问:
Simple swift color picker popover (iOS)
Is there is a simple way to implement a color picker popover in swift?  Are there any built-in libraries or UI elements that I could leverage for this purpose?  I saw some color pickers written in objective-c, but they were several years old and I was wondering if there was something more recent.</p>

答:
Based on Joel Teply code (Swift 4), with gray bar on top:

```<code>import UIKit

class ColorPickerView : UIView {

var onColorDidChange: ((_ color: UIColor) -> ())?

let saturationExponentTop:Float = 2.0
let saturationExponentBottom:Float = 1.3

let grayPaletteHeightFactor: CGFloat = 0.1
var rect_grayPalette = CGRect.zero
var rect_mainPalette = CGRect.zero

// adjustable
var elementSize: CGFloat = 1.0 {
    didSet {
        setNeedsDisplay()
    }
}

override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setup()
}

private func setup() {

    self.clipsToBounds = true
    let touchGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.touchedColor(gestureRecognizer:)))
    touchGesture.minimumPressDuration = 0
    touchGesture.allowableMovement = CGFloat.greatestFiniteMagnitude
    self.addGestureRecognizer(touchGesture)
}

override func draw(_ rect: CGRect) {
    let context = UIGraphicsGetCurrentContext()

    rect_grayPalette = CGRect(x: 0, y: 0, width: rect.width, height: rect.height * grayPaletteHeightFactor)
    rect_mainPalette = CGRect(x: 0, y: rect_grayPalette.maxY,
                              width: rect.width, height: rect.height - rect_grayPalette.height)

    // gray palette
    for y in stride(from: CGFloat(0), to: rect_grayPalette.height, by: elementSize) {

        for x in stride(from: (0 as CGFloat), to: rect_grayPalette.width, by: elementSize) {
            let hue = x / rect_grayPalette.width

            let color = UIColor(white: hue, alpha: 1.0)

            context!.setFillColor(color.cgColor)
            context!.fill(CGRect(x:x, y:y, width:elementSize, height:elementSize))
        }
    }

    // main palette
    for y in stride(from: CGFloat(0), to: rect_mainPalette.height, by: elementSize) {

        var saturation = y < rect_mainPalette.height / 2.0 ? CGFloat(2 * y) / rect_mainPalette.height : 2.0 * CGFloat(rect_mainPalette.height - y) / rect_mainPalette.height
        saturation = CGFloat(powf(Float(saturation), y < rect_mainPalette.height / 2.0 ? saturationExponentTop : saturationExponentBottom))
        let brightness = y < rect_mainPalette.height / 2.0 ? CGFloat(1.0) : 2.0 * CGFloat(rect_mainPalette.height - y) / rect_mainPalette.height

        for x in stride(from: (0 as CGFloat), to: rect_mainPalette.width, by: elementSize) {
            let hue = x / rect_mainPalette.width

            let color = UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0)

            context!.setFillColor(color.cgColor)
            context!.fill(CGRect(x:x, y: y + rect_mainPalette.origin.y,
                                 width: elementSize, height: elementSize))
        }
    }
}

func getColorAtPoint(point: CGPoint) -> UIColor
{
    var roundedPoint = CGPoint(x:elementSize * CGFloat(Int(point.x / elementSize)),
                               y:elementSize * CGFloat(Int(point.y / elementSize)))

    let hue = roundedPoint.x / self.bounds.width

    // main palette
    if rect_mainPalette.contains(point)
    {
        // offset point, because rect_mainPalette.origin.y is not 0
        roundedPoint.y -= rect_mainPalette.origin.y

        var saturation = roundedPoint.y < rect_mainPalette.height / 2.0 ? CGFloat(2 * roundedPoint.y) / rect_mainPalette.height
            : 2.0 * CGFloat(rect_mainPalette.height - roundedPoint.y) / rect_mainPalette.height

        saturation = CGFloat(powf(Float(saturation), roundedPoint.y < rect_mainPalette.height / 2.0 ? saturationExponentTop : saturationExponentBottom))
        let brightness = roundedPoint.y < rect_mainPalette.height / 2.0 ? CGFloat(1.0) : 2.0 * CGFloat(rect_mainPalette.height - roundedPoint.y) / rect_mainPalette.height

        return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0)
    }
    // gray palette
    else{

        return UIColor(white: hue, alpha: 1.0)
    }
}

@objc func touchedColor(gestureRecognizer: UILongPressGestureRecognizer){
    let point = gestureRecognizer.location(in: self)
    let color = getColorAtPoint(point: point)

    self.onColorDidChange?(color)
  }
}
</code>```

Usage:

```<code>    let colorPickerView = ColorPickerView()
    colorPickerView.onColorDidChange = { [weak self] color in
        DispatchQueue.main.async {

            // use picked color for your needs here...
            self?.view.backgroundColor = color
        }

    }

    // add it to some view and set constraints
    ...
</code>```

Title: Simple swift color picker popover (iOS)

Body:
Based on Joel Teply code (Swift 4), with gray bar on top:

import UIKit

class ColorPickerView : UIView {

var onColorDidChange: ((_ color: UIColor) -> ())?

let saturationExponentTop:Float = 2.0
let saturationExponentBottom:Float = 1.3

let grayPaletteHeightFactor: CGFloat = 0.1
var rect_grayPalette = CGRect.zero
var rect_mainPalette = CGRect.zero

// adjustable
var elementSize: CGFloat = 1.0 {
    didSet {
        setNeedsDisplay()
    }
}

override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setup()
}

private func setup() {

    self.clipsToBounds = true
    let touchGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.touchedColor(gestureRecognizer:)))
    touchGesture.minimumPressDuration = 0
    touchGesture.allowableMovement = CGFloat.greatestFiniteMagnitude
    self.addGestureRecognizer(touchGesture)
}

override func draw(_ rect: CGRect) {
    let context = UIGraphicsGetCurrentContext()

    rect_grayPalette = CGRect(x: 0, y: 0, width: rect.width, height: rect.height * grayPaletteHeightFactor)
    rect_mainPalette = CGRect(x: 0, y: rect_grayPalette.maxY,
                              width: rect.width, height: rect.height - rect_grayPalette.height)

    // gray palette
    for y in stride(from: CGFloat(0), to: rect_grayPalette.height, by: elementSize) {

        for x in stride(from: (0 as CGFloat), to: rect_grayPalette.width, by: elementSize) {
            let hue = x / rect_grayPalette.width

            let color = UIColor(white: hue, alpha: 1.0)

            context!.setFillColor(color.cgColor)
            context!.fill(CGRect(x:x, y:y, width:elementSize, height:elementSize))
        }
    }

    // main palette
    for y in stride(from: CGFloat(0), to: rect_mainPalette.height, by: elementSize) {

        var saturation = y < rect_mainPalette.height / 2.0 ? CGFloat(2 * y) / rect_mainPalette.height : 2.0 * CGFloat(rect_mainPalette.height - y) / rect_mainPalette.height
        saturation = CGFloat(powf(Float(saturation), y < rect_mainPalette.height / 2.0 ? saturationExponentTop : saturationExponentBottom))
        let brightness = y < rect_mainPalette.height / 2.0 ? CGFloat(1.0) : 2.0 * CGFloat(rect_mainPalette.height - y) / rect_mainPalette.height

        for x in stride(from: (0 as CGFloat), to: rect_mainPalette.width, by: elementSize) {
            let hue = x / rect_mainPalette.width

            let color = UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0)

            context!.setFillColor(color.cgColor)
            context!.fill(CGRect(x:x, y: y + rect_mainPalette.origin.y,
                                 width: elementSize, height: elementSize))
        }
    }
}

func getColorAtPoint(point: CGPoint) -> UIColor
{
    var roundedPoint = CGPoint(x:elementSize * CGFloat(Int(point.x / elementSize)),
                               y:elementSize * CGFloat(Int(point.y / elementSize)))

    let hue = roundedPoint.x / self.bounds.width

    // main palette
    if rect_mainPalette.contains(point)
    {
        // offset point, because rect_mainPalette.origin.y is not 0
        roundedPoint.y -= rect_mainPalette.origin.y

        var saturation = roundedPoint.y < rect_mainPalette.height / 2.0 ? CGFloat(2 * roundedPoint.y) / rect_mainPalette.height
            : 2.0 * CGFloat(rect_mainPalette.height - roundedPoint.y) / rect_mainPalette.height

        saturation = CGFloat(powf(Float(saturation), roundedPoint.y < rect_mainPalette.height / 2.0 ? saturationExponentTop : saturationExponentBottom))
        let brightness = roundedPoint.y < rect_mainPalette.height / 2.0 ? CGFloat(1.0) : 2.0 * CGFloat(rect_mainPalette.height - roundedPoint.y) / rect_mainPalette.height

        return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0)
    }
    // gray palette
    else{

        return UIColor(white: hue, alpha: 1.0)
    }
}

@objc func touchedColor(gestureRecognizer: UILongPressGestureRecognizer){
    let point = gestureRecognizer.location(in: self)
    let color = getColorAtPoint(point: point)

    self.onColorDidChange?(color)
  }
}

Usage:

    let colorPickerView = ColorPickerView()
    colorPickerView.onColorDidChange = { [weak self] color in
        DispatchQueue.main.async {

            // use picked color for your needs here...
            self?.view.backgroundColor = color
        }

    }

    // add it to some view and set constraints
    ...


来源: stackexchange

问:
How to analyze SQL statement execution time fluctuation?
I know this question is not easy to give an actual answer, but I met it sometimes, SQL execution time is high but cannot reproduce 100%, actually very casually.

here, I just want to get the general way to how to find the root cause, which aspects should I pay more attention to? and please note 1 point, I was doing it on HANA DB (from SAP).

Thanks!

答:
When looking at runtime variations, several factors can come into play, such as

changed data, both in volume and variety (check the statement's selection/grouping conditions and the data in the referenced tables)

changed system load during query execution (other queries/activities running? delta merge? data load? backup?)

system cpu power settings not set correctly (if the CPU perf. gets throttled, this can have quite an effect)

SAP notes 1969700 - SQL Statement Collection for SAP HANA and 2000002 - FAQ: SAP HANA SQL Optimization are great starting points for the analysis, just as the SAP HANA Troubleshooting and Performance Analysis Guide

ContentLicense: CC BY-SA 3.0


问:
How to format a duration
I have the following code which I can't run on play because I use the gin framework and filewalk.

```<code>package main

import (
    "fmt"
    "os"
    "path/filepath"
    "time"
    "regexp"
    "github.com/gin-gonic/gin"
    "sort"
    "strings"
    "github.com/davidscholberg/go-durationfmt"
)

var filext = regexp.MustCompile(`\.[mM][pP]4|\.[mM]4[vV]|\.jpg|\.[hH]264|\.go`)
var m map[int]string
var keys []int

func main() {

    if gin.IsDebugging() {
        fmt.Print("This progamm shows only the path and the age of a file in 'STARTDIR'\n")
        fmt.Print("only the following files will be handled '.[mM][pP]4|.[mM]4[vV$|.[hH]264|.go'\n")
        fmt.Print("The git repository: https://gitlab.com/aleks001/show-files-age \n")
    }

    if len(os.Getenv("LISTEN_IP_PORT")) == 0 {
        fmt.Print("I need a ip and port on which I should listen.\n")
        os.Exit(1)
    }
    router := gin.Default()

    gin.DisableConsoleColor()

    router.GET("/videoinfo",getInfo)

    router.Run(os.Getenv("LISTEN_IP_PORT"))
}

func getInfo(c *gin.Context)  {

    loc, _ := time.LoadLocation("Europe/Vienna")
    var startdir = ""

    if os.Getenv("STARTDIR") != "" {
        startdir = os.Getenv("STARTDIR")
    } else if c.GetHeader("STARTDIR") != "" {
        startdir = c.GetHeader("STARTDIR")
    } else {
        c.String(404,"Startdir not found <br>\n")
        return
    }

    m = make(map[int]string)
    keys = nil

    filepath.Walk(startdir,walkpath)

    for k := range m {
        keys = append(keys, k)
    }
    sort.Ints(keys)

    for _, k := range keys {
        t := time.Date(time.Now().Year(),time.Now().Month(),time.Now().Day(),time.Now().Hour(),k,time.Now().Second(),time.Now().Nanosecond(),loc)
        durStr, err := durationfmt.Format(time.Since(t), "%h:%m")

        if err != nil {
            fmt.Println(err)
        } else {
            //fmt.Println(durStr)
            fmt.Printf("Key: %s Value: %s\n", durStr , m[k])
            c.String(200,"Minutes: %s File: %s\n", durStr, m[k])
        }
    }
}

func walkpath(path string, f os.FileInfo, err error) error {

  if err != nil {
        fmt.Println(err)
    } else {
        if filext.MatchString(path) {
            age := time.Now().Sub(f.ModTime())
            path_new := strings.Replace(path,"/videos/","",1)
            // path_new := strings.Replace(path,"..\\","",1)
            /*
            fmt.Printf("Path: %s, ModTime: %s, Age: %s <br>\n", walker.Path(), walker.Stat().ModTime(), age)
            c.String(200,"Path: %s, ModTime: %s, Age: %s <br>\n", walker.Path(), walker.Stat().ModTime(), age)
            */
            fmt.Printf("Path: %s, Age: %d age minutes %0.2f  <br>\n", path_new, age, age.Minutes())
            m[int(age.Minutes())]=path_new
            //c.String(200,"Path: %s, Age: %0.2f <br>\n", path, age.Minutes())
        }
    //fmt.Printf("%s with %d bytes at motime %s\n", path,f.Size(), f.ModTime())
}
    return nil
}
</code>```

What I want to do is a sorted output of files based on filext als filter and the modtime as sort criteria.

I was able to fulfil the most part of the request but the output looks ugly as you can see below.

I have used https://github.com/davidscholberg/go-durationfmt to format the duration but the output looks ugly or I missus the library.

```<code>Minutes: 0:6 File: upload/dir003/file1.m4v
Minutes: 0:5 File: transfer/dir5/file2.jpg
Minutes: -5:-48 File: transfer/dir001/file.mp4
Minutes: -6:-21 File: transfer/03.jpg
Minutes: -6:-22 File: transfer/02.mp4
</code>```

答:
For example, to provide a custom format for a duration,

```<code>package main

import (
    "fmt"
    "time"
)

func fmtDuration(d time.Duration) string {
    d = d.Round(time.Minute)
    h := d / time.Hour
    d -= h * time.Hour
    m := d / time.Minute
    return fmt.Sprintf("%02d:%02d", h, m)
}

func main() {
    modTime := time.Now().Round(0).Add(-(3600 + 60 + 45) * time.Second)
    since := time.Since(modTime)
    fmt.Println(since)
    durStr := fmtDuration(since)
    fmt.Println(durStr)
}
</code>```

Playground: https://play.golang.org/p/HT4bFfoA5r

Output:

```<code>1h1m45s
01:02
</code>```

If you want to sort on a duration then use the Go sort package. I would sort on ModTime to defer the calculation of the duration, Since(ModTime), to be accurate at the time it is printed. For example,

```<code>package main

import (
    "fmt"
    "os"
    "path/filepath"
    "sort"
    "strings"
    "time"
)

func isVideo(path string) bool {
    videos := []string{".mp4", ".m4v", ".h264"}
    ext := strings.ToLower(filepath.Ext(path))
    for _, video := range videos {
        if ext == video {
            return true
        }
    }
    return false
}

type modTimeInfo struct {
    path    string
    modTime time.Time
}

func walkModTime(root string) ([]modTimeInfo, error) {
    var infos []modTimeInfo
    err := filepath.Walk(
        root,
        func(path string, info os.FileInfo, err error) error {
            if err != nil {
                return err
            }
            if info.Mode().IsRegular() {
                path = filepath.Clean(path)
                if !isVideo(path) {
                    return nil
                }
                sep := string(filepath.Separator)
                dir := sep + `Videos` + sep
                path = strings.Replace(path, dir, sep, 1)
                infos = append(infos, modTimeInfo{
                    path:    path,
                    modTime: info.ModTime()},
                )
            }
            return nil
        },
    )
    if err != nil {
        return nil, err
    }
    return infos, nil
}

func sortModTime(infos []modTimeInfo) {
    sort.SliceStable(
        infos,
        func(i, j int) bool {
            return infos[i].modTime.Before(infos[j].modTime)
        },
    )
}

func fmtAge(d time.Duration) string {
    d = d.Round(time.Minute)
    h := d / time.Hour
    d -= h * time.Hour
    m := d / time.Minute
    return fmt.Sprintf("%02d:%02d", h, m)
}

func main() {
    root := `/home/peter/Videos` // Testing ...
    infos, err := walkModTime(root)
    if err != nil {
        fmt.Println(err)
        return
    }
    sortModTime(infos)
    now := time.Now()
    for _, info := range infos {
        age := fmtAge(now.Sub(info.modTime))
        fmt.Println("Age (H:M):", age, "File:", info.path)
    }
}
</code>```

Playground: https://play.golang.org/p/j2TUmJdAi4

ContentLicense: CC BY-SA 4.0

Title: How to format a duration

Body:
I have the following code which I can't run on play because I use the gin framework and filewalk.

package main

import (
    "fmt"
    "os"
    "path/filepath"
    "time"
    "regexp"
    "github.com/gin-gonic/gin"
    "sort"
    "strings"
    "github.com/davidscholberg/go-durationfmt"
)

var filext = regexp.MustCompile(`\.[mM][pP]4|\.[mM]4[vV]|\.jpg|\.[hH]264|\.go`)
var m map[int]string
var keys []int

func main() {

    if gin.IsDebugging() {
        fmt.Print("This progamm shows only the path and the age of a file in 'STARTDIR'\n")
        fmt.Print("only the following files will be handled '.[mM][pP]4|.[mM]4[vV$|.[hH]264|.go'\n")
        fmt.Print("The git repository: https://gitlab.com/aleks001/show-files-age \n")
    }

    if len(os.Getenv("LISTEN_IP_PORT")) == 0 {
        fmt.Print("I need a ip and port on which I should listen.\n")
        os.Exit(1)
    }
    router := gin.Default()

    gin.DisableConsoleColor()

    router.GET("/videoinfo",getInfo)

    router.Run(os.Getenv("LISTEN_IP_PORT"))
}

func getInfo(c *gin.Context)  {

    loc, _ := time.LoadLocation("Europe/Vienna")
    var startdir = ""

    if os.Getenv("STARTDIR") != "" {
        startdir = os.Getenv("STARTDIR")
    } else if c.GetHeader("STARTDIR") != "" {
        startdir = c.GetHeader("STARTDIR")
    } else {
        c.String(404,"Startdir not found
\n")
        return
    }

    m = make(map[int]string)
    keys = nil

    filepath.Walk(startdir,walkpath)

    for k := range m {
        keys = append(keys, k)
    }
    sort.Ints(keys)

    for _, k := range keys {
        t := time.Date(time.Now().Year(),time.Now().Month(),time.Now().Day(),time.Now().Hour(),k,time.Now().Second(),time.Now().Nanosecond(),loc)
        durStr, err := durationfmt.Format(time.Since(t), "%h:%m")

        if err != nil {
            fmt.Println(err)
        } else {
            //fmt.Println(durStr)
            fmt.Printf("Key: %s Value: %s\n", durStr , m[k])
            c.String(200,"Minutes: %s File: %s\n", durStr, m[k])
        }
    }
}

func walkpath(path string, f os.FileInfo, err error) error {

  if err != nil {
        fmt.Println(err)
    } else {
        if filext.MatchString(path) {
            age := time.Now().Sub(f.ModTime())
            path_new := strings.Replace(path,"/videos/","",1)
            // path_new := strings.Replace(path,"..\\","",1)
            /*
            fmt.Printf("Path: %s, ModTime: %s, Age: %s
\n", walker.Path(), walker.Stat().ModTime(), age)
            c.String(200,"Path: %s, ModTime: %s, Age: %s
\n", walker.Path(), walker.Stat().ModTime(), age)
            */
            fmt.Printf("Path: %s, Age: %d age minutes %0.2f
\n", path_new, age, age.Minutes())
            m[int(age.Minutes())]=path_new
            //c.String(200,"Path: %s, Age: %0.2f
\n", path, age.Minutes())
        }
    //fmt.Printf("%s with %d bytes at motime %s\n", path,f.Size(), f.ModTime())
}
    return nil
}

What I want to do is a sorted output of files based on filext als filter and the modtime as sort criteria.

I was able to fulfil the most part of the request but the output looks ugly as you can see below.

I have used https://github.com/davidscholberg/go-durationfmt to format the duration but the output looks ugly or I missus the library.

Minutes: 0:6 File: upload/dir003/file1.m4v
Minutes: 0:5 File: transfer/dir5/file2.jpg
Minutes: -5:-48 File: transfer/dir001/file.mp4
Minutes: -6:-21 File: transfer/03.jpg
Minutes: -6:-22 File: transfer/02.mp4

Body:
For example, to provide a custom format for a duration,

package main

import (
    "fmt"
    "time"
)

func fmtDuration(d time.Duration) string {
    d = d.Round(time.Minute)
    h := d / time.Hour
    d -= h * time.Hour
    m := d / time.Minute
    return fmt.Sprintf("%02d:%02d", h, m)
}

func main() {
    modTime := time.Now().Round(0).Add(-(3600 + 60 + 45) * time.Second)
    since := time.Since(modTime)
    fmt.Println(since)
    durStr := fmtDuration(since)
    fmt.Println(durStr)
}

Playground: https://play.golang.org/p/HT4bFfoA5r

Output:

1h1m45s
01:02

If you want to sort on a duration then use the Go sort package. I would sort on ModTime to defer the calculation of the duration, Since(ModTime), to be accurate at the time it is printed. For example,

package main

import (
    "fmt"
    "os"
    "path/filepath"
    "sort"
    "strings"
    "time"
)

func isVideo(path string) bool {
    videos := []string{".mp4", ".m4v", ".h264"}
    ext := strings.ToLower(filepath.Ext(path))
    for _, video := range videos {
        if ext == video {
            return true
        }
    }
    return false
}

type modTimeInfo struct {
    path    string
    modTime time.Time
}

func walkModTime(root string) ([]modTimeInfo, error) {
    var infos []modTimeInfo
    err := filepath.Walk(
        root,
        func(path string, info os.FileInfo, err error) error {
            if err != nil {
                return err
            }
            if info.Mode().IsRegular() {
                path = filepath.Clean(path)
                if !isVideo(path) {
                    return nil
                }
                sep := string(filepath.Separator)
                dir := sep + `Videos` + sep
                path = strings.Replace(path, dir, sep, 1)
                infos = append(infos, modTimeInfo{
                    path:    path,
                    modTime: info.ModTime()},
                )
            }
            return nil
        },
    )
    if err != nil {
        return nil, err
    }
    return infos, nil
}

func sortModTime(infos []modTimeInfo) {
    sort.SliceStable(
        infos,
        func(i, j int) bool {
            return infos[i].modTime.Before(infos[j].modTime)
        },
    )
}

func fmtAge(d time.Duration) string {
    d = d.Round(time.Minute)
    h := d / time.Hour
    d -= h * time.Hour
    m := d / time.Minute
    return fmt.Sprintf("%02d:%02d", h, m)
}

func main() {
    root := `/home/peter/Videos` // Testing ...
    infos, err := walkModTime(root)
    if err != nil {
        fmt.Println(err)
        return
    }
    sortModTime(infos)
    now := time.Now()
    for _, info := range infos {
        age := fmtAge(now.Sub(info.modTime))
        fmt.Println("Age (H:M):", age, "File:", info.path)
    }
}

Playground: https://play.golang.org/p/j2TUmJdAi4


问:
javascript object grouped by multiple attributes using js
Here is my JavaScript object. I want to have a method to dynamically generate an object grouped by one or more attributes. The parameter attrs is an array, which contains some attributes for grouping.

```<code>var input= [
    {fistname:'Joe', age:'10', sex:'boy', class:'3'},
    {fistname:'Tom', age:'11', sex:'boy', class:'3'},
    {fistname:'Amily', age:'10', sex:'girl', class:'3'},
    {fistname:'Bob', age:'11', sex:'boy',class:'4'},
    {fistname:'Susan', age:'12', sex:'girl', class:'4'}
]

var attrs = ['age', 'class'];

function json2group(input, attrs){...}
</code>```

Result:

```<code>[
    {
        label:'10',
        groups:[
            {
                label:'3',
                groups:[
                    {fistname:'Joe', age:'10', sex:'boy', class:'3'},
                    {fistname:'Amily', age:'10', sex:'girl', class:'3'}
                ]
            }
        ]
    },
    {
        label:'11',
        groups:[
            {
                label:'3',
                groups:[
                    {fistname:'Tom', age:'11', sex:'boy', class:'3'}
                ]
            },
            {
                label:'4',
                groups:[
                    {fistname:'Bob', age:'11', sex:'boy',class:'4'}
                ]
            }
        ]
    },
    {
        label:'12',
        groups:[
            {
                label:'4',
                groups:[
                    {fistname:'Susan', age:'12', sex:'girl', class:'4'}
                ]
            }
        ]
    }
]
</code>```

Please help me.

答:
You can use pure JS.

```<code>var input = [
    {fistname:'Joe', age:'10', sex:'boy', class:'3'},
    {fistname:'Tom', age:'11', sex:'boy', class:'3'},
    {fistname:'Amily', age:'10', sex:'girl', class:'3'},
    {fistname:'Bob', age:'11', sex:'boy',class:'4'},
    {fistname:'Susan', age:'12', sex:'girl', class:'4'}
];

var attrs = ['age', 'class'];

function GroupByArbitraryNumOfGroup(array, attrs) {
    var output = [];
    for (var i = 0; i < array.length; ++i) {
        var ele = array[i];
        var groups = output;
        for (var j = 0; j < attrs.length; ++j) {
            var attr = attrs[j];
            var value = ele[attr];
            var gs = groups.filter(function(g) {
                return g.hasOwnProperty('label') && g['label'] == value;
            });
            if (gs.length == 0) {
                var g = {};
                g['label'] = value;
                g['groups'] = [];
                groups.push(g);
                groups = g['groups'];
            } else {
                groups = gs[0]['groups'];
            }
        }
        groups.push(ele);
    }
    return output;
}

var o = GroupByArbitraryNumOfGroup(input, attrs);
</code>```

And you will get o as

```<code>[{
    'label': '10',
    'groups': [{
        'label': '3',
        'groups': [{
            'fistname': 'Joe',
            'age': '10',
            'sex': 'boy',
            'class': '3'
        }, {
            'fistname': 'Amily',
            'age': '10',
            'sex': 'girl',
            'class': '3'
        }]
    }]
}, {
    'label': '11',
    'groups': [{
        'label': '3',
        'groups': [{
            'fistname': 'Tom',
            'age': '11',
            'sex': 'boy',
            'class': '3'
        }]
    }, {
        'label': '4',
        'groups': [{
            'fistname': 'Bob',
            'age': '11',
            'sex': 'boy',
            'class': '4'
        }]
    }]
}, {
    'label': '12',
    'groups': [{
        'label': '4',
        'groups': [{
            'fistname': 'Susan',
            'age': '12',
            'sex': 'girl',
            'class': '4'
        }]
    }]
}]
</code>```

Body:
Here is my JavaScript object. I want to have a method to dynamically generate an object grouped by one or more attributes. The parameter attrs is an array, which contains some attributes for grouping.

var input= [
    {fistname:'Joe', age:'10', sex:'boy', class:'3'},
    {fistname:'Tom', age:'11', sex:'boy', class:'3'},
    {fistname:'Amily', age:'10', sex:'girl', class:'3'},
    {fistname:'Bob', age:'11', sex:'boy',class:'4'},
    {fistname:'Susan', age:'12', sex:'girl', class:'4'}
]

var attrs = ['age', 'class'];

function json2group(input, attrs){...}

Result:

[
    {
        label:'10',
        groups:[
            {
                label:'3',
                groups:[
                    {fistname:'Joe', age:'10', sex:'boy', class:'3'},
                    {fistname:'Amily', age:'10', sex:'girl', class:'3'}
                ]
            }
        ]
    },
    {
        label:'11',
        groups:[
            {
                label:'3',
                groups:[
                    {fistname:'Tom', age:'11', sex:'boy', class:'3'}
                ]
            },
            {
                label:'4',
                groups:[
                    {fistname:'Bob', age:'11', sex:'boy',class:'4'}
                ]
            }
        ]
    },
    {
        label:'12',
        groups:[
            {
                label:'4',
                groups:[
                    {fistname:'Susan', age:'12', sex:'girl', class:'4'}
                ]
            }
        ]
    }
]

Please help me.

Body:
You can use pure JS.

var input = [
    {fistname:'Joe', age:'10', sex:'boy', class:'3'},
    {fistname:'Tom', age:'11', sex:'boy', class:'3'},
    {fistname:'Amily', age:'10', sex:'girl', class:'3'},
    {fistname:'Bob', age:'11', sex:'boy',class:'4'},
    {fistname:'Susan', age:'12', sex:'girl', class:'4'}
];

var attrs = ['age', 'class'];

function GroupByArbitraryNumOfGroup(array, attrs) {
    var output = [];
    for (var i = 0; i < array.length; ++i) {
        var ele = array[i];
        var groups = output;
        for (var j = 0; j < attrs.length; ++j) {
            var attr = attrs[j];
            var value = ele[attr];
            var gs = groups.filter(function(g) {
                return g.hasOwnProperty('label') && g['label'] == value;
            });
            if (gs.length == 0) {
                var g = {};
                g['label'] = value;
                g['groups'] = [];
                groups.push(g);
                groups = g['groups'];
            } else {
                groups = gs[0]['groups'];
            }
        }
        groups.push(ele);
    }
    return output;
}

var o = GroupByArbitraryNumOfGroup(input, attrs);

And you will get o as

[{
    'label': '10',
    'groups': [{
        'label': '3',
        'groups': [{
            'fistname': 'Joe',
            'age': '10',
            'sex': 'boy',
            'class': '3'
        }, {
            'fistname': 'Amily',
            'age': '10',
            'sex': 'girl',
            'class': '3'
        }]
    }]
}, {
    'label': '11',
    'groups': [{
        'label': '3',
        'groups': [{
            'fistname': 'Tom',
            'age': '11',
            'sex': 'boy',
            'class': '3'
        }]
    }, {
        'label': '4',
        'groups': [{
            'fistname': 'Bob',
            'age': '11',
            'sex': 'boy',
            'class': '4'
        }]
    }]
}, {
    'label': '12',
    'groups': [{
        'label': '4',
        'groups': [{
            'fistname': 'Susan',
            'age': '12',
            'sex': 'girl',
            'class': '4'
        }]
    }]
}]


问:
react native navigator.geolocation.getCurrentPosition not working
I am using a real android device (version 5.1)

I am able to determine my position using react-native-maps (correct blue point position on map inside my app ) + I am able use google maps app and go to my position (GPS works).

I am using a big timeout, toggling enableHighAccuracy to true and false, remove options ... etc . all failed to get navigator.geolocation to get data.

Here is my code:

```<code>var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

function success(pos) {
  var crd = pos.coords;

  console.log('Your current position is:');
  console.log(`Latitude : ${crd.latitude}`);
  console.log(`Longitude: ${crd.longitude}`);
  console.log(`More or less ${crd.accuracy} meters.`);
};

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
};

navigator.geolocation.getCurrentPosition(success, error, options);
</code>```

I am getting : ERROR(3): Location request timed out

答:
Two things.

1) That is actually not a high timeout for a high accuracy response if the coordinates are not cached
2) Some devices have problems with the highAccuracy setting.

Try putting 30000 ms as timeout and remove the high accuracy until you find one setting that works.

Edit: I found the long bug I was remembering form React Native: https://github.com/facebook/react-native/issues/7495

So, try this:

1) Remove maximumAge property
2) If that does not work, remove the third parameter and use the default values from the native module. Meaning, don't send the options object. That should work.

Body:
I am using a real android device (version 5.1)

I am able to determine my position using react-native-maps (correct blue point position on map inside my app ) + I am able use google maps app and go to my position (GPS works).

I am using a big timeout, toggling enableHighAccuracy to true and false, remove options ... etc . all failed to get navigator.geolocation to get data.

Here is my code:

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

function success(pos) {
  var crd = pos.coords;

  console.log('Your current position is:');
  console.log(`Latitude : ${crd.latitude}`);
  console.log(`Longitude: ${crd.longitude}`);
  console.log(`More or less ${crd.accuracy} meters.`);
};

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
};

navigator.geolocation.getCurrentPosition(success, error, options);

I am getting : ERROR(3): Location request timed out


问:
Throwing an exception from Q_INVOKABLE method?
Trying to understand the best practices for a Qt/QML based application, where we have methods marked as Q_INVOKABLE. What are the ramifications if we throw an exception from one of these methods?

```<code>class Class
{
    ...
    Q_INVOKABLE void method() { throw std::logic_error(); }
};
</code>```

Can QML handle this error, or will I crash the program?

答:
The Q_INVOKABLE macro just marks up the function so that it can be called by using QMetaObject::invokeMethod(). It doesn't really change how exceptions are dealt with in Qt.

For that, it's important to distinguish between slots that are called via a connection, and those that are invoked directly as normal functions. If a method is invoked through a signal-slot connection, it is undefined what happens when you throw an exception, unless you actually handle the exception within the slot. I.e., in a slot you must write:

```<code>void Class::method() {
    try {
        // code that might throw logic_error
    } catch (std::logic_error &err) {
    }
}
</code>```

You cannot omit the catch() statement.

On the other hand, if the method is called directly as a function, then a bare throw is fine. However, it must be caught and handled wherever the method is called. I.e., you must write:

```<code>try {
    obj.method();
catch (std::logic_error &err) {
    // error-handling
}
</code>```

This is really all because error handling in the Qt application event-loop isn't well-defined. See the docs on Qt 5.9 for more information.

Body:
Trying to understand the best practices for a Qt/QML based application, where we have methods marked as Q_INVOKABLE. What are the ramifications if we throw an exception from one of these methods?

class Class
{
    ...
    Q_INVOKABLE void method() { throw std::logic_error(); }
};

Can QML handle this error, or will I crash the program?

Body:
The Q_INVOKABLE macro just marks up the function so that it can be called by using QMetaObject::invokeMethod(). It doesn't really change how exceptions are dealt with in Qt.

For that, it's important to distinguish between slots that are called via a connection, and those that are invoked directly as normal functions. If a method is invoked through a signal-slot connection, it is undefined what happens when you throw an exception, unless you actually handle the exception within the slot. I.e., in a slot you must write:

void Class::method() {
    try {
        // code that might throw logic_error
    } catch (std::logic_error &err) {
    }
}

You cannot omit the catch() statement.

On the other hand, if the method is called directly as a function, then a bare throw is fine. However, it must be caught and handled wherever the method is called. I.e., you must write:

try {
    obj.method();
catch (std::logic_error &err) {
    // error-handling
}

This is really all because error handling in the Qt application event-loop isn't well-defined. See the docs on Qt 5.9 for more information.


问:
UIWebView User-Agent is not properly set for custom value
If we want to change the value of user agent from

```<code>Mozilla/5.0 (iPhone; CPU iPhone OS 10_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Mobile/14B72
</code>```

to

```<code>Mozilla/5.0 (iPad; CPU OS 10_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Mobile/14B72
</code>```

i.e. On iPhone app, my app needs to set the User-Agent of iPad.

My code looks like

```<code>class ViewController: UIViewController, UIWebViewDelegate {
    @IBOutlet weak var webView: UIWebView!
    var userAgent:String = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        userAgent = self.webView.stringByEvaluatingJavaScript(from: "navigator.userAgent")!

        let range = userAgent.range(of: "iPhone")

        if range != nil {
            userAgent = userAgent.replacingCharacters(in: range!, with: "iPad")
            userAgent = userAgent.replacingOccurrences(of: "iPhone", with: "")
        }
        userAgent = userAgent.replacingOccurrences(of: "  ", with: " ")

        UserDefaults.standard.register(defaults: ["UserAgent": userAgent])

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        self.webView.loadRequest(URLRequest(url: URL(string: "http://www.google.com")!))
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let userAgent = request.allHTTPHeaderFields!["User-Agent"]
        print("\(userAgent)")
        return true
    }

}
</code>```

In above case the User-Agent is not set and keeps default value

Instead of logic to manipulate the string to look like iPad's User-Agent, If I change and set hard coded value in viewDidLoad like

```<code>UserDefaults.standard.register(defaults: ["UserAgent": “Mozilla/5.0 (iPad; CPU OS 10_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Mobile/14B72”])
</code>```

then also it is not updated.

But if I hard code like

```<code>UserDefaults.standard.register(defaults: ["UserAgent": “MyValue”])
</code>```

then it is properly set

Any idea, what went wrong here?

答:
There is an interesting workout for this that it helped me in a similar project:

It is true that once you get the value of a http header you can not modify it later on (is it a bug?)

because of that you cant obtain the current value and modify it

That is true for one instance of a webview object. That is why you can add a temporal object with the "hidden" property with true value, so it wont appear in your GUI and then obtain the value from this object so you can modify it on the original object:

```<code> @IBOutlet var tmpWebView: UIWebView!

 @IBOutlet var webview: UIWebView!

 var newAgent = tmpWebView.stringByEvaluatingJavaScript(from: "navigator.userAgent")! + " Added new string"
 UserDefaults.standard.register(defaults: ["UserAgent": newAgent])
</code>```

Body:
If we want to change the value of user agent from

Mozilla/5.0 (iPhone; CPU iPhone OS 10_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Mobile/14B72

to

Mozilla/5.0 (iPad; CPU OS 10_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Mobile/14B72

i.e. On iPhone app, my app needs to set the User-Agent of iPad.

My code looks like

class ViewController: UIViewController, UIWebViewDelegate {
    @IBOutlet weak var webView: UIWebView!
    var userAgent:String = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        userAgent = self.webView.stringByEvaluatingJavaScript(from: "navigator.userAgent")!

        let range = userAgent.range(of: "iPhone")

        if range != nil {
            userAgent = userAgent.replacingCharacters(in: range!, with: "iPad")
            userAgent = userAgent.replacingOccurrences(of: "iPhone", with: "")
        }
        userAgent = userAgent.replacingOccurrences(of: "  ", with: " ")

        UserDefaults.standard.register(defaults: ["UserAgent": userAgent])

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        self.webView.loadRequest(URLRequest(url: URL(string: "http://www.google.com")!))
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let userAgent = request.allHTTPHeaderFields!["User-Agent"]
        print("\(userAgent)")
        return true
    }

}

In above case the User-Agent is not set and keeps default value

Instead of logic to manipulate the string to look like iPad's User-Agent, If I change and set hard coded value in viewDidLoad like

UserDefaults.standard.register(defaults: ["UserAgent": “Mozilla/5.0 (iPad; CPU OS 10_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Mobile/14B72”])

then also it is not updated.

But if I hard code like

UserDefaults.standard.register(defaults: ["UserAgent": “MyValue”])

then it is properly set

Any idea, what went wrong here?

Body:
There is an interesting workout for this that it helped me in a similar project:

It is true that once you get the value of a http header you can not modify it later on (is it a bug?)

because of that you cant obtain the current value and modify it

That is true for one instance of a webview object. That is why you can add a temporal object with the "hidden" property with true value, so it wont appear in your GUI and then obtain the value from this object so you can modify it on the original object:

 @IBOutlet var tmpWebView: UIWebView!

 @IBOutlet var webview: UIWebView!

 var newAgent = tmpWebView.stringByEvaluatingJavaScript(from: "navigator.userAgent")! + " Added new string"
 UserDefaults.standard.register(defaults: ["UserAgent": newAgent])


问:
Self Referencing Table SQL query
I've table with four columns id, name, designation, manager_id.

Table schema:

```<code>CREATE TABLE "Employee_Information"
(
    "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    "name" varchar,
    "designation" varchar,
    "manager_id" integer references employee_information(id)
);
</code>```

It is as follows

```<code>ID  Name    Designation   Manager_id
-------------------------------------
1   Raja    CEO
2   Mani    CTO           1
3   Kavi    COO           1
4   Murugan Head          3
5   Alpha   Head(Fin)     4
7   Kannan  Head          4
</code>```

Employee hierarchy is as follows:

```<code>Raja CEO
    Mani CTO
    Kavi COO
               Murugan Head
                       Alpha Head(Fin)
                           Kannan Head
       Beta CFO
       Delta Head
</code>```

I want an SQL query to display all possible manager for particular employee. His Juniors or other sub level employees name are not supposed to be in the results set.

Display all others employees on same level or above.

I'm unable to figure out a solution for this.

答:
Below query will work:

```<code>SELECT Name+' '+Designation AS 'Manager' FROM table1 WHERE ID=(SELECT manager_id FROM table1 WHERE ID='<employee_id>')
</code>```

If you are executing this query through any other language, you can just pass variable holding employee_id

Title: Self Referencing Table SQL query

Body:
I've table with four columns id, name, designation, manager_id.

Table schema:

CREATE TABLE "Employee_Information"
(
    "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    "name" varchar,
    "designation" varchar,
    "manager_id" integer references employee_information(id)
);

It is as follows

ID  Name    Designation   Manager_id
-------------------------------------
1   Raja    CEO
2   Mani    CTO           1
3   Kavi    COO           1
4   Murugan Head          3
5   Alpha   Head(Fin)     4
7   Kannan  Head          4

Employee hierarchy is as follows:

Raja CEO
    Mani CTO
    Kavi COO
               Murugan Head
                       Alpha Head(Fin)
                           Kannan Head
       Beta CFO
       Delta Head

I want an SQL query to display all possible manager for particular employee. His Juniors or other sub level employees name are not supposed to be in the results set.

Display all others employees on same level or above.

I'm unable to figure out a solution for this.

Body:
Below query will work:

SELECT Name+' '+Designation AS 'Manager' FROM table1 WHERE ID=(SELECT manager_id FROM table1 WHERE ID='<employee_id>')

If you are executing this query through any other language, you can just pass variable holding employee_id


问:
How to generate a pdf file from the information of a form in Angular?
I am creating a project for a job in the university and my project will be created in angular 4 in which a form will be filled and then using this information in conjunction with other texts that I have stored I wish that a pdf letter will be generated .
In the end I have to upload the project to firebase

How could I do this in Angular?
Some idea of the structure of steps that could follow

Thank you for your answers.

答:
If, in the end, it has to be uploaded to Firebase. I'd suggest you don't do it in Angular / the browser directly, rather a Cloud Function for Firebase.

Check out the Cloud Functions samples repo https://github.com/firebase/functions-samples and something like PDFKit to get started.


问:
PHP Laravel 5.5 receiving multiple relations
I have a short issue regarding relations in Laravel. I recently created a task management list, which listed all the todo lists for each user. Each user had his own todo list, and no one could watch it.

It had the following structure:

```<code>id (int)
user_id (int)
title (string)
description (text)
done (bool)
finished_until (datetime)
created_at (datetime)
updated_at (datetime)
</code>```

I had a normal relation going on with

```<code>public function tasks()
{
  return $this->hasMany('App\Task');
}
</code>```

This works all perfectly fine. Now I added the option of adding additional relations for the user. What I did was:

```<code>public function tasksRelated()
{
  return $this->belongsToMany('App\Task', 'task_relations', 'task_id');
}
</code>```

This also worked fine. I was wondering if there is now a way to get ALL tasks at the same time related to the user (own and related ones)?

答:
$user->tasks and $users->tasksRelated will both be eloquent collections.

You can merge them via merge():

```<code>$ownTasks = $user->tasks;
$relatedTasks = $user->tasksRelated;
$allTasks = $ownTasks->merge($relatedTasks);
</code>```

Body:
I have a short issue regarding relations in Laravel. I recently created a task management list, which listed all the todo lists for each user. Each user had his own todo list, and no one could watch it.

It had the following structure:

id (int)
user_id (int)
title (string)
description (text)
done (bool)
finished_until (datetime)
created_at (datetime)
updated_at (datetime)

I had a normal relation going on with

public function tasks()
{
  return $this->hasMany('App\Task');
}

This works all perfectly fine. Now I added the option of adding additional relations for the user. What I did was:

public function tasksRelated()
{
  return $this->belongsToMany('App\Task', 'task_relations', 'task_id');
}

This also worked fine. I was wondering if there is now a way to get ALL tasks at the same time related to the user (own and related ones)?

Body:
$user->tasks and $users->tasksRelated will both be eloquent collections.

You can merge them via merge():

$ownTasks = $user->tasks;
$relatedTasks = $user->tasksRelated;
$allTasks = $ownTasks->merge($relatedTasks);


问:
php hash_hmac to c# - webresponse "NONCE_NOT_PROVIDED"
I try to convert a php-code to c#

php

```<code>$apikey='xxx';
$apisecretkey='yyy';
$nonce=time();
$uri='https://website.com/api/getsomething?apikey='.$apikey.'&nonce='.$nonce;
$sign=hash_hmac('sha512',$uri,$apisecretkey);
$resource = curl_init($uri);
curl_setopt($resource, CURLOPT_HTTPHEADER, array('apisign:'.$sign));
$execResult = curl_exec($resource);
$obj = ($execResult);
</code>```

and here my C#

```<code>WebRequest _WebRequest;
WebResponse _WebResponse;
string apikey = "xxx";
string apisecret = "yyy";
string nonce = ((int)(DateTime.UtcNow - new DateTime(1970,1,1)).TotalSeconds).ToString();
string uri = $"https://website.com/api/getsomething?apikey={apikey}nonce={nonce}";
string _Hash_hmac = Hash_hmac(uri, apisecret);

_WebRequest = WebRequest.Create(uri);
_WebRequest.Headers["apisign"] = _Hash_hmac;

_WebResponse = _WebRequest.GetResponse();
</code>```

The Code for Hash-hmac I use this C# equivalent to hash_hmac in PHP

The Webresponse is always "NONCE_NOT_PROVIDED"

I checked the outcome from the hash_hmac with the one in php - they are the same.
And also try string ToUpper and ToLower.

What I am doing wrong?

答:
Aren't you missing an ampersand (&)?

```<code>apikey={apikey}nonce={nonce}
</code>```

becomes

```<code>apikey={apikey}&nonce={nonce}
</code>```

I would advise reading your code more closely with these kinds of errors.

Body:
I try to convert a php-code to c#

php

$apikey='xxx';
$apisecretkey='yyy';
$nonce=time();
$uri='https://website.com/api/getsomething?apikey='.$apikey.'&nonce='.$nonce;
$sign=hash_hmac('sha512',$uri,$apisecretkey);
$resource = curl_init($uri);
curl_setopt($resource, CURLOPT_HTTPHEADER, array('apisign:'.$sign));
$execResult = curl_exec($resource);
$obj = ($execResult);

and here my C#

WebRequest _WebRequest;
WebResponse _WebResponse;
string apikey = "xxx";
string apisecret = "yyy";
string nonce = ((int)(DateTime.UtcNow - new DateTime(1970,1,1)).TotalSeconds).ToString();
string uri = $"https://website.com/api/getsomething?apikey={apikey}nonce={nonce}";
string _Hash_hmac = Hash_hmac(uri, apisecret);

_WebRequest = WebRequest.Create(uri);
_WebRequest.Headers["apisign"] = _Hash_hmac;

_WebResponse = _WebRequest.GetResponse();

The Code for Hash-hmac I use this C# equivalent to hash_hmac in PHP

The Webresponse is always "NONCE_NOT_PROVIDED"

I checked the outcome from the hash_hmac with the one in php - they are the same.
And also try string ToUpper and ToLower.

What I am doing wrong?

Body:
Aren't you missing an ampersand (&)?

apikey={apikey}nonce={nonce}

becomes

apikey={apikey}&nonce={nonce}

I would advise reading your code more closely with these kinds of errors.


问:
How to change the size of a HTML button?
So I have this line of code put into Sublime Text:

```<code><input id="MM" type="button" style="width: 150px" >
</code>```

But how  do I change the length?

答: Check the developer options maybe your input button is reading other style... or you should put !important to your style.. something like this.. width: 150px !important;</p>

Body:
So I have this line of code put into Sublime Text:

<input id="MM" type="button" style="width: 150px" >

But how  do I change the length?


问:
How to throw an exception in ZSH
I am writing a function and I want to throw an exception when the input is invalid. When I googled I found that there is a throw MyException command but when I try to use it like this:

```<code>#!  /usr/bin/zsh
throw Exception
</code>```

The script throws the following error:

```<code>$ ./test.sh
./test.sh:2: command not found: throw
</code>```

Is there an mechanism to throw error in ZSH? If so are there any resources?

答:
throw and catch must be loaded first; they aren't built directly into the shell.

```<code>autoload throw catch
</code>```

They are documented in zshcontrib(1), under EXCEPTION HANDLING, although it isn't immediately obvious that they need to be loaded.

Title: How to throw an exception in ZSH

Body:
I am writing a function and I want to throw an exception when the input is invalid. When I googled I found that there is a throw MyException command but when I try to use it like this:

#!  /usr/bin/zsh
throw Exception

The script throws the following error:

$ ./test.sh
./test.sh:2: command not found: throw

Is there an mechanism to throw error in ZSH? If so are there any resources?

Body:
throw and catch must be loaded first; they aren't built directly into the shell.

autoload throw catch

They are documented in zshcontrib(1), under EXCEPTION HANDLING, although it isn't immediately obvious that they need to be loaded.


问:
React Native Local Images not showing on android device
local images show in emulator iOS+Android but on android device just dont.
Any ideas?</p>

```<code><View style={styles.imgContainer}>
        <Image
          source={require('../../../../data/images/success.jpg')}
        />
      </View>
</code>```

答:
You need to bundle and install the build every time you add a resource like an image. The resource manager that bundles the JS does not do that in live preview. </p>

<p>You are probably updating the emulator but not the build for the device. </p>

Body:
local images show in emulator iOS+Android but on android device just dont.
Any ideas?

<View style={styles.imgContainer}>
        <Image
          source={require('../../../../data/images/success.jpg')}
        />
      </View>

Body:
You need to bundle and install the build every time you add a resource like an image. The resource manager that bundles the JS does not do that in live preview.

You are probably updating the emulator but not the build for the device.


问:
Can't compare two strings in C++
I am facig some problems with my code in c++. It seems like I cant compare strings use the if operator. This is my code:

```<code>//correct creds
std::string uname ("admin");
std::string pass ("password");

//input creds
std::string r_uname;
std::string r_pass;

//ui
printf("%s \n", "Please enter username");
scanf("%s", r_uname);
printf("%s \n", "Please enter password");
scanf("%s", r_pass);

//cred check
if((r_uname == uname) && (r_pass == pass)){
    printf("%s", "You are in");
}
else{
    printf("%s", "Wrong username/password");
}
</code>```

libraries included: stdio.h and string

Thanks in advance.

答:
You are using C++, the default is to use std::cout and std::cin from iostream unless you have a good reason not to.

In your case, you are using scanf() to read the user input. scanf() can only read into a C styled string AKA char arrays. I don't think your code will even compile in most compilers because you pass in std::string. Moreover, you are comparing C styled strings which just compares the memory addresses of the beginning of the arrays. You should be using strcmp() to compare C strings.

Here is how you use C++ to compare strings:

```<code>#include <iostream>
#include <string>

int main()
{
    //correct creds
    std::string uname ("admin");
    std::string pass ("password");

    //input creds
    std::string r_uname;
    std::string r_pass;

    std::cout << "Enter username: " << std::endl;
    cin >> r_uname;

    std:: cout << "Enter password: " << std::endl;
    cin >> r_pass;

    //cred check
    if ((r_uname == uname) && (r_pass == pass)){
        std::cout << "You're in!" << std::endl;
    } else {
        std::cout << "Wrong credentials" << std::endl;
    }
    return 0;
}
</code>```

Title: Can't compare two strings in C++

Body:
I am facig some problems with my code in c++. It seems like I cant compare strings use the if operator. This is my code:

//correct creds
std::string uname ("admin");
std::string pass ("password");

//input creds
std::string r_uname;
std::string r_pass;

//ui
printf("%s \n", "Please enter username");
scanf("%s", r_uname);
printf("%s \n", "Please enter password");
scanf("%s", r_pass);

//cred check
if((r_uname == uname) && (r_pass == pass)){
    printf("%s", "You are in");
}
else{
    printf("%s", "Wrong username/password");
}

libraries included: stdio.h and string

Thanks in advance.

Body:
You are using C++, the default is to use std::cout and std::cin from iostream unless you have a good reason not to.

In your case, you are using scanf() to read the user input. scanf() can only read into a C styled string AKA char arrays. I don't think your code will even compile in most compilers because you pass in std::string. Moreover, you are comparing C styled strings which just compares the memory addresses of the beginning of the arrays. You should be using strcmp() to compare C strings.

Here is how you use C++ to compare strings:

#include <iostream>
#include <string>

int main()
{
    //correct creds
    std::string uname ("admin");
    std::string pass ("password");

    //input creds
    std::string r_uname;
    std::string r_pass;

    std::cout << "Enter username: " << std::endl;
    cin >> r_uname;

    std:: cout << "Enter password: " << std::endl;
    cin >> r_pass;

    //cred check
    if ((r_uname == uname) && (r_pass == pass)){
        std::cout << "You're in!" << std::endl;
    } else {
        std::cout << "Wrong credentials" << std::endl;
    }
    return 0;
}


答:
to use string in C++, you should use cin or cout instead of scanf or printf.
To use cin in C++, you need to include

Here is the code

```<code>#include <stdio.h>
#include <string>
*#include <iostream>*

int main(){
  //correct creds
  std::string uname ("admin");
  std::string pass ("password");

  //input creds
  std::string r_uname;
  std::string r_pass;

  //ui
  printf("%s \n", "Please enter username");
  //scanf("%s", r_uname);
  *std::cin >> r_uname;*
  printf("%s \n", "Please enter password");
  //scanf("%s", r_pass);
  *std::cin >> r_pass;*

  //cred check
  if((r_uname == uname) && (r_pass == pass)){
      printf("%s", "You are in");
  }
  else{
      printf("%s", "Wrong username/password");
  }

}
</code>```

Title: Can't compare two strings in C++

Body:
to use string in C++, you should use cin or cout instead of scanf or printf.
To use cin in C++, you need to include

Here is the code

#include <stdio.h>
#include <string>
*#include <iostream>*

int main(){
  //correct creds
  std::string uname ("admin");
  std::string pass ("password");

  //input creds
  std::string r_uname;
  std::string r_pass;

  //ui
  printf("%s \n", "Please enter username");
  //scanf("%s", r_uname);
  *std::cin >> r_uname;*
  printf("%s \n", "Please enter password");
  //scanf("%s", r_pass);
  *std::cin >> r_pass;*

  //cred check
  if((r_uname == uname) && (r_pass == pass)){
      printf("%s", "You are in");
  }
  else{
      printf("%s", "Wrong username/password");
  }

}


问:
Generating Images From Dataset Of Images Using A Neural Network
I'm not looking for a chunk of code as a solution, just the name of the model I'd need to implement or some links would be nice.

My problem is I have a dataset I've made of a few hundred 128x128 images (abstract paintings) - I'd like to simply generate more images similar to these images using a neural network (preferably no input needed for the network, except maybe random values?), but it's unclear as to how I'd go about this.

One solution I've thought about but haven't tried out yet is making an LSTM neural network, turning the paintings into 1D arrays of pixel values, and feeding the arrays to the network (LSTM networks are real good at learning sequences) - but if I'd want to work with larger images, this might not be very practical.

Any info is greatly appreciated. Thanks!

答:
GANs (generative adversarial networks) would be appropriate in this case. GANs rely on two separate neural networks and, when properly trained, can be used to generate new images (a process known as hallucinating) that are similar to a collection of known images.

there are many examples of using GANs to generate new images of numbers from the canonical mnist dataset. naturally, you can replace mnist with your abstract paintings.


问:
How to get multiple controls to fire same event/command in Silverlight / XAML?
I am using Mvvm-Light Commands to route events from my Views to my ViewModels. Works great.

But I think I can be more elegant. This is actually probably just a standard XAML question:

I want to change this (10 buttons all with Click="keypadButton_Click" for their event handler):

```<code><Button  Name="button1" Content="1" Grid.Row="0" Grid.Column="0" Click="keypadButton_Click" />
<Button  Name="button2" Content="2" Grid.Row="0" Grid.Column="1" Click="keypadButton_Click"/>
<Button  Name="button3" Content="3" Grid.Row="0" Grid.Column="2" Click="keypadButton_Click"/>
<Button  Name="button4" Content="4" Grid.Row="1" Grid.Column="0" Click="keypadButton_Click"/>
<Button  Name="button5" Content="5" Grid.Row="1" Grid.Column="1" Click="keypadButton_Click"/>
<Button  Name="button6" Content="6" Grid.Row="1" Grid.Column="2" Click="keypadButton_Click"/>
<Button  Name="button7" Content="7" Grid.Row="2" Grid.Column="0" Click="keypadButton_Click"/>
<Button  Name="button8" Content="8" Grid.Row="2" Grid.Column="1" Click="keypadButton_Click"/>
<Button  Name="button9" Content="9" Grid.Row="2" Grid.Column="2" Click="keypadButton_Click"/>
<Button  Name="button0" Content="0" Grid.Row="3" Grid.Column="1" Click="keypadButton_Click"/>
</code>```

To 10 of these:

```<code><Button  x:Name="button1" Content="1" Grid.Row="0" Grid.Column="0">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <Command:EventToCommand
               Command="{Binding KeyPadButtonCommand}"
               CommandParameter="{Binding ElementName=button1, Path=Content }"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>
</code>```

But I don't want that much XAML. I would think there would be a way to "macroize" the Trigger so it would look something like this:

```<code><Button  Name="button1" Content="1" Grid.Row="0" Grid.Column="0"
         Click="{Binding _SendTheEventHere_}" />
</code>```

Where "{Binding _SendTheEventHere_}" should be replaced with some magic incantation that I am clueless about, but I know some wizard here on stackoverflow knows :-).

Make sense?

答:
I have just run a test using the following XAML and it seems to work successfully :-

Your Button XAML :-

```<code><Button Name="MyConfirmButton"
        Content="Confirm"
        Grid.Column="1"
        Style="{StaticResource ButtonStyle}"
        i:Interaction.Triggers="{StaticResource PerformConfirm}">
</Button>
</code>```

Your Resource XAML :-

```<code><UserControl.Resources>
   <i:EventTrigger x:Key="PerformConfirm" EventName="Click">
      <cmd:EventToCommand Command="{Binding Path=PerformConfirm}" />
   </i:EventTrigger>
</UserControl.Resources>
</code>```

Hope this helps

ContentLicense: CC BY-SA 2.5

Body:
I am using Mvvm-Light Commands to route events from my Views to my ViewModels. Works great.

But I think I can be more elegant. This is actually probably just a standard XAML question:

I want to change this (10 buttons all with Click="keypadButton_Click" for their event handler):

<Button  Name="button1" Content="1" Grid.Row="0" Grid.Column="0" Click="keypadButton_Click" />
<Button  Name="button2" Content="2" Grid.Row="0" Grid.Column="1" Click="keypadButton_Click"/>
<Button  Name="button3" Content="3" Grid.Row="0" Grid.Column="2" Click="keypadButton_Click"/>
<Button  Name="button4" Content="4" Grid.Row="1" Grid.Column="0" Click="keypadButton_Click"/>
<Button  Name="button5" Content="5" Grid.Row="1" Grid.Column="1" Click="keypadButton_Click"/>
<Button  Name="button6" Content="6" Grid.Row="1" Grid.Column="2" Click="keypadButton_Click"/>
<Button  Name="button7" Content="7" Grid.Row="2" Grid.Column="0" Click="keypadButton_Click"/>
<Button  Name="button8" Content="8" Grid.Row="2" Grid.Column="1" Click="keypadButton_Click"/>
<Button  Name="button9" Content="9" Grid.Row="2" Grid.Column="2" Click="keypadButton_Click"/>
<Button  Name="button0" Content="0" Grid.Row="3" Grid.Column="1" Click="keypadButton_Click"/>

To 10 of these:

<Button  x:Name="button1" Content="1" Grid.Row="0" Grid.Column="0">

            <Command:EventToCommand
               Command="{Binding KeyPadButtonCommand}"
               CommandParameter="{Binding ElementName=button1, Path=Content }"/>

</Button>

But I don't want that much XAML. I would think there would be a way to "macroize" the Trigger so it would look something like this:

<Button  Name="button1" Content="1" Grid.Row="0" Grid.Column="0"
         Click="{Binding _SendTheEventHere_}" />

Where "{Binding _SendTheEventHere_}" should be replaced with some magic incantation that I am clueless about, but I know some wizard here on stackoverflow knows :-).

Make sense?

Body:
I have just run a test using the following XAML and it seems to work successfully :-

Your Button XAML :-

<Button Name="MyConfirmButton"
        Content="Confirm"
        Grid.Column="1"
        Style="{StaticResource ButtonStyle}"
        i:Interaction.Triggers="{StaticResource PerformConfirm}">
</Button>

Your Resource XAML :-

<UserControl.Resources>
   <i:EventTrigger x:Key="PerformConfirm" EventName="Click">
      <cmd:EventToCommand Command="{Binding Path=PerformConfirm}" />
   </i:EventTrigger>
</UserControl.Resources>

Hope this helps


问:
Dynamically Linking GLEW with CMake
I've looked over Stack Overflow and Google to try to figure this out, but everything I've seen regarding a dynamic linking either doesn't work or they end up static linking.

```<code>E:/CLion/GLEW-Test/main.cpp:8: undefined reference to `_imp__glewInit@0'
E:/CLion/GLEW-Test/main.cpp:12: undefined reference to `_imp__glewGetErrorString@4'
E:/CLion/GLEW-Test/main.cpp:14: undefined reference to `_imp__glewGetString@4'
</code>```

I am trying to dynamically link GLEW using CLion. The problem is, I've grown up with Visual Studio so I've never really had to think much about it. I'm trying to teach myself CMake and OpenGL, so this would have been a perfect exercise.

I downloaded the source for GLEW and built it with CMake and MinGW. I placed the resulting glew32.dll in C:/Windows/System32/, and I placed the libglew32.a in C:/MinGW/lib, and I placed glew.h, glxew.h, and wglew.h into C:/MinGW/include/GL.

Currently, I also have the libraries glew32.dll, libglu32.a, and libopengl32.a in my build directory.

Here is my CMakeLists.txt:

```<code>cmake_minimum_required(VERSION 3.8)
project(GLEW_Test)

set(CMAKE_CXX_STANDARD 11)
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra")
set( CMAKE_VERBOSE_MAKEFILE on )

set(SOURCE_FILES main.cpp)
add_executable(GLEW_Test ${SOURCE_FILES})
target_link_libraries(GLEW_Test glew32 glu32 opengl32)
</code>```

and this is my main.cpp:

```<code>#include <iostream>
#include <GL/glew.h>

int main()
{
    std::cout << "Hello, World!" << std::endl;

    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
        /* Problem: glewInit failed, something is seriously wrong. */
        fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
    }
    fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));

    return 0;
}
</code>```

Now, if I #define GLEW_STATIC before I #include <GL/glew.h>, the program compiles and outputs the expected output (An error for having no GLContext).    However, to my knowledge, that is static linking, and I want to dynamically link GLEW.  This is what I see when I compile without #define GLEW_STATIC:

```<code>"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" --build E:\CLion\GLEW-Test\cmake-build-debug --target GLEW_Test -- -j 2
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -HE:\CLion\GLEW-Test -BE:\CLion\GLEW-Test\cmake-build-debug --check-build-system CMakeFiles\Makefile.cmake 0
C:/MinGW/bin/mingw32-make.exe -f CMakeFiles\Makefile2 GLEW_Test
mingw32-make.exe[1]: Entering directory 'E:/CLion/GLEW-Test/cmake-build-debug'
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -HE:\CLion\GLEW-Test -BE:\CLion\GLEW-Test\cmake-build-debug --check-build-system CMakeFiles\Makefile.cmake 0
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -E cmake_progress_start E:\CLion\GLEW-Test\cmake-build-debug\CMakeFiles 2
C:/MinGW/bin/mingw32-make.exe -f CMakeFiles\Makefile2 CMakeFiles/GLEW_Test.dir/all
mingw32-make.exe[2]: Entering directory 'E:/CLion/GLEW-Test/cmake-build-debug'
C:/MinGW/bin/mingw32-make.exe -f CMakeFiles\GLEW_Test.dir\build.make CMakeFiles/GLEW_Test.dir/depend
mingw32-make.exe[3]: Entering directory 'E:/CLion/GLEW-Test/cmake-build-debug'
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -E cmake_depends "MinGW Makefiles" E:\CLion\GLEW-Test E:\CLion\GLEW-Test E:\CLion\GLEW-Test\cmake-build-debug E:\CLion\GLEW-Test\cmake-build-debug E:\CLion\GLEW-Test\cmake-build-debug\CMakeFiles\GLEW_Test.dir\DependInfo.cmake --color=
mingw32-make.exe[3]: Leaving directory 'E:/CLion/GLEW-Test/cmake-build-debug'
C:/MinGW/bin/mingw32-make.exe -f CMakeFiles\GLEW_Test.dir\build.make CMakeFiles/GLEW_Test.dir/build
mingw32-make.exe[3]: Entering directory 'E:/CLion/GLEW-Test/cmake-build-debug'
[ 50%] Linking CXX executable GLEW_Test.exe
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -E cmake_link_script CMakeFiles\GLEW_Test.dir\link.txt --verbose=1
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -E remove -f CMakeFiles\GLEW_Test.dir/objects.a
C:\MinGW\bin\ar.exe cr CMakeFiles\GLEW_Test.dir/objects.a @CMakeFiles\GLEW_Test.dir\objects1.rsp
C:\MinGW\bin\g++.exe  -Wall -Wextra -g   -Wl,--whole-archive CMakeFiles\GLEW_Test.dir/objects.a -Wl,--no-whole-archive  -o GLEW_Test.exe -Wl,--out-implib,libGLEW_Test.dll.a -Wl,--major-image-version,0,--minor-image-version,0 @CMakeFiles\GLEW_Test.dir\linklibs.rsp
CMakeFiles\GLEW_Test.dir/objects.a(main.cpp.obj): In function `main':
E:/CLion/GLEW-Test/main.cpp:8: undefined reference to `_imp__glewInit@0'
E:/CLion/GLEW-Test/main.cpp:12: undefined reference to `_imp__glewGetErrorString@4'
E:/CLion/GLEW-Test/main.cpp:14: undefined reference to `_imp__glewGetString@4'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[3]: *** [GLEW_Test.exe] Error 1
CMakeFiles\GLEW_Test.dir\build.make:98: recipe for target 'GLEW_Test.exe' failed
mingw32-make.exe[2]: *** [CMakeFiles/GLEW_Test.dir/all] Error 2
mingw32-make.exe[3]: Leaving directory 'E:/CLion/GLEW-Test/cmake-build-debug'
mingw32-make.exe[1]: *** [CMakeFiles/GLEW_Test.dir/rule] Error 2
CMakeFiles\Makefile2:69: recipe for target 'CMakeFiles/GLEW_Test.dir/all' failed
mingw32-make.exe[2]: Leaving directory 'E:/CLion/GLEW-Test/cmake-build-debug'
CMakeFiles\Makefile2:81: recipe for target 'CMakeFiles/GLEW_Test.dir/rule' failed
mingw32-make.exe[1]: Leaving directory 'E:/CLion/GLEW-Test/cmake-build-debug'
Makefile:120: recipe for target 'GLEW_Test' failed
mingw32-make.exe: *** [GLEW_Test] Error 2
</code>```

What am I doing wrong? I followed the guide at glew's sourceforge, and placed the .dll in my System32 folder. Since I built with CMake and MinGW, I have .a files instead of .lib files, and I stuck those in my MinGW/lib directory.
The only thing I didn't do (because I wasn't sure), was do nothing with my libglew32.dll.a
Is this the culprit? I'm not sure what to do with it, and googling for information on a .dll.a file turned up nothing.

答:
Alright, so after googling around a bit and trying to understand what a .dll.a file is, I've got it figured out!

This is what I did to dynamically link glew using CMake:

I deleted glew32.a from my C:\MinGW\lib directory, and replaced it with glew32.dll.a

I placed glew32.dll into my build folder. However, you can also have it in your SysWOW64 folder and it should work.

And that's all! My CMakeLists.txt is still the same.

Title: Dynamically Linking GLEW with CMake

Body:
I've looked over Stack Overflow and Google to try to figure this out, but everything I've seen regarding a dynamic linking either doesn't work or they end up static linking.

E:/CLion/GLEW-Test/main.cpp:8: undefined reference to `_imp__glewInit@0'
E:/CLion/GLEW-Test/main.cpp:12: undefined reference to `_imp__glewGetErrorString@4'
E:/CLion/GLEW-Test/main.cpp:14: undefined reference to `_imp__glewGetString@4'

I am trying to dynamically link GLEW using CLion. The problem is, I've grown up with Visual Studio so I've never really had to think much about it. I'm trying to teach myself CMake and OpenGL, so this would have been a perfect exercise.

I downloaded the source for GLEW and built it with CMake and MinGW. I placed the resulting glew32.dll in C:/Windows/System32/, and I placed the libglew32.a in C:/MinGW/lib, and I placed glew.h, glxew.h, and wglew.h into C:/MinGW/include/GL.

Currently, I also have the libraries glew32.dll, libglu32.a, and libopengl32.a in my build directory.

Here is my CMakeLists.txt:

cmake_minimum_required(VERSION 3.8)
project(GLEW_Test)

set(CMAKE_CXX_STANDARD 11)
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra")
set( CMAKE_VERBOSE_MAKEFILE on )

set(SOURCE_FILES main.cpp)
add_executable(GLEW_Test ${SOURCE_FILES})
target_link_libraries(GLEW_Test glew32 glu32 opengl32)

and this is my main.cpp:

#include <iostream>
#include <GL/glew.h>

int main()
{
    std::cout << "Hello, World!" << std::endl;

    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
        /* Problem: glewInit failed, something is seriously wrong. */
        fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
    }
    fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));

    return 0;
}

Now, if I #define GLEW_STATIC before I #include <GL/glew.h>, the program compiles and outputs the expected output (An error for having no GLContext).    However, to my knowledge, that is static linking, and I want to dynamically link GLEW.  This is what I see when I compile without #define GLEW_STATIC:

"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" --build E:\CLion\GLEW-Test\cmake-build-debug --target GLEW_Test -- -j 2
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -HE:\CLion\GLEW-Test -BE:\CLion\GLEW-Test\cmake-build-debug --check-build-system CMakeFiles\Makefile.cmake 0
C:/MinGW/bin/mingw32-make.exe -f CMakeFiles\Makefile2 GLEW_Test
mingw32-make.exe[1]: Entering directory 'E:/CLion/GLEW-Test/cmake-build-debug'
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -HE:\CLion\GLEW-Test -BE:\CLion\GLEW-Test\cmake-build-debug --check-build-system CMakeFiles\Makefile.cmake 0
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -E cmake_progress_start E:\CLion\GLEW-Test\cmake-build-debug\CMakeFiles 2
C:/MinGW/bin/mingw32-make.exe -f CMakeFiles\Makefile2 CMakeFiles/GLEW_Test.dir/all
mingw32-make.exe[2]: Entering directory 'E:/CLion/GLEW-Test/cmake-build-debug'
C:/MinGW/bin/mingw32-make.exe -f CMakeFiles\GLEW_Test.dir\build.make CMakeFiles/GLEW_Test.dir/depend
mingw32-make.exe[3]: Entering directory 'E:/CLion/GLEW-Test/cmake-build-debug'
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -E cmake_depends "MinGW Makefiles" E:\CLion\GLEW-Test E:\CLion\GLEW-Test E:\CLion\GLEW-Test\cmake-build-debug E:\CLion\GLEW-Test\cmake-build-debug E:\CLion\GLEW-Test\cmake-build-debug\CMakeFiles\GLEW_Test.dir\DependInfo.cmake --color=
mingw32-make.exe[3]: Leaving directory 'E:/CLion/GLEW-Test/cmake-build-debug'
C:/MinGW/bin/mingw32-make.exe -f CMakeFiles\GLEW_Test.dir\build.make CMakeFiles/GLEW_Test.dir/build
mingw32-make.exe[3]: Entering directory 'E:/CLion/GLEW-Test/cmake-build-debug'
[ 50%] Linking CXX executable GLEW_Test.exe
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -E cmake_link_script CMakeFiles\GLEW_Test.dir\link.txt --verbose=1
"C:\Program Files\JetBrains\CLion 2017.2.2\bin\cmake\bin\cmake.exe" -E remove -f CMakeFiles\GLEW_Test.dir/objects.a
C:\MinGW\bin\ar.exe cr CMakeFiles\GLEW_Test.dir/objects.a @CMakeFiles\GLEW_Test.dir\objects1.rsp
C:\MinGW\bin\g++.exe  -Wall -Wextra -g   -Wl,--whole-archive CMakeFiles\GLEW_Test.dir/objects.a -Wl,--no-whole-archive  -o GLEW_Test.exe -Wl,--out-implib,libGLEW_Test.dll.a -Wl,--major-image-version,0,--minor-image-version,0 @CMakeFiles\GLEW_Test.dir\linklibs.rsp
CMakeFiles\GLEW_Test.dir/objects.a(main.cpp.obj): In function `main':
E:/CLion/GLEW-Test/main.cpp:8: undefined reference to `_imp__glewInit@0'
E:/CLion/GLEW-Test/main.cpp:12: undefined reference to `_imp__glewGetErrorString@4'
E:/CLion/GLEW-Test/main.cpp:14: undefined reference to `_imp__glewGetString@4'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[3]: *** [GLEW_Test.exe] Error 1
CMakeFiles\GLEW_Test.dir\build.make:98: recipe for target 'GLEW_Test.exe' failed
mingw32-make.exe[2]: *** [CMakeFiles/GLEW_Test.dir/all] Error 2
mingw32-make.exe[3]: Leaving directory 'E:/CLion/GLEW-Test/cmake-build-debug'
mingw32-make.exe[1]: *** [CMakeFiles/GLEW_Test.dir/rule] Error 2
CMakeFiles\Makefile2:69: recipe for target 'CMakeFiles/GLEW_Test.dir/all' failed
mingw32-make.exe[2]: Leaving directory 'E:/CLion/GLEW-Test/cmake-build-debug'
CMakeFiles\Makefile2:81: recipe for target 'CMakeFiles/GLEW_Test.dir/rule' failed
mingw32-make.exe[1]: Leaving directory 'E:/CLion/GLEW-Test/cmake-build-debug'
Makefile:120: recipe for target 'GLEW_Test' failed
mingw32-make.exe: *** [GLEW_Test] Error 2

What am I doing wrong? I followed the guide at glew's sourceforge, and placed the .dll in my System32 folder. Since I built with CMake and MinGW, I have .a files instead of .lib files, and I stuck those in my MinGW/lib directory.
The only thing I didn't do (because I wasn't sure), was do nothing with my libglew32.dll.a
Is this the culprit? I'm not sure what to do with it, and googling for information on a .dll.a file turned up nothing.


问:
Realm, complex linked query
in the official docs, https://realm.io/docs/java/latest/#link-queries - there's an example how to select owners of "Brown Fluffy" dogs.

My questions is, how do I select only those not having Brown Fluffy (and, obviously, those having no dogs at all)

I do not see how can one achieve this result by, say, using .not().beginGroup().equalTo(...).equalTo(...).endGroup() (that someone with previous SQL experience would try)

Thanks a lot in advance!

答:
Have you tried

```<code>.not().equalTo(...).findAll().where().not().equalTo(...).findAll();
</code>```

?

Chaining link queries is a bit tricky, but if I understand correctly, that is what you should try.

Title: Realm, complex linked query

Body:
Have you tried

.not().equalTo(...).findAll().where().not().equalTo(...).findAll();

?

Chaining link queries is a bit tricky, but if I understand correctly, that is what you should try.


问:
Python recursion facts
I need help knowing which of the following are TRUE in a recursive function in python

A recursive solution to a problem is always preferable

A recursive function calls itself

Each recursive call diminishes the size of the problem

A recursive function can have one or more base cases

A recursive function can have one or more recursive steps.

Could I please get an answer as to which of these are true. MORE THAN ONE can be correct.

This was one of my past papers in my subject but I couldn't get the right answer for 5 and I was wondering if that was true or false. This isn't for homework and I'm not asking to just get the answer but for a further understanding of recursive functions in python.

Thank you!

答:
1) A recursive solution has a few benefits. Generally it is more readable, and smaller in terms of lines of code. When it doesn't work, it's almost always harder to debug. It's usually preferable when it runs faster than a non-recursive solution (see merge sort).

2) By definition.

3) True -- the point of recursion is to reduce every problem to a base case which has a trivial solution.

4) Also true. See the implementation below:

```<code>def pow3(input):
   if input//3 is not input/3:
       return False
   elif input is 1:
       return True
   else:
       return pow3(input/3)
</code>```

5) Based on the wording of the question, "one or more recursive steps", certainly true. Every recursive function must have a recursive step, and therefore every recursive function must have one or more recursive steps.

Feel free to ask any other questions below.

Title: Python recursion facts

Body:
1) A recursive solution has a few benefits. Generally it is more readable, and smaller in terms of lines of code. When it doesn't work, it's almost always harder to debug. It's usually preferable when it runs faster than a non-recursive solution (see merge sort).

2) By definition.

3) True -- the point of recursion is to reduce every problem to a base case which has a trivial solution.

4) Also true. See the implementation below:

def pow3(input):
   if input//3 is not input/3:
       return False
   elif input is 1:
       return True
   else:
       return pow3(input/3)

5) Based on the wording of the question, "one or more recursive steps", certainly true. Every recursive function must have a recursive step, and therefore every recursive function must have one or more recursive steps.

Feel free to ask any other questions below.


问:
C array sorting ignoring special characters
```<code>char temp[size];
int b, z;
for (b = 0; b < size; b++) {
    for (z = 0; z < size; z++) {
        if (strcmp(processNames[b], processNames[z]) < 0) {
            strcpy(temp, processNames[b]);
            strcpy(processNames[b], processNames[z]);
            strcpy(processNames[z], temp);
        }
    }
}
</code>```

I'm sorting a list of char ** processNames;

I want it to sort like this:

```<code>abc
bee
george
(sally)
saw
thomas
zebra
</code>```

However, it is sorting it like this:

```<code>(sally)
abc
bee
george
saw
thomas
zebra
</code>```

Thanks, I'm not sure how to negate the special characters and only sort on alphabet. Thanks!

答:
“Sorting” means “putting things in order.” What order? The order is defined by some thing that tells us which of two items goes first.

In your code, you are using strcmp to decide which item goes first. That is the thing that decides the order. Since strcmp is giving an order you do not want, you need another function. In this case, you have to write your own function.

Your function should take two strings (via pointers to char), examine the strings, and return a value to indicate whether the first string should be before or after the second string (or whether they are equal).

Since this is likely a class assignment, I will leave it to you to ponder the necessary comparison function.

Alternative

There is an alternative method which is likely to be used in professionally deployed code, in suitable situations. I recommend the above because it is suitable for a class assignment—it addresses the key principle this assignment seems to target.

The alternative is to preprocess all the list items before doing the sort. Since you want to sort on the non-special characters of the names, you would augment the list by creating copies of the names with the special characters removed. These new versions would be your “sort keys”—they would be the values you use to decide order instead of the original names. You could compare them with strcmp.

This method requires allocating new memory for the new versions of the names, managing both the keys and the names while you sort them, and releasing the memory after the sort. It requires some overhead before you start the sort. However, if there are a very large number of things to sort with a considerable number of special characters, then doing the extra work up front can result in better performance overall.

(Again, I mention this only for completeness. It is likely not useful in a class assignment of this sort, just something computer science students should learn over time.)

Bonus Notes

You say you are sorting an array of char **ProcessNames. In this case, it is probably not necessary to move the strings themselves with strcpy. Instead, you can simply move the pointers to the strings. E.g., if you want to swap ProcessNames[4] and ProcessNames[7], just make a copy of the pointer that is ProcessNames[4], set ProcessNames[4] to be the pointer that is ProcessNames[7], and set ProcessNames[7] to be the temporary copy you made. This is generally faster than moving strings.

As others note, starting your z loop with z = 0 is probably not a good idea. You likely want z = b+1.

Your code uses size for the size of the string buffer (char temp[size]) and for the size of the ProcessNames array (for (b = 0; b < size; b++)). It is unlikely the number of strings to be sorted is the same as the maximum length of the strings. You should be sure to use the correct size in each instance.

Body:
char temp[size];
int b, z;
for (b = 0; b < size; b++) {
    for (z = 0; z < size; z++) {
        if (strcmp(processNames[b], processNames[z]) < 0) {
            strcpy(temp, processNames[b]);
            strcpy(processNames[b], processNames[z]);
            strcpy(processNames[z], temp);
        }
    }
}

I'm sorting a list of char ** processNames;

I want it to sort like this:

abc
bee
george
(sally)
saw
thomas
zebra

However, it is sorting it like this:

(sally)
abc
bee
george
saw
thomas
zebra

Thanks, I'm not sure how to negate the special characters and only sort on alphabet. Thanks!


问:
Regex delete duplicate urls
I have a list with several urls like

```<code>google.com
google.com/1
google.com/2
google.com/3
google.com/4
google.com/5
google.com/6
yahoo.com
yahoo.com/1
yahoo.com/2
yahoo.com/3
yahoo.com/4
yahoo.com/5
yahoo.com/6
</code>```

How can I remove the first the 3 entries keeping google.com/3 to 6 and same goes for yahoo?

答:
I'm not sure Regex are the best approach to this. But here's it anyway:

```<code>s/(google.com[\s/\d]*){3}//
s/(yahoo.com[\s/\d]*){3}//
</code>```

Regexes are enclosed in slashes and the preceeding s is substitution in vi notation

Title: Regex delete duplicate urls

Body:
I have a list with several urls like

google.com
google.com/1
google.com/2
google.com/3
google.com/4
google.com/5
google.com/6
yahoo.com
yahoo.com/1
yahoo.com/2
yahoo.com/3
yahoo.com/4
yahoo.com/5
yahoo.com/6

How can I remove the first the 3 entries keeping google.com/3 to 6 and same goes for yahoo?

Body:
I'm not sure Regex are the best approach to this. But here's it anyway:

s/(google.com[\s/\d]*){3}//
s/(yahoo.com[\s/\d]*){3}//

Regexes are enclosed in slashes and the preceeding s is substitution in vi notation


问:
Downloading a single directory from Git using Subversion
I am trying to download a folder from a Github Git repo using SVN and the instructions found here.

However, when I type:

```<code>svn checkout https://github.com/johnmyleswhite/ML_for_Hackers/tree/master/08-PCA/data .
</code>```

I get the error message:

svn: E170000: URL
  'https://github.com/johnmyleswhite/ML_for_Hackers/tree/master/08-PCA/data'
  doesn't exist

Any ideas what is going wrong? I am using Slik SVN on 64-bit Windows.

答: I got this error when my URL was pointing to /tree but not the /branches.</p>

Body:
I am trying to download a folder from a Github Git repo using SVN and the instructions found here.

However, when I type:

svn checkout https://github.com/johnmyleswhite/ML_for_Hackers/tree/master/08-PCA/data .

I get the error message:

svn: E170000: URL
  'https://github.com/johnmyleswhite/ML_for_Hackers/tree/master/08-PCA/data'
  doesn't exist

Any ideas what is going wrong? I am using Slik SVN on 64-bit Windows.


问:
VSTS - Can I get different features to show different bugs?
Afternoon,

I was looking for some help in relation to VSTS.

Is there any way to have a dashboard widget that shows bugs but only shows them for certain features. (Please see picture 1]

We are looking to see.

FRD001 bugs - New and closed
FRD002 bugs - New and closed
etc etc

image here

答:
Since get bugs based on different feature is actually query by Tree of work items, while charting in dashboard is not support the tree queries.

But there are two work around for your situation:

Work around 1: Add a query results widget in your dashboard

If it’s also ok for you to show the bugs based on different features as below list, you can add a query results widget in your dashboard. Detail steps as below:

Add a new query as below to list bugs based on different features.

Drag the query you added in step1 under the shared queries (As below example drag the New Query 1 under Current Sprint).

In your dash board, add Query Results widget and select the query you added for the widget configuration.

Now bugs will be showed based on different features.

Work around 2: show bugs for different features separately

If you only want to show the bugs by chart, you should add queries of bugs for different features separately, and then add charts of the bugs in different features to dashboard separately.


问:
Can angular4 route to a file with .html extsion?
such as :

```<code>{path: 'overview.html', component: OverviewComponent},
</code>```

Is it valid? Because I want to route to a local html file.

答: Yes it does, because overview.html is the path name you chose and the dot is a valid character in path names. I tried it, and tried overview$html and overview.html.... (yes, with four dots) and they all work, blindly. That said, you shouldn't not go for such naming! The actual html template file is loaded when the path (in your case, overview.html) resolves to a proper component (OverviewComponent) which has a selector that points to the proper html file. This is probably what you intended in the first place. So, you could (should) swap overview.html for just overview or even ov and it should work.

Body:
such as :

{path: 'overview.html', component: OverviewComponent},

Is it valid? Because I want to route to a local html file.


问:
mod_rewrite mod_pagespeed RewriteCond
I have the following in my .htaccess file:

```<code># Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php/$0 [PT]
</code>```

The server admin has installed Google mod_pagespeed and of course, because the folder doesn't exist, it logs an error every time as it tries to access /mod_pagespeed_beacon (and no stats are logged).

What RewriteCond do I need to add (and where) so /mod_pagespeed_beacon will work?

答:
I have vBulletin 4 Suite + vBSEO
Found that this line in .htaccess sorted out the problem

```<code># mod_pagespeed
RewriteCond %{REQUEST_URI} !(mod_pagespeed_statistics|mod_pagespeed_beacon) [NC]
</code>```

Place it before this line in

```<code>RewriteRule ^(.+)$ vbseo.php [L,QSA]
</code>```

Title: mod_rewrite mod_pagespeed RewriteCond

Body:
I have the following in my .htaccess file:

# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php/$0 [PT]

The server admin has installed Google mod_pagespeed and of course, because the folder doesn't exist, it logs an error every time as it tries to access /mod_pagespeed_beacon (and no stats are logged).

What RewriteCond do I need to add (and where) so /mod_pagespeed_beacon will work?

Body:
I have vBulletin 4 Suite + vBSEO
Found that this line in .htaccess sorted out the problem

# mod_pagespeed
RewriteCond %{REQUEST_URI} !(mod_pagespeed_statistics|mod_pagespeed_beacon) [NC]

Place it before this line in

RewriteRule ^(.+)$ vbseo.php [L,QSA]


问:
PHP line break inside of cell remove qoute
This is my PHP

```<code>$val = "";
foreach($data as $v){
  $val .= '"' . $v . "\n" . '"';
}
</code>```

The result is

```<code>//this is inside of cell
sample
"sample
"sample
</code>```

This is correct but I cant figure out how to remove the double quote in "sample. Only the first value dont have a double quote the rest will have a double quote.

EDIT

This is the result of my code

This is what I want

答:
The answer to my question is

```<code>$val = "";
foreach($data as $v){
  $val .= $v . "\n";
}

 $val = '"'. $val .'"';
</code>```

I need to add the '"' outside of the loop.

Body:
This is my PHP

$val = "";
foreach($data as $v){
  $val .= '"' . $v . "\n" . '"';
}

The result is

//this is inside of cell
sample
"sample
"sample

This is correct but I cant figure out how to remove the double quote in "sample. Only the first value dont have a double quote the rest will have a double quote.

EDIT

This is the result of my code

This is what I want

Body:
The answer to my question is

$val = "";
foreach($data as $v){
  $val .= $v . "\n";
}

 $val = '"'. $val .'"';

I need to add the '"' outside of the loop.


问:
Best way to retrieve active calls without making request each second?
We need to create a monitor that will show any income calls in our extranet in live time.

We were able to show active calls by using /account/~/extension/~/active-calls, however, to achieve what we need we would need to make a request each second which I guess will be blocked by rate limits.

Is there a better solution for it?

Thanks

答:
Subscription (Push Notification) API resource empowers developers to enable the client application(s) to create a single subscription (to one or more extension's) and continually receive push notifications in real time for each subscribed extension.When using this approach for your application(s) to receive events on your RingCentral account, no polling is involved.

You can create a subscription using either of the below-mentioned transportType for receiving push notifications:

PubNub

WebHook

Notifications which the client wants to receive can be specified by the event filters which are set in the subscription request. The event filter is exposed as a URL, pointing to the required RingCentral API resource. Currently the following event types are available for notifications: extensions, messages and presence. They are described in detail below:

Notifications Event Types

You can take a look at the Subscription API below:

Subscription API

If you are interested in Subscribing to Push notifications via WebHook then we have an Easy-to-follow Quickstart guide here:

RingCentral Webhooks Quickstart Guide


问:
Parsing optional recursive parser runs in infinite recursion
I'm currently writing a parser for ECMAScript 5 (as a toy). The standard dictates how logical or expressions should be parsed:

```<code><LogicalORExpression> :
    <LogicalANDExpression>
    <LogicalORExpression> || <LogicalANDExpression>
</code>```

basicly this is equivalent to

<logicalOrExpression> = [<logicalOrExpression> ||] <LogicalAndExpression>

but how should I parse this without running into an infite loop? My current parser obviously does:

```<code>logicalOrExpression :: Parser LogicalOrExpression
logicalOrExpression = do
    orExpr <- optional $ do
        e <- logicalOrExpression
        _ <- symbol "||"
        return e
    andExpr <- logicalAndExpression
    case orExpr of
        Just e -> return $ LogicalOrExpression (e, andExpr)
        Nothing -> return $ AndExpression andExpr
</code>```

Thanks

答:
It's easiest to use megaparsec's built-in tools if you need to parse a grammar of operators with precedence and associativity.

```<code>expr = makeExprParser term table
    where
        term = literal <|> parenthesised expr
        table = [[InfixL (string "&&" $> And)], [InfixL (string "||" $> Or)]]
</code>```

For suitable definitions of literal and parenthesised, this'll parse a grammar of literal expressions composed with left-associative infix && and || operators, with && having greater precedence than ||. Megaparsec takes care of the tedious work of generating an LL(k) parser, and produces correct (left-associative, in this instance) parse trees.

Of course JavaScript's expression grammar is much larger than two operators. This example can be straightforwardly extended to include (eg) unary prefix operators like !, postfix function calls, etc. See the module's documentation.

Body:
I'm currently writing a parser for ECMAScript 5 (as a toy). The standard dictates how logical or expressions should be parsed:

<LogicalORExpression> :
    <LogicalANDExpression>
    <LogicalORExpression> || <LogicalANDExpression>

basicly this is equivalent to

<logicalOrExpression> = [<logicalOrExpression> ||] <LogicalAndExpression>

but how should I parse this without running into an infite loop? My current parser obviously does:

logicalOrExpression :: Parser LogicalOrExpression
logicalOrExpression = do
    orExpr <- optional $ do
        e <- logicalOrExpression
        _ <- symbol "||"
        return e
    andExpr <- logicalAndExpression
    case orExpr of
        Just e -> return $ LogicalOrExpression (e, andExpr)
        Nothing -> return $ AndExpression andExpr

Thanks

Body:
It's easiest to use megaparsec's built-in tools if you need to parse a grammar of operators with precedence and associativity.

expr = makeExprParser term table
    where
        term = literal <|> parenthesised expr
        table = [[InfixL (string "&&" $> And)], [InfixL (string "||" $> Or)]]

For suitable definitions of literal and parenthesised, this'll parse a grammar of literal expressions composed with left-associative infix && and || operators, with && having greater precedence than ||. Megaparsec takes care of the tedious work of generating an LL(k) parser, and produces correct (left-associative, in this instance) parse trees.

Of course JavaScript's expression grammar is much larger than two operators. This example can be straightforwardly extended to include (eg) unary prefix operators like !, postfix function calls, etc. See the module's documentation.


问:
Populate Interactive Report from another interactive Report
There is an interactive Report A with fields: Name, Position, Salary. I want another interactive report with information from A with fields Position and Salary. Can we do something like

```<code>select position,sum(salary) from A group by position;
</code>```

I am trying to achieve this without hitting the database twice for 2 interactive reports.

答:
By design the Interactive Reports are a direct query to table or view in the database so each Interactive Report will 'hit the database' so you can't avoid that.

Given that your query 'select position,sum(salary) from A group by position;' has a aggregate and grouping function I assume this is what you really want to avoid as being hard on the database, so what you can do is create a materialized view and that's what you query in your second Interactive Report.

Body:
There is an interactive Report A with fields: Name, Position, Salary. I want another interactive report with information from A with fields Position and Salary. Can we do something like

select position,sum(salary) from A group by position;

I am trying to achieve this without hitting the database twice for 2 interactive reports.