问:
How to fix matplotlib installation errors
I do not know how to fix this, any help is appreciated. Thanks in advance
-J

I have tried various ways of installing and importing matplotlib (though command prompt, the text editor I've been using (geany). and neither option has worked. I've also installed the .whl file from https://matplotlib.org/ and it still has not worked (gives the same error)

I originally used the code:

import matplotlib.pyplot as plt
```

<p>in my text editor (<em>geany</em>) to install <em>matplotlib</em> but this gave the error shown below</p>

<p><strong><em>Expected Results:</em></strong></p>

<p>I expect it to import and install the right version of matplotlib (I think the right version for me is matplotlib 3.0 because I'm using python 3.7).</p>

<p><strong><em>Actual Results:</em></strong></p>

<p>When I type 'python -m pip install -U matplotlib' into my command prompt (I'm on windows 10, using python 3.7) it displays: </p>

```WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))': /simple/matplotlib/
```

<p>and repeats the message for a total of 5 times then displays: </p>

```Could not fetch URL https://pypi.org/simple/matplotlib/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/matplotlib/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))) - skipping
```

<p>and finishes with the error: </p>

```ERROR: Could not find a version that satisfies the requirement matplotlib (from versions: none)
ERROR: No matching distribution found for matplotlib
```

I have tried to fix this SSLError but I haven't made any progress in this simply because I don't know where to start.

Thanks again for any help

答:
From this topic:

You should add the pypi host to the list of trusted host. To do so, enter those commands:

```<code>pip install --trusted-host pypi.python.org pytest-xdist
pip install --trusted-host pypi.python.org --upgrade pip
</code>```

Body:
I do not know how to fix this, any help is appreciated. Thanks in advance
-J

I have tried various ways of installing and importing matplotlib (though command prompt, the text editor I've been using (geany). and neither option has worked. I've also installed the .whl file from https://matplotlib.org/ and it still has not worked (gives the same error)

I originally used the code:

import matplotlib.pyplot as plt

in my text editor (geany) to install matplotlib but this gave the error shown below

Expected Results:

I expect it to import and install the right version of matplotlib (I think the right version for me is matplotlib 3.0 because I'm using python 3.7).

Actual Results:

When I type 'python -m pip install -U matplotlib' into my command prompt (I'm on windows 10, using python 3.7) it displays:

WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))': /simple/matplotlib/

and repeats the message for a total of 5 times then displays:

Could not fetch URL https://pypi.org/simple/matplotlib/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/matplotlib/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1056)'))) - skipping

and finishes with the error:

ERROR: Could not find a version that satisfies the requirement matplotlib (from versions: none)
ERROR: No matching distribution found for matplotlib

I have tried to fix this SSLError but I haven't made any progress in this simply because I don't know where to start.

Thanks again for any help

Body:
From this topic:

You should add the pypi host to the list of trusted host. To do so, enter those commands:

pip install --trusted-host pypi.python.org pytest-xdist
pip install --trusted-host pypi.python.org --upgrade pip


来源: stackexchange

问:
Javascript Thousand Separator / string format
Is there any function in Javascript for formatting number and strings ?

I am looking for a way for thousand separator for string or numbers...
(Like String.Format In c#)

答: PHP.js has a function to do this called number_format. If you are familiar with PHP it works exactly the same way.</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
TVS RP-45 roll paper printing
I have a receipt made using Crystal Reports where the page is 4 inch wide and the height should be dynamic. I set the height to 2 inches, because I don't know how to make it dynamic. The printer is a TVS RP-45 Justbill printer.

The printer is ejecting paper after printing. How do I stop this from happening?

Any solution besides Crystal Reports would be helpful. The program is written in C# .NET 2.0 Winforms and connects to a SQL Server 2005 database.

```

Report Header Section
                      Bill no : 101
______________________________________________
Detail Section
Item Code               Qty           Amount
[ItemCode]             [Qty]         [Amount]
______________________________________________
Report Footer Section
Grand Total                      [GrandTotal]
______________________________________________

 ```

The Report Footer Section is using around 2 inches so I set the Height of the paper to 2 inches. This did not solve the problem. The paper height is now 2 times what it should be if there is more than 1 item.

The printer uses roll paper and it should feed more paper proportionally with the number of items sold.

Please help me solve this without wasting paper.

答: Just remove headers and footers, It will work fine.</p>

Title: TVS RP-45 roll paper printing

Body:
I have a receipt made using Crystal Reports where the page is 4 inch wide and the height should be dynamic. I set the height to 2 inches, because I don't know how to make it dynamic. The printer is a TVS RP-45 Justbill printer.

The printer is ejecting paper after printing. How do I stop this from happening?

Any solution besides Crystal Reports would be helpful. The program is written in C# .NET 2.0 Winforms and connects to a SQL Server 2005 database.

Report Header Section
                      Bill no : 101
______________________________________________
Detail Section
Item Code               Qty           Amount
[ItemCode]             [Qty]         [Amount]
______________________________________________
Report Footer Section
Grand Total                      [GrandTotal]
______________________________________________

The Report Footer Section is using around 2 inches so I set the Height of the paper to 2 inches. This did not solve the problem. The paper height is now 2 times what it should be if there is more than 1 item.

The printer uses roll paper and it should feed more paper proportionally with the number of items sold.

Please help me solve this without wasting paper.

ContentLicense: CC BY-SA 4.0


问:
Log4j creating logs in multiple nodes. Want to create a single log in one node
I have a multi-node cluster Spark cluster. I am creating logs using log4j. Logs are getting created but one all the nodes in the cluster. They are also getting created in /tmp directory and not on any other directory. This is

spark2-submit --master yarn --deploy-mode cluster --files /path/log4j.properties --conf "spark.driver.extraJavaOptions=-Dlog4j.configuration=log4j.properties" --conf "spark.executor.extraJavaOptions=-Dlog4j.configuration=log4j.properties" --class com.dataLoad.Load_WF /path/LoadData.jar

How to append all the logs in one log file instead of multiple logs?
How to create logs in directory other than /tmp directory in Linux?
Sample code will be very helpful for understanding.
Much Appreciated.

答:
On a multinode spark cluster, the logs of your applications are written by the spark driver.

if you execute with client mode on node A, logs will be saved on node
A

if you execute with cluster mode, logs will be saved on node where
the spark driver is running.

We had the same problem, the solution we found is to use syslog to centralize the logs of each nodes, for all of our applications on the same node.

On the main node, you have to configure the syslog to be the logs server.
Inside /etc/syslog-ng/, you have to edit syslog-ng.conf to create destinations to save the centralized log files,  :

example :

```<code>@version: 3.5
@include "scl.conf"
@include "`scl-root`/system/tty10.conf"
    options {
        time-reap(30);
        mark-freq(10);
        keep-hostname(yes);
        };
    source s_local { system(); internal(); };

    source s_network {
        syslog(transport(udp) port(514));
        };

    destination df_local2 {
        file(
            "/var/log/MyClusterLogs/myAppLogs.$YEAR-$MONTH-$DAY.log"
            owner("user")
            group("user")
            perm(0777)
            ); };
    filter f_local2 { facility(local2); };
    log { source(s_network); filter(f_local2); destination(df_local2); };
</code>```

And then, change the config in log4j.properties file of the spark application to point on syslog server :

```<code>log4j.rootCategory=INFO,FILE,SYSLOG
log4j.appender.SYSLOG=org.apache.log4j.net.SyslogAppender
log4j.appender.SYSLOG.syslogHost=<syslog_server_ip>
log4j.appender.SYSLOG.layout=org.apache.log4j.PatternLayout
log4j.appender.SYSLOG.layout.conversionPattern=%d{ISO8601} %-5p [%t] %c{2} %x - %m%n
log4j.appender.SYSLOG.Facility=LOCAL2
</code>```

Body:
On a multinode spark cluster, the logs of your applications are written by the spark driver.

if you execute with client mode on node A, logs will be saved on node
A

if you execute with cluster mode, logs will be saved on node where
the spark driver is running.

We had the same problem, the solution we found is to use syslog to centralize the logs of each nodes, for all of our applications on the same node.

On the main node, you have to configure the syslog to be the logs server.
Inside /etc/syslog-ng/, you have to edit syslog-ng.conf to create destinations to save the centralized log files,  :

example :

@version: 3.5
@include "scl.conf"
@include "`scl-root`/system/tty10.conf"
    options {
        time-reap(30);
        mark-freq(10);
        keep-hostname(yes);
        };
    source s_local { system(); internal(); };

    source s_network {
        syslog(transport(udp) port(514));
        };

    destination df_local2 {
        file(
            "/var/log/MyClusterLogs/myAppLogs.$YEAR-$MONTH-$DAY.log"
            owner("user")
            group("user")
            perm(0777)
            ); };
    filter f_local2 { facility(local2); };
    log { source(s_network); filter(f_local2); destination(df_local2); };

And then, change the config in log4j.properties file of the spark application to point on syslog server :

log4j.rootCategory=INFO,FILE,SYSLOG
log4j.appender.SYSLOG=org.apache.log4j.net.SyslogAppender
log4j.appender.SYSLOG.syslogHost=<syslog_server_ip>
log4j.appender.SYSLOG.layout=org.apache.log4j.PatternLayout
log4j.appender.SYSLOG.layout.conversionPattern=%d{ISO8601} %-5p [%t] %c{2} %x - %m%n
log4j.appender.SYSLOG.Facility=LOCAL2


问:
How can i use the value to calculate? "10/10"
Hi i was wondering if i can make the value 10/10 and 90/100 in 4 different var so i can calculate the avarge?

I tried calling the var with innerHTML, but it doesn't seem to work.

This are the div's:

```<code><div class="course_eval_cell hasGrade" smsctip="true">10/10</div>
<div class="course_eval_cell hasGrade">90/100</div>

</code>```

example: 10 + 90 / 10 + 100 => 90.9%. Any suggestion/ideas on how to become this solution?

答:
You need to calculate your average like this.

10/10 which is equal to 100/100. by that means the total is 190/200. so the percentage is 95%

var perc = 0;
var count = 0;
$( ".course_eval_cell" ).each(function( index ) {
  perc += eval($( this ).text());
  count = index+1;
});

console.log((perc/count)*100 + "%")```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="course_eval_cell hasGrade" smsctip="true">10/10</div>
<div class="course_eval_cell hasGrade">90/100</div></code>```

Body:
Hi i was wondering if i can make the value 10/10 and 90/100 in 4 different var so i can calculate the avarge?

I tried calling the var with innerHTML, but it doesn't seem to work.

This are the div's:

10/10

90/100

example: 10 + 90 / 10 + 100 => 90.9%. Any suggestion/ideas on how to become this solution?

Body:
You need to calculate your average like this.

10/10 which is equal to 100/100. by that means the total is 190/200. so the percentage is 95%

var perc = 0;
var count = 0;
$( ".course_eval_cell" ).each(function( index ) {
  perc += eval($( this ).text());
  count = index+1;
});

console.log((perc/count)*100 + "%")

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="course_eval_cell hasGrade" smsctip="true">10/10</div>
<div class="course_eval_cell hasGrade">90/100</div>


问:
React Navigation: Transparent header has no height
If I set headerTransparent: true the other content which was usually rendered below it moves underneath it. How can I avoid that?

My code:

```<code>export class RegisterScreen extends Component {
  static navigationOptions = {
    title: strings.header,
    headerTitleStyle: { color: '#fff' },
    headerTintColor: '#fff',
    headerTransparent: true,
  };
  render() {
    return <Display onSignUpPressed={() => {}} onHelpPressed={() => {}} />;
  }
}
</code>```

With transparent header (it overlaps :( ):

Without transparent header:

I'd like to have the content aligned as if the header had a height. So I want the content to be like in the second picture, but with a transparent header like in the first.

答:
Add headerBackground to navigationOptions like this</p>

```<code>static navigationOptions = {
    title: strings.header,
    headerTitleStyle: { color: '#fff' },
    headerTintColor: '#fff',
    headerTransparent: true,
    headerBackground: Platform.select({
        ios: <BlurView style={{ flex: 1 }} intensity={98} />,
        android: (
          <View style={{ flex: 1, backgroundColor: 'rgba(255,255,255,0.7)' }} />
    ),
  }),
};
</code>```

Body:
If I set headerTransparent: true the other content which was usually rendered below it moves underneath it. How can I avoid that?

My code:

export class RegisterScreen extends Component {
  static navigationOptions = {
    title: strings.header,
    headerTitleStyle: { color: '#fff' },
    headerTintColor: '#fff',
    headerTransparent: true,
  };
  render() {
    return <Display onSignUpPressed={() => {}} onHelpPressed={() => {}} />;
  }
}

With transparent header (it overlaps :( ):

Without transparent header:

I'd like to have the content aligned as if the header had a height. So I want the content to be like in the second picture, but with a transparent header like in the first.

Body:
Add headerBackground to navigationOptions like this

static navigationOptions = {
    title: strings.header,
    headerTitleStyle: { color: '#fff' },
    headerTintColor: '#fff',
    headerTransparent: true,
    headerBackground: Platform.select({
        ios: <BlurView style={{ flex: 1 }} intensity={98} />,
        android: (
          <View style={{ flex: 1, backgroundColor: 'rgba(255,255,255,0.7)' }} />
    ),
  }),
};


问:
How do I get a layer backed NSView to write to PDF in the clipboard
I am using a layer backed view with a CGImage and would like to use the NSView.writePDF(inside:to) API to copy the views image to the clipboard.  The view has subviews that I would like included in the PDF.

I have created a Xcode playground to illustrate the problem.

```<code>//: A Cocoa based Playground to test NSView.writePDF()

import AppKit
import PlaygroundSupport

class BaseView: NSView {

    var isSelected: Bool = false {
        didSet {
            self.needsDisplay = true
        }
    }

    var fillColor = NSColor.yellow

    var cgFillColor: CGColor {
        return self.isSelected ? fillColor.cgColor : fillColor.withAlphaComponent(0.5).cgColor
    }

    var storeLayoutCGImageRef: CGImage? {
        didSet {

            self.layer?.contents = storeLayoutCGImageRef

        }
    }

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)
        guard let context = NSGraphicsContext.current?.cgContext else {
            return
        }

        context.setFillColor(cgFillColor)
        context.fill(dirtyRect)
    }

    override func mouseDown(with theEvent: NSEvent) {

        self.isSelected = !self.isSelected
    }

    @objc func copyImage(_ sender: Any){
         let pb = NSPasteboard.general
        pb.declareTypes([.pdf], owner: self)

        self.writePDF(inside: self.bounds, to: pb)
    }
    @objc func doNothing(_ sender: Any){

    }
    // Load image in the background
    func loadImage(completion: @escaping ()->Void){
        DispatchQueue.global().async {
            if let image = NSImage(named: "B-019969.jpg") {

                // Lets use double the size ?
                var rect = CGRect(x: 0, y: 0, width: image.size.width*3.0, height: image.size.height*3.0)
                let cgImage = image.cgImage(forProposedRect: &rect, context: nil, hints: nil)

                DispatchQueue.main.async {
                    self.storeLayoutCGImageRef = cgImage

                    completion()
                }
                return
            }

            DispatchQueue.main.async {
                //self.storeLayoutImage = nil
                self.storeLayoutCGImageRef = nil
                completion()
            }
        }
    }
}

class ModuleView: BaseView {

    let color = NSColor.purple

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        self.fillColor = color
    }

    required init?(coder decoder: NSCoder) {
         super.init(coder: decoder)
        self.fillColor = color
    }

    override func menu(for event: NSEvent) -> NSMenu? {
        if !isSelected {
            let menu = NSMenu()
            menu.addItem(NSMenuItem(title: "Copy module", action: #selector(copyImage(_:)), keyEquivalent: ""))
            return menu
        } else {
            // Display popup menu
            let menu = NSMenu()
            menu.addItem(NSMenuItem(title: "Copy module", action: #selector(copyImage(_:)), keyEquivalent: ""))
            menu.addItem(NSMenuItem(title: "Do Something", action: #selector(doNothing(_:)), keyEquivalent: ""))
            return menu

        }
    }

}
class ShelfView: BaseView {

    let color = NSColor.yellow

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        self.fillColor = color
        self.loadImage {
            print("Image loaded")
        }
    }
    required init?(coder decoder: NSCoder) {
        super.init(coder: decoder)
        self.fillColor = color
    }
    override func menu(for event: NSEvent) -> NSMenu? {
        if !isSelected {
            let menu = NSMenu()
            menu.addItem(NSMenuItem(title: "Copy shelf", action: #selector(copyImage(_:)), keyEquivalent: ""))
            return menu
        } else {
            // Display popup menu
            let menu = NSMenu()
            menu.addItem(NSMenuItem(title: "Copy shelf", action: #selector(copyImage(_:)), keyEquivalent: ""))
            menu.addItem(NSMenuItem(title: "Do Something", action: #selector(doNothing(_:)), keyEquivalent: ""))
            return menu

        }
    }
    override var wantsUpdateLayer: Bool {
        return true
    }
    override func updateLayer() {
        self.layer?.backgroundColor = self.cgFillColor
        self.layer?.contents = self.storeLayoutCGImageRef
    }
}

class view: BaseView
{

    var module: ModuleView?

    let color = NSColor.cyan

    override init(frame: NSRect)
    {
        super.init(frame: frame)
        self.fillColor = color
        self.addModules()
        self.addShelves()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func addModules(){

        let module = ModuleView()

        module.frame = NSRect(x: 10.0, y: 10.0, width: 180.0, height: 180.0)
        self.module = module
        self.addSubview(module)
    }
    func addShelves(){

        let shelf = ShelfView()

        shelf.frame = NSRect(x: 10.0, y: 10.0, width:160.0, height: 160.0)
        self.module?.addSubview(shelf)
    }

    override func menu(for event: NSEvent) -> NSMenu? {
        if !isSelected {
            let menu = NSMenu()
            menu.addItem(NSMenuItem(title: "Copy fixture", action: #selector(copyImage(_:)), keyEquivalent: ""))
            return menu
        } else {
            // Display popup menu
            let menu = NSMenu()
            menu.addItem(NSMenuItem(title: "Copy fixture", action: #selector(copyImage(_:)), keyEquivalent: ""))
            menu.addItem(NSMenuItem(title: "Do Something", action: #selector(doNothing(_:)), keyEquivalent: ""))
            return menu

        }
    }
}

var v = view(frame: NSRect(x: 0, y: 0, width: 200, height: 200))

PlaygroundPage.current.liveView = v
</code>```

Is there a way to make sure the layer gets included in the PDF output?

答:
OK, I just figured it out - basically you have to implement the draw(_ dirtyRect) function which gets called during printing or when the NSView.writePDF() is called.

Note that the draw() function won't get called under certain conditions - e.g. selecting the item with the mouse will only result in the updateLayer() method being called.

Here is the updated playground, hope this saves someone else some time.

    //: A Cocoa based Playground to test NSView.writePDF()

    import AppKit
    import PlaygroundSupport

    class BaseView: NSView {

        var isSelected: Bool = false {
            didSet {
                self.needsDisplay = true
            }
        }

        var fillColor = NSColor.yellow

        var cgFillColor: CGColor {
            return self.isSelected ? fillColor.cgColor : fillColor.withAlphaComponent(0.5).cgColor
        }

        var storeLayoutCGImageRef: CGImage? {
            didSet {

                self.layer?.contents = storeLayoutCGImageRef

            }
        }

        var image: CGImage?

        override func draw(_ dirtyRect: NSRect) {
            super.draw(dirtyRect)
            guard let context = NSGraphicsContext.current?.cgContext else {
                return
            }
            // NB THIS PART !!
            self.layer?.render(in:context)
        }

        override func mouseDown(with theEvent: NSEvent) {

            self.isSelected = !self.isSelected
        }

        @objc func copyImage(_ sender: Any){
             let pb = NSPasteboard.general
            pb.declareTypes([.pdf], owner: self)

            self.writePDF(inside: self.bounds, to: pb)
        }
        @objc func doNothing(_ sender: Any){

        }
        // Load image in the background
        func loadImage(completion: @escaping ()->Void){
            DispatchQueue.global().async {
                if let image = NSImage(named: "Sample Image.png") {

                    // Lets use double the size ?
                    var rect = CGRect(x: 0, y: 0, width: image.size.width*3.0, height: image.size.height*3.0)
                    let cgImage = image.cgImage(forProposedRect: &rect, context: nil, hints: nil)

                    DispatchQueue.main.async {
                        self.storeLayoutCGImageRef = cgImage

                        completion()
                    }
                    return
                }

                DispatchQueue.main.async {
                    //self.storeLayoutImage = nil
                    self.storeLayoutCGImageRef = nil
                    completion()
                }
            }
        }
    }

    class ModuleView: BaseView {

        let color = NSColor.purple

        override init(frame frameRect: NSRect) {
            super.init(frame: frameRect)
            self.fillColor = color
        }

        required init?(coder decoder: NSCoder) {
             super.init(coder: decoder)
            self.fillColor = color
        }

        override func menu(for event: NSEvent) -> NSMenu? {
            if !isSelected {
                let menu = NSMenu()
                menu.addItem(NSMenuItem(title: "Copy module", action: #selector(copyImage(_:)), keyEquivalent: ""))
                return menu
            } else {
                // Display popup menu
                let menu = NSMenu()
                menu.addItem(NSMenuItem(title: "Copy module", action: #selector(copyImage(_:)), keyEquivalent: ""))
                menu.addItem(NSMenuItem(title: "Do Something", action: #selector(doNothing(_:)), keyEquivalent: ""))
                return menu

            }
        }

    }
    class ShelfView: BaseView {

        let color = NSColor.green

        override init(frame frameRect: NSRect) {
            super.init(frame: frameRect)
            self.fillColor = color
            self.loadImage {
                print("Image loaded")
            }
        }
        required init?(coder decoder: NSCoder) {
            super.init(coder: decoder)
            self.fillColor = color
        }
        override func menu(for event: NSEvent) -> NSMenu? {
            if !isSelected {
                let menu = NSMenu()
                menu.addItem(NSMenuItem(title: "Copy shelf", action: #selector(copyImage(_:)), keyEquivalent: ""))
                return menu
            } else {
                // Display popup menu
                let menu = NSMenu()
                menu.addItem(NSMenuItem(title: "Copy shelf", action: #selector(copyImage(_:)), keyEquivalent: ""))
                menu.addItem(NSMenuItem(title: "Do Something", action: #selector(doNothing(_:)), keyEquivalent: ""))
                return menu

            }
        }

        override func draw(_ dirtyRect: NSRect) {
            print("ShelfView.draw() called")
            super.draw(dirtyRect)
            guard let context = NSGraphicsContext.current?.cgContext else {
                return
            }
            if let image = self.storeLayoutCGImageRef {
                context.draw(image, in: self.bounds)
            }
        }

        override var wantsUpdateLayer: Bool {
            return true
        }
        override func updateLayer() {
            print("updateLayer() called")
            self.layer?.backgroundColor = self.cgFillColor
            self.layer?.contents = self.storeLayoutCGImageRef

        }
    }

    class view: BaseView
    {

        var module: ModuleView?

        let color = NSColor.cyan

        override init(frame: NSRect)
        {
            super.init(frame: frame)
            self.fillColor = color
            self.addModules()
            self.addShelves()
        }

        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }

        func addModules(){

            let module = ModuleView()

            module.frame = NSRect(x: 10.0, y: 10.0, width: 180.0, height: 180.0)
            self.module = module
            self.addSubview(module)
        }
        func addShelves(){

            let shelf = ShelfView()

            shelf.frame = NSRect(x: 10.0, y: 10.0, width:160.0, height: 160.0)
            self.module?.addSubview(shelf)
        }

        override func menu(for event: NSEvent) -> NSMenu? {
            if !isSelected {
                let menu = NSMenu()
                menu.addItem(NSMenuItem(title: "Copy fixture", action: #selector(copyImage(_:)), keyEquivalent: ""))
                return menu
            } else {
                // Display popup menu
                let menu = NSMenu()
                menu.addItem(NSMenuItem(title: "Copy fixture", action: #selector(copyImage(_:)), keyEquivalent: ""))
                menu.addItem(NSMenuItem(title: "Do Something", action: #selector(doNothing(_:)), keyEquivalent: ""))
                return menu

            }
        }
    }

    var v = view(frame: NSRect(x: 0, y: 0, width: 200, height: 200))

    PlaygroundPage.current.liveView = v

```

Body:
I am using a layer backed view with a CGImage and would like to use the NSView.writePDF(inside:to) API to copy the views image to the clipboard.  The view has subviews that I would like included in the PDF.

I have created a Xcode playground to illustrate the problem.

//: A Cocoa based Playground to test NSView.writePDF()

import AppKit
import PlaygroundSupport

class BaseView: NSView {

    var isSelected: Bool = false {
        didSet {
            self.needsDisplay = true
        }
    }

    var fillColor = NSColor.yellow

    var cgFillColor: CGColor {
        return self.isSelected ? fillColor.cgColor : fillColor.withAlphaComponent(0.5).cgColor
    }

    var storeLayoutCGImageRef: CGImage? {
        didSet {

            self.layer?.contents = storeLayoutCGImageRef

        }
    }

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)
        guard let context = NSGraphicsContext.current?.cgContext else {
            return
        }

        context.setFillColor(cgFillColor)
        context.fill(dirtyRect)
    }

    override func mouseDown(with theEvent: NSEvent) {

        self.isSelected = !self.isSelected
    }

    @objc func copyImage(_ sender: Any){
         let pb = NSPasteboard.general
        pb.declareTypes([.pdf], owner: self)

        self.writePDF(inside: self.bounds, to: pb)
    }
    @objc func doNothing(_ sender: Any){

    }
    // Load image in the background
    func loadImage(completion: @escaping ()->Void){
        DispatchQueue.global().async {
            if let image = NSImage(named: "B-019969.jpg") {

                // Lets use double the size ?
                var rect = CGRect(x: 0, y: 0, width: image.size.width*3.0, height: image.size.height*3.0)
                let cgImage = image.cgImage(forProposedRect: &rect, context: nil, hints: nil)

                DispatchQueue.main.async {
                    self.storeLayoutCGImageRef = cgImage

                    completion()
                }
                return
            }

            DispatchQueue.main.async {
                //self.storeLayoutImage = nil
                self.storeLayoutCGImageRef = nil
                completion()
            }
        }
    }
}

class ModuleView: BaseView {

    let color = NSColor.purple

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        self.fillColor = color
    }

    required init?(coder decoder: NSCoder) {
         super.init(coder: decoder)
        self.fillColor = color
    }

    override func menu(for event: NSEvent) -> NSMenu? {
        if !isSelected {
            let menu = NSMenu()
            menu.addItem(NSMenuItem(title: "Copy module", action: #selector(copyImage(_:)), keyEquivalent: ""))
            return menu
        } else {
            // Display popup menu
            let menu = NSMenu()
            menu.addItem(NSMenuItem(title: "Copy module", action: #selector(copyImage(_:)), keyEquivalent: ""))
            menu.addItem(NSMenuItem(title: "Do Something", action: #selector(doNothing(_:)), keyEquivalent: ""))
            return menu

        }
    }

}
class ShelfView: BaseView {

    let color = NSColor.yellow

    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        self.fillColor = color
        self.loadImage {
            print("Image loaded")
        }
    }
    required init?(coder decoder: NSCoder) {
        super.init(coder: decoder)
        self.fillColor = color
    }
    override func menu(for event: NSEvent) -> NSMenu? {
        if !isSelected {
            let menu = NSMenu()
            menu.addItem(NSMenuItem(title: "Copy shelf", action: #selector(copyImage(_:)), keyEquivalent: ""))
            return menu
        } else {
            // Display popup menu
            let menu = NSMenu()
            menu.addItem(NSMenuItem(title: "Copy shelf", action: #selector(copyImage(_:)), keyEquivalent: ""))
            menu.addItem(NSMenuItem(title: "Do Something", action: #selector(doNothing(_:)), keyEquivalent: ""))
            return menu

        }
    }
    override var wantsUpdateLayer: Bool {
        return true
    }
    override func updateLayer() {
        self.layer?.backgroundColor = self.cgFillColor
        self.layer?.contents = self.storeLayoutCGImageRef
    }
}

class view: BaseView
{

    var module: ModuleView?

    let color = NSColor.cyan

    override init(frame: NSRect)
    {
        super.init(frame: frame)
        self.fillColor = color
        self.addModules()
        self.addShelves()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func addModules(){

        let module = ModuleView()

        module.frame = NSRect(x: 10.0, y: 10.0, width: 180.0, height: 180.0)
        self.module = module
        self.addSubview(module)
    }
    func addShelves(){

        let shelf = ShelfView()

        shelf.frame = NSRect(x: 10.0, y: 10.0, width:160.0, height: 160.0)
        self.module?.addSubview(shelf)
    }

    override func menu(for event: NSEvent) -> NSMenu? {
        if !isSelected {
            let menu = NSMenu()
            menu.addItem(NSMenuItem(title: "Copy fixture", action: #selector(copyImage(_:)), keyEquivalent: ""))
            return menu
        } else {
            // Display popup menu
            let menu = NSMenu()
            menu.addItem(NSMenuItem(title: "Copy fixture", action: #selector(copyImage(_:)), keyEquivalent: ""))
            menu.addItem(NSMenuItem(title: "Do Something", action: #selector(doNothing(_:)), keyEquivalent: ""))
            return menu

        }
    }
}

var v = view(frame: NSRect(x: 0, y: 0, width: 200, height: 200))

PlaygroundPage.current.liveView = v

Is there a way to make sure the layer gets included in the PDF output?


问:
Check is service running within laravel
If I am using Laravel Scheduler and Laravel Echo Server.

```<code>$schedule->exec('laravel-echo-server start')
         ->everyMinute()
         ->onSuccess(function () {
             // send logs
         })
         ->onFailure(function () {
             // send failure message and retry
         });
</code>```

Is there a way to check is laravel-echo-server active or down?
I saw that I could use supervisor to auto-restart services etc.
Is there a way to do it within laravel without supervisor or any other similar program?

答:
You might wanna check if the port occupied. It's a solid way of checking such services.

Something like netstat -tulpn | grep LISTEN would give you the list of used ports, then you can simply check for the port.

Title: Check is service running within laravel

Body:
If I am using Laravel Scheduler and Laravel Echo Server.

$schedule->exec('laravel-echo-server start')
         ->everyMinute()
         ->onSuccess(function () {
             // send logs
         })
         ->onFailure(function () {
             // send failure message and retry
         });

Is there a way to check is laravel-echo-server active or down?
I saw that I could use supervisor to auto-restart services etc.
Is there a way to do it within laravel without supervisor or any other similar program?


问:
Get SSL Certificate 'Issued to'
I want to know how can I get Local Computer SSL certificates Issued to field values. I used this command to show all SSL certificates informations but it did not show me Issued To field

GET-CHILDITEM -Path 'Cert:\LocalMachine\' –RECURSE | FORMAT-LIST –PROPERTY *

答:
IssuedTo field seems to be dynamically generated by certmgr.msc based on Subject field.

The closest I got based on certificates I have installed on my machine was something like that:

```<code>$CertsDetail = Get-ChildItem -Path 'Cert:\LocalMachine\' –Recurse
$CertsDetail | select @{n="IssuedTo";e={(($_.Subject -split ",") |? {$_ -like "CN=*"}) -replace "CN="}}
</code>```

What I did was to use calculated property to find first CN= part in Subject and then to remove that CN= part. For sure that doesn't cover all the possible scenarios but you can use it as starting point.

Title: Get SSL Certificate 'Issued to'

Body:
IssuedTo field seems to be dynamically generated by certmgr.msc based on Subject field.

The closest I got based on certificates I have installed on my machine was something like that:

$CertsDetail = Get-ChildItem -Path 'Cert:\LocalMachine\' –Recurse
$CertsDetail | select @{n="IssuedTo";e={(($_.Subject -split ",") |? {$_ -like "CN=*"}) -replace "CN="}}

What I did was to use calculated property to find first CN= part in Subject and then to remove that CN= part. For sure that doesn't cover all the possible scenarios but you can use it as starting point.


问:
how can i change the checkbox attribute which are in the 9th column of a table
How to modify the checkbox attribute (checkbok in the 9th cells of the table MyTab) ?

MyTab contains 9 columns and the last is a checkbox.

None of the following code is working.

```<code>$('#MyTab tr').filter(':visible').each(function( index,element) {

     element.cells[8].attr('checked', true);

     $(this).attr('checked',true);

     $(this).prop('checked',true);

     $(element "input[type='checkbox']").attr('checked',true) ;

     element.cells[8].attr('checked', true);

     element.cells[8].prop('checked', true);

 });

HTML part = exemple with one row =
<table id="MyTab"  border=0 width=1400 cellspacing=2 cellpadding=2 class="table" >
<tr class='impair' onMouseOver="this.className='ModuleCorpsColorOver';" onMouseOut="this.className='impair';">
   <td>USER</td>
   <td>964469597</td>
   <td>17231215</td>
   <td>450,60</td>
   <td>22-11-18</td>
   <td>08-10-18</td>
   <td>DOCUMENT1</td>
   <td>LIBELLE1</td>
   <td><input type='checkbox' class='inputNoBord' name='upd_statut[]' value='1' enable></td>
</tr>

<tr>
    ....
</tr>
</table>

I am also using following jquery =
<script src="../lib/jquery-1.11.1.min.js"></script>
<script src="../lib/sorttable.js"></script>
<script src="../lib/jquery.filtertable.min.js"></script>
</code>```

答:
$(this).find("td:first input:checkbox").prop("checked",true);
could you try like this..

Body:
How to modify the checkbox attribute (checkbok in the 9th cells of the table MyTab) ?

MyTab contains 9 columns and the last is a checkbox.

None of the following code is working.

$('#MyTab tr').filter(':visible').each(function( index,element) {

     element.cells[8].attr('checked', true);

     $(this).attr('checked',true);

     $(this).prop('checked',true);

     $(element "input[type='checkbox']").attr('checked',true) ;

     element.cells[8].attr('checked', true);

     element.cells[8].prop('checked', true);

 });

HTML part = exemple with one row =

   USER
   964469597
   17231215
   450,60
   22-11-18
   08-10-18
   DOCUMENT1
   LIBELLE1
   <input type='checkbox' class='inputNoBord' name='upd_statut[]' value='1' enable>

    ....

I am also using following jquery =


问:
Vector option in Java
I am using vector of object. My issue is the removal from vector is expensive operation( O(n^2)). What would be the replacement of vector in Java. In my uses addition and removal is extensively happens.

i am C++ person don't know much Java

答:
Well, Vector class shouldn't be used. There are so many containers available in Java. Few of them:

ArrayList is good for random access, but is bad for inserting or removing from the middle of the list.

LinkedList is bad for random access, but is fair good for iterating and adding/removing elements from the middle of container.

Title: Vector option in Java


问:
Jquery Span click find next div
I try to toogle div class from a span click i tried

```<code>$(this).closest(".div").find(".list-type-demandes").toggle();
</code>```

but it doesn't work.

if i use :

```<code>$(".list-type-demandes").toggle();
</code>```

it's works but it's showing me the two div and i need to display the div from "this" span

here HTML  :

```<code><label style="color: #1c5081">
        <span id="toolbar-open" name="toolbar_open" class="toogle-toobar-open" onclick="toogleListTypeDemande(this)"><b>+</b>
        </span> Organisation, support et services
      </label>

      <div class="list-type-demandes" style="padding-left: ; display: none">
         <label style="display: inline">
         <input type="radio" class="checkbox_type_demande" data-appel-projet="474" name="appel_projet[type_demande_list]" value="54" id="appel_projet_type_demande_list_54"> Architecture d'entreprise
        </label>
      </div>

      <label style="color: #1c5081">
        <span id="toolbar-open" name="toolbar_open" class="toogle-toobar-open" onclick="toogleListTypeDemande(this)"><b>+</b></span> Applications
      </label>

      <div class="list-type-demandes" style="padding-left: ; display: none">
        <label style="display: inline">
        <input type="radio" class="checkbox_type_demande" data-appel-projet="474" name="appel_projet[type_demande_list]" value="52" id="appel_projet_type_demande_list_52"> Système d'information activités recherche
        </label>
      </div>
</code>```

here the script :

```<code>function toogleListTypeDemande(element) {
        $(this).closest(".div").find(".list-type-demandes").toggle();
    }
</code>```

答:
You need to modify toogleListTypeDemande(element) just a little.

Javascript offers the attribute nextElementSibling to get the next html element. Unfortunately there is no next sibling to your span element. So we need to travel one node back to get it's parent element.parentNode - which is the label - and from there the next sibling is the div.

```<code>function toogleListTypeDemande(element) {
        $(element.parentNode.nextElementSibling).toggle();
    }
</code>```

Title: Jquery Span click find next div

Body:
I try to toogle div class from a span click i tried

$(this).closest(".div").find(".list-type-demandes").toggle();

but it doesn't work.

if i use :

$(".list-type-demandes").toggle();

it's works but it's showing me the two div and i need to display the div from "this" span

here HTML  :

        +
         Organisation, support et services

         <input type="radio" class="checkbox_type_demande" data-appel-projet="474" name="appel_projet[type_demande_list]" value="54" id="appel_projet_type_demande_list_54"> Architecture d'entreprise

        + Applications

        <input type="radio" class="checkbox_type_demande" data-appel-projet="474" name="appel_projet[type_demande_list]" value="52" id="appel_projet_type_demande_list_52"> Système d'information activités recherche

here the script :

function toogleListTypeDemande(element) {
        $(this).closest(".div").find(".list-type-demandes").toggle();
    }

Body:
You need to modify toogleListTypeDemande(element) just a little.

Javascript offers the attribute nextElementSibling to get the next html element. Unfortunately there is no next sibling to your span element. So we need to travel one node back to get it's parent element.parentNode - which is the label - and from there the next sibling is the div.

function toogleListTypeDemande(element) {
        $(element.parentNode.nextElementSibling).toggle();
    }


问:
Angular 2 FormGroup Add Validators dynamic
i'm tring to add validator to FormContol dynamic (not on initialization) and it's not work....

the code:

this.formGroup.controls["firstName"].validator = Validators.Required;```

Did anyone do it?

答:
I ended up using:

```<code>export function getValidatorFnArray(obj): ValidatorFn[] {

  const validators = [];

  if (obj.required || obj.required === '' ) {
    validators.push(Validators.required);
  }
  if (obj.minLength) {
    validators.push(Validators.minLength(parseInt(obj.minLength, 10)));
  }
  if (obj.maxLength) {
    validators.push(Validators.maxLength(parseInt(obj.maxLength, 10)));
  }
  if (obj.pattern) {
    validators.push(Validators.pattern(obj.pattern));
  }
  if (obj.email || obj.email === '') {
    validators.push(Validators.email);
  }

  return validators
}
</code>```

where obj could be something like:

```<code>validation: {
  required: '',
  pattern: '\d+',
}
</code>```

Body:
i'm tring to add validator to FormContol dynamic (not on initialization) and it's not work....

the code:

this.formGroup.controls["firstName"].validator = Validators.Required;

Did anyone do it?

Body:
I ended up using:

export function getValidatorFnArray(obj): ValidatorFn[] {

  const validators = [];

  if (obj.required || obj.required === '' ) {
    validators.push(Validators.required);
  }
  if (obj.minLength) {
    validators.push(Validators.minLength(parseInt(obj.minLength, 10)));
  }
  if (obj.maxLength) {
    validators.push(Validators.maxLength(parseInt(obj.maxLength, 10)));
  }
  if (obj.pattern) {
    validators.push(Validators.pattern(obj.pattern));
  }
  if (obj.email || obj.email === '') {
    validators.push(Validators.email);
  }

  return validators
}

where obj could be something like:

validation: {
  required: '',
  pattern: '\d+',
}


问:
react if statement in jsx and map
i have working code and little problem with if statement in map function here is code

```<code>    const SortableItem = SortableElement(CashItem);
const SortableList = SortableContainer(({items}) => {
  return (
    <div>
      {items.map((cashitem, index) => (
        <SortableItem key={`item-${index}`}
          index={index}
          isPayed={cashitem.isPayed}
          date={cashitem.date}
          name={cashitem.name}
          realisticVal={cashitem.realisticVal}
          realisticBalance={cashitem.realisticBalance}
          optimisticBalance={cashitem.optimisticBalance}
          optimisticVal={cashitem.optimisticVal}
          changedName={(event) => this.nameChangedHandler(event, cashitem.id)}
          isBlocked={(event) => this.handleChangeCheckbox(event, cashitem.id)}
          delete={(event) => this.removeItem(event, cashitem.id)}
          addNext={(event) => this.addNext(event, cashitem)}
          realisticChange={(event) => this.realisticBalanceChangedHandler(event, cashitem.id)}
          optimisticChange={(event) => this.optimisticBalanceChangedHandler(event, cashitem.id)}
          dateChangedHandler={(event) => this.dateChangedHandler(event, cashitem.id)}
         />
      ))}
    </div>
  );
});
</code>```

now i want chceck if statement to render only  when in map cashitem has state is visible cashitems isVisible already have isVisible:true or false i want to do something like that

```<code> const SortableItem = SortableElement(CashItem);
const SortableList = SortableContainer(({items}) => {
  return (
    <div>
      {items.map((cashitem, index) => (
        if(cashitem.isVisible===true){
          <SortableItem key={`item-${index}`}
          index={index}
          isPayed={cashitem.isPayed}
          date={cashitem.date}
          name={cashitem.name}
          realisticVal={cashitem.realisticVal}
          realisticBalance={cashitem.realisticBalance}
          optimisticBalance={cashitem.optimisticBalance}
          optimisticVal={cashitem.optimisticVal}
          changedName={(event) => this.nameChangedHandler(event, cashitem.id)}
          isBlocked={(event) => this.handleChangeCheckbox(event, cashitem.id)}
          delete={(event) => this.removeItem(event, cashitem.id)}
          addNext={(event) => this.addNext(event, cashitem)}
          realisticChange={(event) => this.realisticBalanceChangedHandler(event, cashitem.id)}
          optimisticChange={(event) => this.optimisticBalanceChangedHandler(event, cashitem.id)}
          dateChangedHandler={(event) => this.dateChangedHandler(event, cashitem.id)}
         />
        }

      ))}
    </div>
  );
});
</code>```

答:
Create a function that handle the if/else statement and return the jsx/html builder, then call it in the jsx render() function.

Check this solution/ author: Blair Anderson

```<code>renderSkillSection: function(){
  if (this.state.challengeChoices.length < 0) {
    return this.state.challengeChoices.map((para2, i) =>
         <ChallengeSkill key={i} {...para2} callback={this.madeSelection} />)
  }
  else {
    return <div>Hello world</div>
  }
},

render: function(){
 return (<div className="skillSection">
  {this.renderSkillSection()}
 </div>)
}
</code>```

Title: react if statement in jsx and map

Body:
i have working code and little problem with if statement in map function here is code

    const SortableItem = SortableElement(CashItem);
const SortableList = SortableContainer(({items}) => {
  return (

      {items.map((cashitem, index) => (
        <SortableItem key={`item-${index}`}
          index={index}
          isPayed={cashitem.isPayed}
          date={cashitem.date}
          name={cashitem.name}
          realisticVal={cashitem.realisticVal}
          realisticBalance={cashitem.realisticBalance}
          optimisticBalance={cashitem.optimisticBalance}
          optimisticVal={cashitem.optimisticVal}
          changedName={(event) => this.nameChangedHandler(event, cashitem.id)}
          isBlocked={(event) => this.handleChangeCheckbox(event, cashitem.id)}
          delete={(event) => this.removeItem(event, cashitem.id)}
          addNext={(event) => this.addNext(event, cashitem)}
          realisticChange={(event) => this.realisticBalanceChangedHandler(event, cashitem.id)}
          optimisticChange={(event) => this.optimisticBalanceChangedHandler(event, cashitem.id)}
          dateChangedHandler={(event) => this.dateChangedHandler(event, cashitem.id)}
         />
      ))}

  );
});

now i want chceck if statement to render only  when in map cashitem has state is visible cashitems isVisible already have isVisible:true or false i want to do something like that

 const SortableItem = SortableElement(CashItem);
const SortableList = SortableContainer(({items}) => {
  return (

      {items.map((cashitem, index) => (
        if(cashitem.isVisible===true){
          <SortableItem key={`item-${index}`}
          index={index}
          isPayed={cashitem.isPayed}
          date={cashitem.date}
          name={cashitem.name}
          realisticVal={cashitem.realisticVal}
          realisticBalance={cashitem.realisticBalance}
          optimisticBalance={cashitem.optimisticBalance}
          optimisticVal={cashitem.optimisticVal}
          changedName={(event) => this.nameChangedHandler(event, cashitem.id)}
          isBlocked={(event) => this.handleChangeCheckbox(event, cashitem.id)}
          delete={(event) => this.removeItem(event, cashitem.id)}
          addNext={(event) => this.addNext(event, cashitem)}
          realisticChange={(event) => this.realisticBalanceChangedHandler(event, cashitem.id)}
          optimisticChange={(event) => this.optimisticBalanceChangedHandler(event, cashitem.id)}
          dateChangedHandler={(event) => this.dateChangedHandler(event, cashitem.id)}
         />
        }

      ))}

  );
});

Body:
Create a function that handle the if/else statement and return the jsx/html builder, then call it in the jsx render() function.

Check this solution/ author: Blair Anderson

renderSkillSection: function(){
  if (this.state.challengeChoices.length < 0) {
    return this.state.challengeChoices.map((para2, i) =>
         <ChallengeSkill key={i} {...para2} callback={this.madeSelection} />)
  }
  else {
    return <div>Hello world</div>
  }
},

render: function(){
 return (<div className="skillSection">
  {this.renderSkillSection()}
 </div>)
}


问:
Is there a way of hiding the telephone country code in Android Studio
I need to add a country code to phone numbers to dial it from Android, but I would like to display the phone numbers without the country code. I can get the dialler working using setText() for the phone number (with country code) in Java and adding Autolink in the XML.

However I can't seem to find a way of displaying the phone number without the country code i.e. when using href= you can have different text to the actual hyperlink.

So I want to display 01234 567890, but dial +441234567890.

I've tried using this HTML in a string but it doesn't work:

```<code><a href="tel:+441234567890">01234 567890</a>
</code>```

答:
Use a ClickableSpan:

```<code>final SpannableString span = new SpannableString("01234 567890");
final ClickableSpan onClick = new ClickableSpan() {
    @Override
    public void onClick(View textView) {
        //Launch your Intent to dial the number, with whatever number you like
    }
    @Override
    public void updateDrawState(TextPaint ds) {
        super.updateDrawState(ds);
    }
};
span.setSpan(onClick, 0, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

final TextView tv = (TextView) findViewById(R.id.text_view);
tv.setText(span);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setHighlightColor(Color.GREEN);
</code>```

You may need to add clickable:true in your XML as well.

Or, if your TextView just contains the number, you can set a click listener on the entire TextView and launch your dial from there

Body:
I need to add a country code to phone numbers to dial it from Android, but I would like to display the phone numbers without the country code. I can get the dialler working using setText() for the phone number (with country code) in Java and adding Autolink in the XML.

However I can't seem to find a way of displaying the phone number without the country code i.e. when using <a href= you can have different text to the actual hyperlink.

So I want to display 01234 567890, but dial +441234567890.

I've tried using this HTML in a string but it doesn't work:

01234 567890

Body:
Use a ClickableSpan:

final SpannableString span = new SpannableString("01234 567890");
final ClickableSpan onClick = new ClickableSpan() {
    @Override
    public void onClick(View textView) {
        //Launch your Intent to dial the number, with whatever number you like
    }
    @Override
    public void updateDrawState(TextPaint ds) {
        super.updateDrawState(ds);
    }
};
span.setSpan(onClick, 0, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

final TextView tv = (TextView) findViewById(R.id.text_view);
tv.setText(span);
textView.setMovementMethod(LinkMovementMethod.getInstance());
textView.setHighlightColor(Color.GREEN);

You may need to add clickable:true in your XML as well.

Or, if your TextView just contains the number, you can set a click listener on the entire TextView and launch your dial from there


问:
Use apply on a data class in Kotlin
I know how to use the apply function on a normal Kotlin class but have not been able to use it with a data class:

```<code>data class Person(name: String)

val person = Person().apply {
    name = "Tony Stark"
}
</code>```

I get a compile message of:

No value passed for parameter 'name'

答:
The issue is that name is a constructor parameter only and not made a property, which is invalid for the data class concept anyway. Fix like this:

```<code>data class Person(val name: String)
</code>```

Title: Use apply on a data class in Kotlin

Body:
I know how to use the apply function on a normal Kotlin class but have not been able to use it with a data class:

data class Person(name: String)

val person = Person().apply {
    name = "Tony Stark"
}

I get a compile message of:

No value passed for parameter 'name'

Body:
The issue is that name is a constructor parameter only and not made a property, which is invalid for the data class concept anyway. Fix like this:

data class Person(val name: String)


问:
How to fix this error "Impossible to connect, please check your Algolia Application Id"?
I have everything correct, as written at laravel/algolia websites.

I tried to read lot of documentations and tutorials about Laravel Scout installation, but still can't find solution.

I have everything correct in my settings and also APIs are correct but still getting this error:

Impossible to connect, please check your Algolia Application Id.

答:
Apparently on the issue came from on wrong credentials, this can occurs providing the wrong Application ID or Admin API Key. Also the correct way to provide the credential on scout.php is :

```<code>'algolia' => [
'id' => env('ALGOLIA_APP_ID', ''),
'secret' => env('ALGOLIA_SECRET', '')
],
</code>```

And then fill your credentials in your .env file.

I'd recommend you to run php artisan config:clear in case you have cached your configuration (which you shouldn't do in dev env).

Let us know if it solve your issue.

Body:
Apparently on the issue came from on wrong credentials, this can occurs providing the wrong Application ID or Admin API Key. Also the correct way to provide the credential on scout.php is :

'algolia' => [
'id' => env('ALGOLIA_APP_ID', ''),
'secret' => env('ALGOLIA_SECRET', '')
],

And then fill your credentials in your .env file.

I'd recommend you to run php artisan config:clear in case you have cached your configuration (which you shouldn't do in dev env).

Let us know if it solve your issue.


问:
What is the correct way to embed Wyam into an asp.net core MVC solution?
What is the correct way to embed Wyam into and asp.net core MVC solution?

As the project needs advanced authentication, I've embedded it in MVC.
I am currently embedding it with an MVC controller reading generated html files with a controller and rendering it through a view.

The files are served in the following way

```<code>public IActionResult Index()
{
    return ServeMarkdownPage("index");
}

[Route("{pageName}")]
public IActionResult ServeMarkdownPage([FromRoute]string pageName)
{
     if (!System.IO.File.Exists($"HtmlOutput//{pageName}.html"))
     {
         return View("Error");
     }

     var content = System.IO.File.ReadAllText($"HtmlOutput//{pageName}.html");

     return View("MarkdownPage", new MarkdownPageViewModel { HtmlContent = content });
}
</code>```

The view just outputs the html content into the page.

```<code>@Html.Raw(Model.HtmlContent)
</code>```

Markdown generation is done with instantiation of the engine instance and transforming it into html.
The waym recipe seems to be ignored in this case.

```<code>var engine = new Wyam.Core.Execution.Engine();

engine.FileSystem.InputPaths.Add(new DirectoryPath("Markdown"));
engine.FileSystem.OutputPath = new DirectoryPath("HtmlOutput");

engine.Pipelines.Add(new Pipeline(
    "DocumentationPages",
    new ReadFiles("**/*.md"),
    new FrontMatter(new Yaml()),
    new Markdown(),
    new WriteFiles(".html")));

var docsRecipe = new Docs();

docsRecipe.Apply(engine);
</code>```

Can this be done in a better way? Is the recipe correctly invocated?

答:
According to the docs

https://wyam.io/docs/usage/embedding

While Wyam is usually executed from the command line application, this is just a thin wrapper around a core library that you can include in your own applications. The core Wyam library is available on NuGet as Wyam.Core. Once you've included it in your application, you will need to create an instance of the Wyam.Core.Execution.Engine class.

To configure the engine, you use the properties of the Engine class.

  ...

  ...

  Once the engine is configured, execute it with a call to Engine.Execute(). This will start evaluation of the pipelines and any output messages will be sent to the configured trace endpoints.

So ideally since you are embedding it, you will have to manually start the process of generation.

You can create a simple helper to manage that for you.

```<code>public static class WyamConfiguration {
    public static void Embed(Action<Wyam.Core.Execution.Engine> configure) {
        // you will need to create an instance of the Wyam.Core.Execution.Engine class
        var engine = new Wyam.Core.Execution.Engine();
        // configure the engine
        configure(engine);
        // Once the engine is configured, execute it with a call to Engine.Execute()
        // This will start evaluation of the pipelines and any output messages will
        // be sent to the configured trace endpoints.
        engine.Execute();
    }
}
</code>```

And call that from your Startup.cs

For example

```<code>WyamConfiguration.Embed(engine => {
    engine.FileSystem.InputPaths.Add(new DirectoryPath("Markdown"));
    engine.FileSystem.OutputPath = new DirectoryPath("HtmlOutput");

    engine.Pipelines.Add(new Pipeline(
        "DocumentationPages",
        new ReadFiles("**/*.md"),
        new FrontMatter(new Yaml()),
        new Markdown(),
        new WriteFiles(".html")));

    var docsRecipe = new Docs();

    docsRecipe.Apply(engine);
});
</code>```

Body:
What is the correct way to embed Wyam into and asp.net core MVC solution?

As the project needs advanced authentication, I've embedded it in MVC.
I am currently embedding it with an MVC controller reading generated html files with a controller and rendering it through a view.

The files are served in the following way

public IActionResult Index()
{
    return ServeMarkdownPage("index");
}

[Route("{pageName}")]
public IActionResult ServeMarkdownPage([FromRoute]string pageName)
{
     if (!System.IO.File.Exists($"HtmlOutput//{pageName}.html"))
     {
         return View("Error");
     }

     var content = System.IO.File.ReadAllText($"HtmlOutput//{pageName}.html");

     return View("MarkdownPage", new MarkdownPageViewModel { HtmlContent = content });
}

The view just outputs the html content into the page.

@Html.Raw(Model.HtmlContent)

Markdown generation is done with instantiation of the engine instance and transforming it into html.
The waym recipe seems to be ignored in this case.

var engine = new Wyam.Core.Execution.Engine();

engine.FileSystem.InputPaths.Add(new DirectoryPath("Markdown"));
engine.FileSystem.OutputPath = new DirectoryPath("HtmlOutput");

engine.Pipelines.Add(new Pipeline(
    "DocumentationPages",
    new ReadFiles("**/*.md"),
    new FrontMatter(new Yaml()),
    new Markdown(),
    new WriteFiles(".html")));

var docsRecipe = new Docs();

docsRecipe.Apply(engine);

Can this be done in a better way? Is the recipe correctly invocated?

Body:
According to the docs

https://wyam.io/docs/usage/embedding

While Wyam is usually executed from the command line application, this is just a thin wrapper around a core library that you can include in your own applications. The core Wyam library is available on NuGet as Wyam.Core. Once you've included it in your application, you will need to create an instance of the Wyam.Core.Execution.Engine class.

To configure the engine, you use the properties of the Engine class.

  ...

  ...

  Once the engine is configured, execute it with a call to Engine.Execute(). This will start evaluation of the pipelines and any output messages will be sent to the configured trace endpoints.

So ideally since you are embedding it, you will have to manually start the process of generation.

You can create a simple helper to manage that for you.

public static class WyamConfiguration {
    public static void Embed(Action<Wyam.Core.Execution.Engine> configure) {
        // you will need to create an instance of the Wyam.Core.Execution.Engine class
        var engine = new Wyam.Core.Execution.Engine();
        // configure the engine
        configure(engine);
        // Once the engine is configured, execute it with a call to Engine.Execute()
        // This will start evaluation of the pipelines and any output messages will
        // be sent to the configured trace endpoints.
        engine.Execute();
    }
}

And call that from your Startup.cs

For example

WyamConfiguration.Embed(engine => {
    engine.FileSystem.InputPaths.Add(new DirectoryPath("Markdown"));
    engine.FileSystem.OutputPath = new DirectoryPath("HtmlOutput");

    engine.Pipelines.Add(new Pipeline(
        "DocumentationPages",
        new ReadFiles("**/*.md"),
        new FrontMatter(new Yaml()),
        new Markdown(),
        new WriteFiles(".html")));

    var docsRecipe = new Docs();

    docsRecipe.Apply(engine);
});


问:
Removing a list of elements from a list of elements
I have a list of elements. I want to remove three of these elements at the same time.

I tried doing a list comprehension type of a thing. log_r.columns is an array of the column names from a pd.DataFrame(). This is what it looks like:

array(['MBI10', 'SAX', 'PX', 'CAC40', 'CRBEX', 'SOFIX', 'DAX', 'SBITOP',
       'BELEX15', 'UAX', 'SASX10', 'AEX', 'BET', 'BUX'], dtype=object).

I want to remove 'AEX', 'DAX' and 'CAC40'

emerging_names = log_r.columns.values[log_r.columns.values != ['AEX','DAX','CAC40']]

FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
```

Any help is appreciated!

答:
Use Index.isin with inverting mask by ~:

```<code>emerging_names = log_r.columns.values[~log_r.columns.isin(['AEX','DAX','CAC40'])]
</code>```

Or use list comprehension with filtering:

```<code>emerging_names = [x for x in log_r.columns if x not in ['AEX','DAX','CAC40']]
</code>```

Or if not problem with sorted columns names use Index.difference:

```<code>emerging_names = log_r.columns.difference(['AEX','DAX','CAC40'])
</code>```

Body:
I have a list of elements. I want to remove three of these elements at the same time.

I tried doing a list comprehension type of a thing. log_r.columns is an array of the column names from a pd.DataFrame(). This is what it looks like:

array(['MBI10', 'SAX', 'PX', 'CAC40', 'CRBEX', 'SOFIX', 'DAX', 'SBITOP',
       'BELEX15', 'UAX', 'SASX10', 'AEX', 'BET', 'BUX'], dtype=object).

I want to remove 'AEX', 'DAX' and 'CAC40'

emerging_names = log_r.columns.values[log_r.columns.values != ['AEX','DAX','CAC40']]

FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison

Any help is appreciated!

Body:
Use Index.isin with inverting mask by ~:

emerging_names = log_r.columns.values[~log_r.columns.isin(['AEX','DAX','CAC40'])]

Or use list comprehension with filtering:

emerging_names = [x for x in log_r.columns if x not in ['AEX','DAX','CAC40']]

Or if not problem with sorted columns names use Index.difference:

emerging_names = log_r.columns.difference(['AEX','DAX','CAC40'])


问:
How to map a set<text> field of cassandra using spark Dataset to a POJO in java
I am having a set< text> field in my cassandra table and I am creating Apache sparks Dataset of the same table having some other fields as well. When i print the value of Dataset the values are getting printed but when I map the Dataset to a POJO then the field having set< text> type gives value null and rest of the fields gives their respective values.

the test_ids field in cassandra is of type set< text> and in java i am using HashSet< String > to represent it. If anyone can help then please do respond.

```<code>Dataset<Row> dsQ = spark1.read().format("org.apache.spark.sql.cassandra").options(props1).load();
    dsQ.show();

Dataset<Employee> res = dsQ.as(Encoders.bean(Employee.class));
    res.collectAsList().forEach(employee -> {
        System.out.println("POJO: " + employee);
});

//POJO Class
@Column("emp_branch")
private String empBranch;

@Column("epoch_hour")
private int epochHour;

@Column("test_ids")
private Set<String> testIds = new HashSet<String>();

public String getEmpBranch() {
    return empBranch;
}
public void setEmpBranch(String empBranch) {
    this.empBranch = empBranch;
}
public int getEpochHour() {
    return epochHour;
}
public void setEpochHour(int epochHour) {
    this.epochHour = epochHour;
}
public Set<String> getTestIds() {
    return testIds;
}
public void setTestIds(Set<String> testIds) {
    this.testIds = testIds;
}
@Override
public String toString() {
    return "StackOverflow [empBranch=" + empBranch + ", epochHour=" + epochHour + ", testIds=" + testIds + "]";
}
</code>```

[Actual Result]
emp_branch=cs, epoch_hour=433064, test_ids=[ ]

[Expected Result]
emp_branch=cs, epoch_hour=433064, test_ids=['1234']

答:
Your Employee pojo should have something like this;</p>

```<code>@Column("test_ids")
private Set<String> testIds= new HashSet<String>();
</code>```

Body:
I am having a set< text> field in my cassandra table and I am creating Apache sparks Dataset of the same table having some other fields as well. When i print the value of Dataset the values are getting printed but when I map the Dataset to a POJO then the field having set< text> type gives value null and rest of the fields gives their respective values.

the test_ids field in cassandra is of type set< text> and in java i am using HashSet< String > to represent it. If anyone can help then please do respond.

Dataset<Row> dsQ = spark1.read().format("org.apache.spark.sql.cassandra").options(props1).load();
    dsQ.show();

Dataset<Employee> res = dsQ.as(Encoders.bean(Employee.class));
    res.collectAsList().forEach(employee -> {
        System.out.println("POJO: " + employee);
});

//POJO Class
@Column("emp_branch")
private String empBranch;

@Column("epoch_hour")
private int epochHour;

@Column("test_ids")
private Set<String> testIds = new HashSet<String>();

public String getEmpBranch() {
    return empBranch;
}
public void setEmpBranch(String empBranch) {
    this.empBranch = empBranch;
}
public int getEpochHour() {
    return epochHour;
}
public void setEpochHour(int epochHour) {
    this.epochHour = epochHour;
}
public Set<String> getTestIds() {
    return testIds;
}
public void setTestIds(Set<String> testIds) {
    this.testIds = testIds;
}
@Override
public String toString() {
    return "StackOverflow [empBranch=" + empBranch + ", epochHour=" + epochHour + ", testIds=" + testIds + "]";
}

[Actual Result]
emp_branch=cs, epoch_hour=433064, test_ids=[ ]

[Expected Result]
emp_branch=cs, epoch_hour=433064, test_ids=['1234']

Body:
Your Employee pojo should have something like this;

@Column("test_ids")
private Set<String> testIds= new HashSet<String>();


问:
GCC C vector extension: How to check if result of ANY element-wise comparison is true, and which?
I am new to GCC's C vector extensions. According to the manual, the result of comparing one vector to another in the form (test = vec1 > vec2;) is that "test" contains a 0 in each element that is false and a -1 in each element that is true.

But how to very quickly check if ANY of the element comparisons was true? And, further, how to tell which is the first element for which the comparison was true?

For example, with:

```<code>vec1 = {1,1,3,1};
vec2 = {1,2,2,2};
test = vec1 > vec2;
</code>```

I want to determine if "test" contains any truth (non-zero elements). In this case I want "test" to reduce to true, because there exists an element for which vec1 is greater than vec2 and hence an element in test containing -1.

Additionally, or alternatively, I want to quickly discover WHICH element fails the test. In this case, this would simply be the number 2. Said another way, I want to test which is the first non-zero element.

```<code>int hasAnyTruth = ...; // should be non-zero. "bool" works too since C99
int whichTrue = ...; // should contain 2, because test[2] == -1
</code>```

I imagine we could use a simd reduction-addition command (?) to sum everything in the vector into a number and compare that sum to 0, but I don't know how (or if there is a faster way). I am guessing some form of argmax is necessary for the second question, but again, I don't know how to instruct GCC to use it on the vectors.

答:
Here's what I ended up using in one case:</p>

```<code>#define V_EQ(v1, v2) \
  ({ \
    __typeof__ (v1) v_d = (v1) != (v2); \
    __typeof__ (v_d) v_0 = { 0 }; \
    memcmp (&v_d, &v_0, sizeof v_d) == 0; \
  })

assert (V_EQ (v4ldblo, v4ldbli - 1));
</code>```

Body:
I am new to GCC's C vector extensions. According to the manual, the result of comparing one vector to another in the form (test = vec1 > vec2;) is that "test" contains a 0 in each element that is false and a -1 in each element that is true.

But how to very quickly check if ANY of the element comparisons was true? And, further, how to tell which is the first element for which the comparison was true?

For example, with:

vec1 = {1,1,3,1};
vec2 = {1,2,2,2};
test = vec1 > vec2;

I want to determine if "test" contains any truth (non-zero elements). In this case I want "test" to reduce to true, because there exists an element for which vec1 is greater than vec2 and hence an element in test containing -1.

Additionally, or alternatively, I want to quickly discover WHICH element fails the test. In this case, this would simply be the number 2. Said another way, I want to test which is the first non-zero element.

int hasAnyTruth = ...; // should be non-zero. "bool" works too since C99
int whichTrue = ...; // should contain 2, because test[2] == -1

I imagine we could use a simd reduction-addition command (?) to sum everything in the vector into a number and compare that sum to 0, but I don't know how (or if there is a faster way). I am guessing some form of argmax is necessary for the second question, but again, I don't know how to instruct GCC to use it on the vectors.

Body:
Here's what I ended up using in one case:

#define V_EQ(v1, v2) \
  ({ \
    __typeof__ (v1) v_d = (v1) != (v2); \
    __typeof__ (v_d) v_0 = { 0 }; \
    memcmp (&v_d, &v_0, sizeof v_d) == 0; \
  })

assert (V_EQ (v4ldblo, v4ldbli - 1));


问:
Sum of all odd fibonacci numbers upto n
I am stuck in summing up to number 10. Can't get it right.
What i am getting is the total sum from 10 digits (after filtering odd only 7). Where should i make <= num ?

function sumFibs(num) {
  var fib = [1, 1];
  for (var i = 2; i < num; i++) {
    var next = fib[i - 1] + fib[i - 2];
    var fibi = fib.push(next);
  }

  return fib.filter(function(a) {
      return (a % 2 != 0);
    })
    .reduce(function(a, z) {
      return a + z;
    })
}
console.log(sumFibs(10));```

Expected output 10, but getting 99

答:
You need to change the loop condition. Loop till the last value of fib is less than num

function sumFibs(num) {
  var fib = [1, 1];
  for (var i = 2; fib[fib.length - 1] < num; i++) {
    var next = fib[i - 1] + fib[i - 2];
    fib.push(next);
  }
   return fib
    .filter(x => !(x % 2))
    .reduce((ac,a) => ac + a,0)
}
console.log(sumFibs(10));```

Title: Sum of all odd fibonacci numbers upto n

Body:
I am stuck in summing up to number 10. Can't get it right.
What i am getting is the total sum from 10 digits (after filtering odd only 7). Where should i make <= num ?

function sumFibs(num) {
  var fib = [1, 1];
  for (var i = 2; i < num; i++) {
    var next = fib[i - 1] + fib[i - 2];
    var fibi = fib.push(next);
  }

  return fib.filter(function(a) {
      return (a % 2 != 0);
    })
    .reduce(function(a, z) {
      return a + z;
    })
}
console.log(sumFibs(10));

Expected output 10, but getting 99


问:
Does std::discrete_distribution() allow zero weights?
Can std::discrete_distribution be used with some zero weights, assuming that at least one positive weight was given? The items with zero weights should simply never be sampled.

The fact that it appears to work on my machine does not give me confidence that it will work on all systems.

Example:

```<code>std::discrete_distribution<> dd({1.0, 2.0, 0.0, 3.0});
</code>```

答:
Per [rand.dist.samp.discrete]/2

Unless specified otherwise, the distribution parameters are calculated as: pk = wk / S for k = 0, ..., n−1, in which the values wk, commonly known as the weights, shall be non-negative, non-NaN, and non-infinity. Moreover, the following relation shall hold: 0 < S = w0 + ... + wn−1.

So zero weights are allowed, but not all of the weights can be zero since S must be greater than zero.

Body:
Can std::discrete_distribution be used with some zero weights, assuming that at least one positive weight was given? The items with zero weights should simply never be sampled.

The fact that it appears to work on my machine does not give me confidence that it will work on all systems.

Example:

std::discrete_distribution<> dd({1.0, 2.0, 0.0, 3.0});


问:
iis 7 disable windows auth
I setup a test website on my IIS 7.5, I created a Web Application project in VisualStudio and set up a web site in a new application pool in Classic Pipeline Mode.

I have this line in C:\Windows\System32\drivers\etc\hosts:

```192.168.50.142     dev.mybigdomain.org.uk```

Now if I access my website with http://localhost/testHello/Default.aspx it works fine,
but when I try http://dev.mybigdomain.org.uk/testHello/Default.aspx I get a "Windows security" window asking for authentication, but if enter "administrator" and password it does not recognise them and just asks again.

How can I disable the authentication?

答:
Have you try to change the web.config authentication mode to Forms or None?

```<code> <system.web>
...
 <authentication mode="Forms">
</code>```

instead of

```<code><system.web>
...
<authentication mode="Windows">
</code>```

Title: iis 7 disable windows auth

Body:
I setup a test website on my IIS 7.5, I created a Web Application project in VisualStudio and set up a web site in a new application pool in Classic Pipeline Mode.

I have this line in C:\Windows\System32\drivers\etc\hosts:

192.168.50.142     dev.mybigdomain.org.uk

Now if I access my website with http://localhost/testHello/Default.aspx it works fine,
but when I try http://dev.mybigdomain.org.uk/testHello/Default.aspx I get a "Windows security" window asking for authentication, but if enter "administrator" and password it does not recognise them and just asks again.

How can I disable the authentication?

Body:
Have you try to change the web.config authentication mode to Forms or None?

 <system.web>
...
 <authentication mode="Forms">

instead of

<system.web>
...
<authentication mode="Windows">


问:
How can I dismiss the on screen keyboard?
I am collecting user input with a TextFormField and when the user presses a FloatingActionButton indicating they are done, I want to dismiss the on screen keyboard.

How do I make the keyboard go away automatically?

```<code>import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
  MyHomePageState createState() => new MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  TextEditingController _controller = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.send),
        onPressed: () {
          setState(() {
            // send message
            // dismiss on screen keyboard here
            _controller.clear();
          });
        },
      ),
      body: new Container(
        alignment: FractionalOffset.center,
        padding: new EdgeInsets.all(20.0),
        child: new TextFormField(
          controller: _controller,
          decoration: new InputDecoration(labelText: 'Example Text'),
        ),
      ),
    );
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

void main() {
  runApp(new MyApp());
}
</code>```

答:
Following code helped me to hide keyboard </p>

```<code>   void initState() {
   SystemChannels.textInput.invokeMethod('TextInput.hide');
   super.initState();
   }
</code>```

Body:
I am collecting user input with a TextFormField and when the user presses a FloatingActionButton indicating they are done, I want to dismiss the on screen keyboard.

How do I make the keyboard go away automatically?

import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
  MyHomePageState createState() => new MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  TextEditingController _controller = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.send),
        onPressed: () {
          setState(() {
            // send message
            // dismiss on screen keyboard here
            _controller.clear();
          });
        },
      ),
      body: new Container(
        alignment: FractionalOffset.center,
        padding: new EdgeInsets.all(20.0),
        child: new TextFormField(
          controller: _controller,
          decoration: new InputDecoration(labelText: 'Example Text'),
        ),
      ),
    );
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

void main() {
  runApp(new MyApp());
}

Body:
Following code helped me to hide keyboard

   void initState() {
   SystemChannels.textInput.invokeMethod('TextInput.hide');
   super.initState();
   }


问:
Performance: Double nested subquery unknown column
If I do COUNT()/AVG() in the first subquery MySQL process all rows inside the table, because of that reason it is necessary to filter at from all rows with another subquery.

As example if I have 3 rows, but only 1 row has the id which should get count, MySQL process all 3 rows (according to EXPLAIN) and does the where clause after.

If I'm able to select in a double nested sub query this single row and call the count outside it would be a lot better performance wise.

The problem MySQL does not allow using outer values in a second level subquery.

Simple example of my code:

```<code>SELECT
    pr.id, pr.catid, ...
    (
        SELECT COUNT(pra.id)
        FROM (
            SELECT id
            FROM productsrating
            WHERE pr.id = productid
        ) pra
    ) as ratingcount,
    ...
FROM
(
    SELECT id, ...
    FROM products
    WHERE active = 1

) pr
</code>```

-> Unknown column pr.id

I do also tried to use the COUNT in the main select but it isn't allowed to have multiple values inside a subquery.

Edit: I have an index on productid.

EDIT2 SOLUTION:
Sorry at all its working fine with the first single subquery, server problems caused bad behavior.

答:
It seems you want the count of ratings occurring for an active product. Is this correct?

So; why is a simple left join not working?  The count of PRA should be based on only those products which are active; so index usage should work here.

I'd need to see sample data / expected results to figure out the overall goal here.

```<code>SELECT PR.*, count(PRA.ID)
FROM products PR
LEFT JOIN productsRating PRA
 on PR.ID = PRA.ProductID
WHERE PR.Active = 1
GROUP BY PR.*
</code>```

Substitute all fields needed for PR.*

Maybe this... seems like an odd thing to have to do to get the products rating to be filtered before the average/count is done though.

```<code>SELECT PR.*, count(PRA.ID)
FROM products PR
LEFT JOIN (SELECT * FROM productsRating PRI
           WHERE EXISTS (SELECT 1
                         FROM Products P
                         WHERE active = 1 and PRI.ProductID = P.ID)) PRA
 on PR.ID = PRA.ProductID
WHERE PR.Active = 1
GROUP BY PR.*
</code>```

Body:
If I do COUNT()/AVG() in the first subquery MySQL process all rows inside the table, because of that reason it is necessary to filter at from all rows with another subquery.

As example if I have 3 rows, but only 1 row has the id which should get count, MySQL process all 3 rows (according to EXPLAIN) and does the where clause after.

If I'm able to select in a double nested sub query this single row and call the count outside it would be a lot better performance wise.

The problem MySQL does not allow using outer values in a second level subquery.

Simple example of my code:

SELECT
    pr.id, pr.catid, ...
    (
        SELECT COUNT(pra.id)
        FROM (
            SELECT id
            FROM productsrating
            WHERE pr.id = productid
        ) pra
    ) as ratingcount,
    ...
FROM
(
    SELECT id, ...
    FROM products
    WHERE active = 1

) pr

-> Unknown column pr.id

I do also tried to use the COUNT in the main select but it isn't allowed to have multiple values inside a subquery.

Edit: I have an index on productid.

EDIT2 SOLUTION:
Sorry at all its working fine with the first single subquery, server problems caused bad behavior.

Body:
It seems you want the count of ratings occurring for an active product. Is this correct?

So; why is a simple left join not working?  The count of PRA should be based on only those products which are active; so index usage should work here.

I'd need to see sample data / expected results to figure out the overall goal here.

SELECT PR.*, count(PRA.ID)
FROM products PR
LEFT JOIN productsRating PRA
 on PR.ID = PRA.ProductID
WHERE PR.Active = 1
GROUP BY PR.*

Substitute all fields needed for PR.*

Maybe this... seems like an odd thing to have to do to get the products rating to be filtered before the average/count is done though.

SELECT PR.*, count(PRA.ID)
FROM products PR
LEFT JOIN (SELECT * FROM productsRating PRI
           WHERE EXISTS (SELECT 1
                         FROM Products P
                         WHERE active = 1 and PRI.ProductID = P.ID)) PRA
 on PR.ID = PRA.ProductID
WHERE PR.Active = 1
GROUP BY PR.*


问:
Hosting for Ruby (and Rails) like hosting for PHP
I was wondering if there was around a hosting as those that have existed for years for PHP that would give the opportunity to publish many Ruby and Rails applications and not as Heroku that forces a single application for dyno.

In classical hosting PHP I can create a folder, upload some files in php and navigate them through links.

You can something like that on some Web hosting?

答:
You can try Ruby hosting on Jelastic PaaS with automated deployment to containers and scaling, as well as pay-per-use pricing model that makes it not so pricy.

There are pre-configured Apache and NGINX containers for running Ruby application, supported different Ruby versions, built-in Ruby on Rails framework, Passenger, Puma, Unicorn, Bundler dependency manager etc.

When deploying a Ruby application, only a single context (ROOT) can be used. However, you can switch between three deployment types: deployment, production and test.

More details are described here https://jelastic.com/blog/ruby-paas-hosting/

You can start with a free trial and test how it suits your project before investing any budget. This Ruby PaaS is available on different local service providers https://jelastic.cloud/


问:
How to speed up copying/creating a file many times in Google Apps Script?
So, I'm setting up student surveys in a college. There are lots of forms to be handed out to lots of groups of students. For one particular survey, I have a template google form.

What I do is a loop that on every iteration creates a copy of this template and then modifies it a little bit. It takes A LOT of time. Google is copying and modifying 220 forms for like 40-50 minutes. I found my way around the time limit put on google script, but it's still too long. Do you see any way to speed this up a little?

Now it looks schematically like this:

for(some range):{
   template.makeCopy("template", formsFolder);
   var formFile = formsFolder.getFilesByName("template").next();
   var form = FormApp.openById(formFile.getId())
//   ... do some modifications
  }```

Thank you!

答:
File#makeCopy already hands you the exact file you want, so you can completely cut out the need to search for the file you create:

```<code>for (var f = 0; f < newNames.length; ++f) {
  var formFile = template.makeCopy(newNames[f], formsFolder);
  var form = FormApp.openById(formFile.getId());
  // Do stuff
}
</code>```

Body:
So, I'm setting up student surveys in a college. There are lots of forms to be handed out to lots of groups of students. For one particular survey, I have a template google form.

What I do is a loop that on every iteration creates a copy of this template and then modifies it a little bit. It takes A LOT of time. Google is copying and modifying 220 forms for like 40-50 minutes. I found my way around the time limit put on google script, but it's still too long. Do you see any way to speed this up a little?

Now it looks schematically like this:

for(some range):{
   template.makeCopy("template", formsFolder);
   var formFile = formsFolder.getFilesByName("template").next();
   var form = FormApp.openById(formFile.getId())
//   ... do some modifications
  }

Thank you!

Body:
File#makeCopy already hands you the exact file you want, so you can completely cut out the need to search for the file you create:

for (var f = 0; f < newNames.length; ++f) {
  var formFile = template.makeCopy(newNames[f], formsFolder);
  var form = FormApp.openById(formFile.getId());
  // Do stuff
}


问:
Reordering a list from comma sepperated ID's
I have a list of objects I want to reorder. The order is determined in a string.

(I hope my current code explains better than the text)

```<code>List<DataObject> objects = GetDataObjectsFromDatabase();
string order = "1,3,2";
List<DataObject> orderedObjects = new List<DataObject>
foreach(string index in order.Split(',')
{
    orderedObjects.Add(objects.FirstOrDefault(x => x.id == index));
}
</code>```

Is there a single Linq statement or a better way to do this?

答: var data = order.Split(',').ToList();</p>

Body:
I have a list of objects I want to reorder. The order is determined in a string.

(I hope my current code explains better than the text)

List<DataObject> objects = GetDataObjectsFromDatabase();
string order = "1,3,2";
List<DataObject> orderedObjects = new List<DataObject>
foreach(string index in order.Split(',')
{
    orderedObjects.Add(objects.FirstOrDefault(x => x.id == index));
}

Is there a single Linq statement or a better way to do this?

Body: var data = order.Split(',').ToList();


问:
How to remove empty strings from the end of a list of strings (only at the end)
i have some list of strings. I want to remove empty strings from the end of the list (i.e.  each list should end with a non empty element).

```<code>input
list1= ['a1','b1','c1','d1','']
list2 = ['a2','','b2','','c2','d2','']
list3 = ['a3','','b3','','','']
list4 = ['','','','','']
</code>```

output

```<code>list1= ['a1','b1','c1','d1']
list2 = ['a2','','b2','','c2','d2']
list3 = ['a3','','b3']
list4 = ['']
</code>```

if all the elements are empty strings , only one empty string should remain (eg. list4).

Body:
i have some list of strings. I want to remove empty strings from the end of the list (i.e.  each list should end with a non empty element).

input
list1= ['a1','b1','c1','d1','']
list2 = ['a2','','b2','','c2','d2','']
list3 = ['a3','','b3','','','']
list4 = ['','','','','']

output

list1= ['a1','b1','c1','d1']
list2 = ['a2','','b2','','c2','d2']
list3 = ['a3','','b3']
list4 = ['']

if all the elements are empty strings , only one empty string should remain (eg. list4).

Body:
This is one approach using str methods.

Ex:

list1= ['a1','b1','c1','d1','']
list2 = ['a2','','b2','','c2','d2','']
list3 = ['a3','','b3','','','']
list4 = ['','','','','']

data = [list1, list2, list3, list4]

result = ["*#*".join(i).strip("*#* ").split("*#*") for i in data]
print(result)

Output:

[['a1', 'b1', 'c1', 'd1'],
 ['a2', '', 'b2', '', 'c2', 'd2'],
 ['a3', '', 'b3'],
 ['']]


问:
add a class to the li element or the a?
I have a standard list of links:

```<code><li><a href="">one</a></li>
<li><a href="">two</a></li>
</code>```

If I want to add an extra class to one of the list items, should I add the class to the li or the a element? What is best practice?

Many thanks!

Cameron

答:
I generally would add it to the list item.. this gives you the flexibility to target with CSS the list item or the anchor tag it contains

```<code>li.class-name {
    /* target li class */

}

li.class-name a {
    /*target it's anchor */
}
</code>```

In production though, you're better off leaving the initial li off the class name when referencing it. It is unnecessary (unless you have a really bad memory).

OwnerDisplayName: Cameron

Title: add a class to the li element or the a?

Body:
I have a standard list of links:

one

two

If I want to add an extra class to one of the list items, should I add the class to the li or the a element? What is best practice?

Many thanks!

Cameron

Body:
I generally would add it to the list item.. this gives you the flexibility to target with CSS the list item or the anchor tag it contains

li.class-name {
    /* target li class */

}

li.class-name a {
    /*target it's anchor */
}

In production though, you're better off leaving the initial li off the class name when referencing it. It is unnecessary (unless you have a really bad memory).

OwnerDisplayName: alex