问:
lsb_release of the host OS in a Docker
I want to get the Operating System that I'm running on inside a Docker.

This is what my docker-compose looks like and I'm inheriting from the python:2.7 image

```<code> version: '2'
 services:
   robot-configuration-interface:
     build: '.'
     restart: always
     network_mode: 'host'
     ports:
       - 8000:80
     environment:
       - REDIS_HOST=localhost
       - DEBUG=true
     volumes:
       - ~/logs/fetchcore-server:/var/log/supervisor
       - /var/run/docker.sock:/var/run/docker.sock
       - /opt/ros/indigo:/opt/ros/indigo
       - /etc/environment:/etc/environment
       - /etc/NetworkManager/system-connections/:/etc/NetworkManager/system-connections/
       - /lib:/lib
       - /usr/lib/:/usr/lib
       - /usr/bin/:/usr/bin/
       - /var/run/:/var/run/
     privileged: true
     user: root
</code>```

The lsb_release -d command returns Debian GNU/Linux 8.7 (n/a) instead of
Ubuntu 14.04.5 LTS even though i'm mounting /usr/bin

答:
LSB is kind of deprecated/ignored on Debian-based distributions, and the file is not present in the Docker images of the most popular distros.</p>

<p>/etc/os-release is prefered now.  You can see that this file is present on the Docker images of a lot of distributions (even Alpine), which is not the case with /etc/lsb-release.  </p>

Title: lsb_release of the host OS in a Docker

Body:
I want to get the Operating System that I'm running on inside a Docker.

This is what my docker-compose looks like and I'm inheriting from the python:2.7 image

 version: '2'
 services:
   robot-configuration-interface:
     build: '.'
     restart: always
     network_mode: 'host'
     ports:
       - 8000:80
     environment:
       - REDIS_HOST=localhost
       - DEBUG=true
     volumes:
       - ~/logs/fetchcore-server:/var/log/supervisor
       - /var/run/docker.sock:/var/run/docker.sock
       - /opt/ros/indigo:/opt/ros/indigo
       - /etc/environment:/etc/environment
       - /etc/NetworkManager/system-connections/:/etc/NetworkManager/system-connections/
       - /lib:/lib
       - /usr/lib/:/usr/lib
       - /usr/bin/:/usr/bin/
       - /var/run/:/var/run/
     privileged: true
     user: root

The lsb_release -d command returns Debian GNU/Linux 8.7 (n/a) instead of
Ubuntu 14.04.5 LTS even though i'm mounting /usr/bin

Body:
LSB is kind of deprecated/ignored on Debian-based distributions, and the file is not present in the Docker images of the most popular distros.

/etc/os-release is prefered now.  You can see that this file is present on the Docker images of a lot of distributions (even Alpine), which is not the case with /etc/lsb-release.


来源: stackexchange

问:
Tagging and Training NER dataset
I have a data set and I want to tag it for Named Entity Recognition. My dataset is in Persian.
I want to know how should I tag expressions like :

*** آقای مهدی کاظمی  = Mr Mehdi Kazemi / Mr will Smith. >>> (names with titles) should I tag all as a person or just the first name and last name should be tagged? (I mean should i also tag "Mr")

Mr  >>  b_per     ||     Mr >> O

Mehdi  >>   i_per || Mehdi >> b_per

Kazemi  >> i_per || Kazemi >> i_per

*** بیمارستان نور = Noor hospital >>> Should I tag the name only or the name and hospital both as Named Entity?

*** Eiffel tower / The Ministry of Defense (I mean the us DOD for example) >>> in Persian it is called :
وزارت دفاع    (vezarate defa)
should I only tag Defense ? or all together?

There are many more examples for schools, movies, cities, countries and.... since we use the entity class before the named entity.

I would appreciate if you can help me with tagging this dataset.

答:
I believe you are heading to Stanford NLP and BIO format. But in case you'd also consider other options, you may have a look a structured entities such as: http://www.afcp-parole.org/etape/docs/etape-06022012-quaero-en.pdf.

Those allow to describe entities as trees, providing a finer analysis for information extraction. More tedious to annotate but probably relevant if you intend to use annotation for semantic purposes, not only indexing.

ContentLicense: CC BY-SA 3.0

Title: Tagging and Training NER dataset


问:
How send parameter to a url without using form in php?
dear all,
I need to send parameters to a URL without using form in php and get value from that page.We can easily send parameters using form like this:

```<code><html>
    <form action="http://..../abc.php" method="get">
    <input name="id" type="text" />
    <input name="name" type="text"/>
    <input  type="submit" value="press" />
    </form>
</html>
</code>```

But i already have value like this

```<code>     <?php
       $id="123";
       $name="blahblah";
      ?>
</code>```

Now i need to send values to http://..../abc.php without using form.when the 2 value send to abc.php link then it's show a value OK.Now i have to collect the "OK" msg from abc.php and print on my current page.
i need to auto execute the code.when user enter into the page those value automatically send to a the url.So i can't use form or href. because form and href need extra one click.

Is their any kind heart who can help me to solve this issue?

答:
You can do:</p>

```<code>$id="123";
$name="blahblah";
echo "<a href = 'http://foo.com/abc.php?id=$id&name=$name'> link </a>";
</code>```

ContentLicense: CC BY-SA 2.5

Body:
dear all,
I need to send parameters to a URL without using form in php and get value from that page.We can easily send parameters using form like this:

    <form action="http://..../abc.php" method="get">
    <input name="id" type="text" />
    <input name="name" type="text"/>
    <input  type="submit" value="press" />
    </form>

But i already have value like this

     <?php
       $id="123";
       $name="blahblah";
      ?>

Now i need to send values to http://..../abc.php without using form.when the 2 value send to abc.php link then it's show a value OK.Now i have to collect the "OK" msg from abc.php and print on my current page.
i need to auto execute the code.when user enter into the page those value automatically send to a the url.So i can't use form or href. because form and href need extra one click.

Is their any kind heart who can help me to solve this issue?

Body:
You can do:

$id="123";
$name="blahblah";
echo "<a href = 'http://foo.com/abc.php?id=$id&name=$name'> link </a>";


问:
I can't figure out this F# error message
The error messages generated by the F# compiler are sometimes confusing. For example:

```<code>open Deedle
let inds = [1;   2;  6;  8; 11; 12]
let vals = [10; 20; 30; 40; 50; 60]
let siv = Series(inds, vals)
let fbminmax b (s: Series<float, float>) =
    if b then (Seq.min s.Values) else (Seq.max s.Values)
let sgi =
    siv
    |> Series.groupInto (fun i _ -> i % 2 = 0) fbminmax
printfn "%A" <| sgi
// error FS0001: Type mismatch. Expecting a
//    'bool -> Series<int,int> -> 'a'
// but given a
//    'bool -> Series<int,int> -> float'
// The type 'float' does not match the type 'int'
</code>```

I understand there is an error (the code works fine with Series<int,int> replacing Series<float,float> in the definition of fbminmax). And I understand that a

'bool -> Series<int,int> -> 'a'

was expected. But I do not understand why the compiler says that it was given a

'bool -> Series<int,int> -> float'

when it was given fbminmax, which is a

'bool -> Series<float,float> -> float'

Moreover, if the compiler had indeed been given a

'bool -> Series<int,int> -> float'

as it claimed it did that should have been Ok with float playing the role of 'a.

Can someone provide some insight on what is going on?

答:
Just a guess but what does the compiler say when you experiment with making your ints floats?

from:

```<code>let inds = [1;   2;  6;  8; 11; 12]
let vals = [10; 20; 30; 40; 50; 60]
</code>```

to:

```<code>let inds = [1.0;   2.0;  6.0;  8.0; 11.0; 12.0]
let vals = [10.0; 20.0; 30.0; 40.0; 50.0; 60.0]
</code>```

Body:
The error messages generated by the F# compiler are sometimes confusing. For example:

open Deedle
let inds = [1;   2;  6;  8; 11; 12]
let vals = [10; 20; 30; 40; 50; 60]
let siv = Series(inds, vals)
let fbminmax b (s: Series<float, float>) =
    if b then (Seq.min s.Values) else (Seq.max s.Values)
let sgi =
    siv
    |> Series.groupInto (fun i _ -> i % 2 = 0) fbminmax
printfn "%A" <| sgi
// error FS0001: Type mismatch. Expecting a
//    'bool -> Series<int,int> -> 'a'
// but given a
//    'bool -> Series<int,int> -> float'
// The type 'float' does not match the type 'int'

I understand there is an error (the code works fine with Series<int,int> replacing Series<float,float> in the definition of fbminmax). And I understand that a

'bool -> Series<int,int> -> 'a'

was expected. But I do not understand why the compiler says that it was given a

'bool -> Series<int,int> -> float'

when it was given fbminmax, which is a

'bool -> Series<float,float> -> float'

Moreover, if the compiler had indeed been given a

'bool -> Series<int,int> -> float'

as it claimed it did that should have been Ok with float playing the role of 'a.

Can someone provide some insight on what is going on?

Body:
Just a guess but what does the compiler say when you experiment with making your ints floats?

from:

let inds = [1;   2;  6;  8; 11; 12]
let vals = [10; 20; 30; 40; 50; 60]

to:

let inds = [1.0;   2.0;  6.0;  8.0; 11.0; 12.0]
let vals = [10.0; 20.0; 30.0; 40.0; 50.0; 60.0]


问:
EXCEL VBA - Populating last Row with database new data only
So i have a database that i update it daily and i want to populate a sheet with only the tickets that had been breached.
What i want to do is to check on the database and copy only the new tickets to that sheet right after the last value.

My code now is copying all the tickets avaiable and i wanted to change that.

Can anyone help? Thank you

Here is my code so far

```<code>'SELECT DATABASE SHEET
Sheets("RAW ALL INC").Select

'FILTER ONLY THE BROKEN TICKETS
Selection.AutoFilter
ActiveSheet.Range("$A$1:$X$1312").AutoFilter Field:=4, Criteria1:="TRUE"

'COPY ALL TICKETS (THIS IS WHERE I WANT TO SELECT ONLY NEW TICKETS)
Range("A2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy

'PASTE THE TICKETS ON THE BROKEN TICKETS SHEET
Sheets("Broken Justification").Select
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
</code>```

答:
I think you can select just the visible cells after you apply your auto-filter, like this:

```<code>Sub filtersub()
    ActiveSheet.Range("$A$1:$X$1312").AutoFilter Field:=4, Criteria1:="TRUE"
    Range("$A$1:$X$131").Select
     'here's where you select filtered results...
    Selection.SpecialCells(xlCellTypeVisible).Select
    Selection.Copy
    Sheets("Broken Justification").Select
    Range("A2").Select
    ActiveSheet.Paste
End Sub
</code>```

So filter for the rows you want, then just copy them all and paste them into your destination.

Body:
So i have a database that i update it daily and i want to populate a sheet with only the tickets that had been breached.
What i want to do is to check on the database and copy only the new tickets to that sheet right after the last value.

My code now is copying all the tickets avaiable and i wanted to change that.

Can anyone help? Thank you

Here is my code so far

'SELECT DATABASE SHEET
Sheets("RAW ALL INC").Select

'FILTER ONLY THE BROKEN TICKETS
Selection.AutoFilter
ActiveSheet.Range("$A$1:$X$1312").AutoFilter Field:=4, Criteria1:="TRUE"

'COPY ALL TICKETS (THIS IS WHERE I WANT TO SELECT ONLY NEW TICKETS)
Range("A2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy

'PASTE THE TICKETS ON THE BROKEN TICKETS SHEET
Sheets("Broken Justification").Select
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False

Body:
I think you can select just the visible cells after you apply your auto-filter, like this:

Sub filtersub()
    ActiveSheet.Range("$A$1:$X$1312").AutoFilter Field:=4, Criteria1:="TRUE"
    Range("$A$1:$X$131").Select
     'here's where you select filtered results...
    Selection.SpecialCells(xlCellTypeVisible).Select
    Selection.Copy
    Sheets("Broken Justification").Select
    Range("A2").Select
    ActiveSheet.Paste
End Sub

So filter for the rows you want, then just copy them all and paste them into your destination.


问:
Why should hash functions use a prime number modulus?
A long time ago, I bought a data structures book off the bargain table for $1.25.  In it, the explanation for a hashing function said that it should ultimately mod by a prime number because of "the nature of math".

What do you expect from a $1.25 book?

Anyway, I've had years to think about the nature of math, and still can't figure it out.

Is the distribution of numbers truly more even when there are a prime number of buckets?

Or is this an old programmer's tale that everyone accepts because everybody else accepts it?

答:
Copying from my other answer https://stackoverflow.com/a/43126969/917428. See it for more details and examples.

I believe that it just has to do with the fact that computers work with in base 2. Just think at how the same thing works for base 10:

8 % 10 = 8

18 % 10 = 8

87865378 % 10 = 8

It doesn't matter what the number is: as long as it ends with 8, its modulo 10 will be 8.

Picking a big enough, non-power-of-two number will make sure the hash function really is a function of all the input bits, rather than a subset of them.

ContentLicense: CC BY-SA 4.0


问:
How can custom tableview cells be made in swift playground?
In swift playground (not in a project)
Could you please give me a hint about how to do this please?enter image description here

答:
You have to implement init(style:reuseIdentifier:) in your custom class to define subviews and constraints programmatically.

Thus:

```<code>import UIKit
import PlaygroundSupport

class CustomCell: UITableViewCell {
    weak var label1: UILabel!
    weak var label2: UILabel!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        let label1 = UILabel()
        label1.translatesAutoresizingMaskIntoConstraints = false
        label1.font = .preferredFont(forTextStyle: .title1)
        label1.backgroundColor = #colorLiteral(red: 0.572549045085907, green: 0.0, blue: 0.23137255012989, alpha: 1.0)
        label1.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        contentView.addSubview(label1)
        self.label1 = label1

        let label2 = UILabel()
        label2.translatesAutoresizingMaskIntoConstraints = false
        label2.font = .preferredFont(forTextStyle: .title1)
        label2.backgroundColor = #colorLiteral(red: 0.0901960805058479, green: 0.0, blue: 0.301960796117783, alpha: 1.0)
        label2.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        contentView.addSubview(label2)
        self.label2 = label2

        NSLayoutConstraint.activate([
            label1.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10),
            label2.leadingAnchor.constraint(equalTo: label1.trailingAnchor, constant: 10),
            contentView.trailingAnchor.constraint(equalTo: label2.trailingAnchor, constant: 10),
            label1.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10),
            label2.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10),
            contentView.bottomAnchor.constraint(equalTo: label1.bottomAnchor, constant: 10),
            contentView.bottomAnchor.constraint(equalTo: label2.bottomAnchor, constant: 10),
            label1.widthAnchor.constraint(equalTo: label2.widthAnchor)
            ])
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
</code>```

And then you'd have a standard UITableViewController which registers this class and uses it:

```<code>class ViewController: UITableViewController {
    var objects: [String] = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .spellOut
        return Array(0 ..< 1000).flatMap { formatter.string(from: NSNumber(value: $0)) }
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(CustomCell.self, forCellReuseIdentifier: "CustomCell")

        // set it up to let auto-layout resize the cell

        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 44
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return objects.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell

        cell.label1.text = objects[indexPath.row]
        cell.label2.text = "Row \(indexPath.row)"

        return cell
    }
}

PlaygroundPage.current.liveView = ViewController()
</code>```

Now that just creates a simple view like this:

That's not terribly pretty, but I set the background colors like I did, just so you can see that the frames are set appropriately. You'd obviously adjust your init(style:reuseIdentifier:) to create subviews more to your liking.

If you want the standard cell, then you don't need to have a custom cell subclass, but you can just use UITableViewCell:

```<code>import UIKit
import PlaygroundSupport

class ViewController: UITableViewController {
    var objects: [String] = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .spellOut
        return Array(0 ..< 1000).flatMap { formatter.string(from: NSNumber(value: $0)) }
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 44
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return objects.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

        cell.textLabel?.text = objects[indexPath.row]

        return cell
    }
}

PlaygroundPage.current.liveView = ViewController()
</code>```

On the iPad, that yields:

On Playground in Xcode, it yields:

Body:
You have to implement init(style:reuseIdentifier:) in your custom class to define subviews and constraints programmatically.

Thus:

import UIKit
import PlaygroundSupport

class CustomCell: UITableViewCell {
    weak var label1: UILabel!
    weak var label2: UILabel!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        let label1 = UILabel()
        label1.translatesAutoresizingMaskIntoConstraints = false
        label1.font = .preferredFont(forTextStyle: .title1)
        label1.backgroundColor = #colorLiteral(red: 0.572549045085907, green: 0.0, blue: 0.23137255012989, alpha: 1.0)
        label1.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        contentView.addSubview(label1)
        self.label1 = label1

        let label2 = UILabel()
        label2.translatesAutoresizingMaskIntoConstraints = false
        label2.font = .preferredFont(forTextStyle: .title1)
        label2.backgroundColor = #colorLiteral(red: 0.0901960805058479, green: 0.0, blue: 0.301960796117783, alpha: 1.0)
        label2.textColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        contentView.addSubview(label2)
        self.label2 = label2

        NSLayoutConstraint.activate([
            label1.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10),
            label2.leadingAnchor.constraint(equalTo: label1.trailingAnchor, constant: 10),
            contentView.trailingAnchor.constraint(equalTo: label2.trailingAnchor, constant: 10),
            label1.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10),
            label2.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10),
            contentView.bottomAnchor.constraint(equalTo: label1.bottomAnchor, constant: 10),
            contentView.bottomAnchor.constraint(equalTo: label2.bottomAnchor, constant: 10),
            label1.widthAnchor.constraint(equalTo: label2.widthAnchor)
            ])
    }

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

And then you'd have a standard UITableViewController which registers this class and uses it:

class ViewController: UITableViewController {
    var objects: [String] = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .spellOut
        return Array(0 ..< 1000).flatMap { formatter.string(from: NSNumber(value: $0)) }
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(CustomCell.self, forCellReuseIdentifier: "CustomCell")

        // set it up to let auto-layout resize the cell

        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 44
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return objects.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell

        cell.label1.text = objects[indexPath.row]
        cell.label2.text = "Row \(indexPath.row)"

        return cell
    }
}

PlaygroundPage.current.liveView = ViewController()

Now that just creates a simple view like this:

That's not terribly pretty, but I set the background colors like I did, just so you can see that the frames are set appropriately. You'd obviously adjust your init(style:reuseIdentifier:) to create subviews more to your liking.

If you want the standard cell, then you don't need to have a custom cell subclass, but you can just use UITableViewCell:

import UIKit
import PlaygroundSupport

class ViewController: UITableViewController {
    var objects: [String] = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .spellOut
        return Array(0 ..< 1000).flatMap { formatter.string(from: NSNumber(value: $0)) }
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 44
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return objects.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

        cell.textLabel?.text = objects[indexPath.row]

        return cell
    }
}

PlaygroundPage.current.liveView = ViewController()

On the iPad, that yields:

On Playground in Xcode, it yields:


问:
How to manage persistant caching in Office 365 for Windows and Mac OS?
I am new in Office 365 Add-ins. I want to know about caching. I am working on a Add-In using Office.js. I want to manage caching.

Scienario:

1- Add-In will get data from server once in a day. Data can be in MBs(i.e 5 MB).

2- It should store somewhere. So, user can use it even there is no internet connection.

Is there any internal caching mechanism provide by Office APIs?

I was also thinking to store in File. Is it possible to create and manage File using Office Add-ins in Windows and Mac?(I am just curious about File permission in Mac)

Please suggest

答: You need to read through the following resource: Persisting add-in state and settings. Depend on the Office application you are writing your add-in for you would need to use different objects or approaches (for example use HTML5 web storage, etc.)</p>


问:
Android can't include linux in C program with Android.mk
I'm trying to compile a C program for Android 6. This is my Android.mk:

```<code>APP_PLATFORM := android-23
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
# Enable PIE manually. Will get reset on $(CLEAR_VARS). This
# is what enabling PIE translates to behind the scenes.
LOCAL_CFLAGS += -fPIE -DHAVE_FANOTIFY=1 -DHAVE_SYS_FANOTIFY=0
LOCAL_LDFLAGS += -fPIE -pie
# give module name
LOCAL_MODULE := fsmon
# list your C files to compile
LOCAL_SRC_FILES := inotify.c fanotify.c util.c main.c
# this option will build executables instead of building library for android application.
include $(BUILD_EXECUTABLE)
</code>```

In the fanotify.c following include is written:

```<code>#include <linux/fanotify.h>
</code>```

When I try to use ndk-build, following error appears:

```<code>fsmon/jni/fanotify.c:51:10: fatal error: 'linux/fanotify.h' file not found
#include <linux/fanotify.h>
         ^
</code>```

The header fanotify.h is present in the ndk path /Android/Sdk/ndk-bundle/sysroot/usr/include/linux

Any suggestions?

EDIT: Same error if I try to include sys/fanotify.h

答:
You can specify additional include paths for your module using LOCAL_C_INCLUDES.

LOCAL_C_INCLUDES := /Android/Sdk/ndk-bundle/sysroot/usr/include/

https://developer.android.com/ndk/guides/android_mk.html#mdv

Body:
I'm trying to compile a C program for Android 6. This is my Android.mk:

APP_PLATFORM := android-23
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
# Enable PIE manually. Will get reset on $(CLEAR_VARS). This
# is what enabling PIE translates to behind the scenes.
LOCAL_CFLAGS += -fPIE -DHAVE_FANOTIFY=1 -DHAVE_SYS_FANOTIFY=0
LOCAL_LDFLAGS += -fPIE -pie
# give module name
LOCAL_MODULE := fsmon
# list your C files to compile
LOCAL_SRC_FILES := inotify.c fanotify.c util.c main.c
# this option will build executables instead of building library for android application.
include $(BUILD_EXECUTABLE)

In the fanotify.c following include is written:

#include <linux/fanotify.h>

When I try to use ndk-build, following error appears:

fsmon/jni/fanotify.c:51:10: fatal error: 'linux/fanotify.h' file not found
#include <linux/fanotify.h>
         ^

The header fanotify.h is present in the ndk path /Android/Sdk/ndk-bundle/sysroot/usr/include/linux

Any suggestions?

EDIT: Same error if I try to include sys/fanotify.h


问:
How to parse parts of a string and insert them into columns
I have a column in my database that stores data like so:

```<code> Description - (Width 1 Height 1)
</code>```

I need to parse this string and insert the Width and Height into 2 new columns.

I currently have this query:

```<code>SELECT CASE
        WHEN Description LIKE '%Width %' THEN SUBSTRING(Description, CHARINDEX('Width ', Description) + 6, 1)
      END AS Width,
      CASE
        WHEN Description LIKE '%Height %' THEN SUBSTRING(Description, CHARINDEX('Height ', Description) + 7, 1)
      END AS Height
FROM table
</code>```

It works great with this query, but if I have an entry like this, it only grabs the first digit:

```<code>Description - (Width 25 Height 10)
</code>```

I know this is because I am using '1' as the length of my SUBSTRING, but I am not sure how I can make this work properly.

答:
This query could run well for any length of height, width,  except for case ( Height xxxxx - Width xxxxx)</p>

```<code>DECLARE @Description AS TABLE (Description varchar(50))
INSERT INTO @Description
VALUES( 'Width 252 Height 1011'), ('Width 2 Height 22'),('Width 2144'), ('Height 2133')

SELECT CHARINDEX('Width', 'Width 25 Height 10')
;WITH temps AS
(
    SELECT
        CASE
            WHEN CHARINDEX('Height', d.Description) > 1 THEN CHARINDEX('Height', d.Description)
            ELSE 1
        END AS IndexPosition,
        d.Description
    FROM @Description d
)
SELECT
t.Description,
CASE
    WHEN t.IndexPosition = 1 AND t.Description LIKE '%Width%' THEN RTRIM(LTRIM(REPLACE(t.Description,'Width','' )))
    WHEN t.IndexPosition = 1 AND t.Description LIKE '%Height%' THEN NULL
    ELSE RTRIM(LTRIM(REPLACE(SUBSTRING(t.Description, 0, t.IndexPosition -1),'Width','' )))
END AS Width,
CASE
    WHEN t.IndexPosition = 1 AND t.Description LIKE '%Height%' THEN RTRIM(LTRIM(REPLACE(t.Description,'Height','' )))
    WHEN t.IndexPosition = 1 AND t.Description LIKE '%Width%' THEN NULL
    ELSE RTRIM(LTRIM(REPLACE(SUBSTRING(t.Description, t.IndexPosition, LEN(t.Description)),'Height','' )))
END AS Height
FROM temps t
</code>```

Body:
I have a column in my database that stores data like so:

 Description - (Width 1 Height 1)

I need to parse this string and insert the Width and Height into 2 new columns.

I currently have this query:

SELECT CASE
        WHEN Description LIKE '%Width %' THEN SUBSTRING(Description, CHARINDEX('Width ', Description) + 6, 1)
      END AS Width,
      CASE
        WHEN Description LIKE '%Height %' THEN SUBSTRING(Description, CHARINDEX('Height ', Description) + 7, 1)
      END AS Height
FROM table

It works great with this query, but if I have an entry like this, it only grabs the first digit:

Description - (Width 25 Height 10)

I know this is because I am using '1' as the length of my SUBSTRING, but I am not sure how I can make this work properly.

Body:
This query could run well for any length of height, width,  except for case ( Height xxxxx - Width xxxxx)

DECLARE @Description AS TABLE (Description varchar(50))
INSERT INTO @Description
VALUES( 'Width 252 Height 1011'), ('Width 2 Height 22'),('Width 2144'), ('Height 2133')

SELECT CHARINDEX('Width', 'Width 25 Height 10')
;WITH temps AS
(
    SELECT
        CASE
            WHEN CHARINDEX('Height', d.Description) > 1 THEN CHARINDEX('Height', d.Description)
            ELSE 1
        END AS IndexPosition,
        d.Description
    FROM @Description d
)
SELECT
t.Description,
CASE
    WHEN t.IndexPosition = 1 AND t.Description LIKE '%Width%' THEN RTRIM(LTRIM(REPLACE(t.Description,'Width','' )))
    WHEN t.IndexPosition = 1 AND t.Description LIKE '%Height%' THEN NULL
    ELSE RTRIM(LTRIM(REPLACE(SUBSTRING(t.Description, 0, t.IndexPosition -1),'Width','' )))
END AS Width,
CASE
    WHEN t.IndexPosition = 1 AND t.Description LIKE '%Height%' THEN RTRIM(LTRIM(REPLACE(t.Description,'Height','' )))
    WHEN t.IndexPosition = 1 AND t.Description LIKE '%Width%' THEN NULL
    ELSE RTRIM(LTRIM(REPLACE(SUBSTRING(t.Description, t.IndexPosition, LEN(t.Description)),'Height','' )))
END AS Height
FROM temps t


问:
std::shared_ptr<Parent> to std::shared_ptr<Child>
I have an "interface" as .h file that has a virtual method like this:

```<code>class ISomeInterface {
    public:
        virtual std::shared_ptr<Parent> getX() = 0;
}
</code>```

now that parent is "abstract" and in the implementors of the interface I use an actual class. So I wanted to do this:

```<code>class Implementor : public ISomeInterface {
    public:
        std::shared_ptr<Child> getX() = { return this->x; }
}
</code>```

But then I get:

Could not convert ‘((Implementor*)this)->Implementor::parent’ from ‘std::shared_ptr’ to ‘std::shared_ptr’

So, basically the std::shared_ptr is a wrapper and the compiler does not know how to come from wrapper<apple> to wrapper<fruit>, even though apple extends fruit.

How can I circumvent that behaviour?

Edit: Looks like this is still not possible in c++, as covariant types are only working for pointers/references, not inside wrappers like std::shared_ptr... a shame :(

答:
You can't. Covariant return types only work for raw pointers and references because the compiler knows how they work. For this to work for arbitrary types the compiler would need to be able to be told "this is safe to use with covariant return types", like C# does with out T generic parameters, but there's no such feature in C++.

Unfortunately, you need to return std::shared_ptr<Parent> in Implementor.

Body:
I have an "interface" as .h file that has a virtual method like this:

class ISomeInterface {
    public:
        virtual std::shared_ptr<Parent> getX() = 0;
}

now that parent is "abstract" and in the implementors of the interface I use an actual class. So I wanted to do this:

class Implementor : public ISomeInterface {
    public:
        std::shared_ptr<Child> getX() = { return this->x; }
}

But then I get:

Could not convert ‘((Implementor*)this)->Implementor::parent’ from ‘std::shared_ptr’ to ‘std::shared_ptr’

So, basically the std::shared_ptr is a wrapper and the compiler does not know how to come from wrapper<apple> to wrapper<fruit>, even though apple extends fruit.

How can I circumvent that behaviour?

Edit: Looks like this is still not possible in c++, as covariant types are only working for pointers/references, not inside wrappers like std::shared_ptr... a shame :(


问:
Why C++ CLI has no default argument on managed types?
The following line has the error Default argument is not allowed.

```<code>public ref class SPlayerObj{
private:

    void k(int s = 0){ //ERROR
    }
}
</code>```

Why C++ has no default argument on managed types ?

I would like to know if there is a way to fix this.

答:
An alternative solution is to use the [OptionalAttribute] along side a Nullable<int> typed parameter.  If the parameter is not specified by the caller it will be a nullptr.

```<code>void k([OptionalAttribute]Nullable<int>^ s)
{
    if(s == nullptr)
    {
        // s was not provided
    }
    else if(s->HasValue)
    {
        // s was provided and has a value
        int theValue = s->Value;
    }
}
// call with no parameter
k();
// call with a parameter value
k(100);
</code>```

Body:
The following line has the error Default argument is not allowed.

public ref class SPlayerObj{
private:

    void k(int s = 0){ //ERROR
    }
}

Why C++ has no default argument on managed types ?

I would like to know if there is a way to fix this.

Body:
An alternative solution is to use the [OptionalAttribute] along side a Nullable<int> typed parameter.  If the parameter is not specified by the caller it will be a nullptr.

void k([OptionalAttribute]Nullable<int>^ s)
{
    if(s == nullptr)
    {
        // s was not provided
    }
    else if(s->HasValue)
    {
        // s was provided and has a value
        int theValue = s->Value;
    }
}
// call with no parameter
k();
// call with a parameter value
k(100);


问:
Logout user with alert message
I have a login component that controls the login page and alerts (success, error, information,...). I can display alerts with no problems when I am in the page, for instance, to inform the user invalid credentials or to inform that the page is being updated. Basically this messages are variables in the login component class binded to the frontend:

```<code>export class Login {
  error;
  info;
}
</code>```

Now when the user logouts I redirect to the login page:

```<code>this.router.navigate(['/login']);
</code>```

I want to show an alert to the user informing the logout process was successful (actually I will use this same logic to inform if the user session expires). I created two methods in login component class:

```<code>  logout() {
    this.authenticationService.logout()
        .subscribe(response => {
            this.logoutRedirect();
        },
        error => {
            this.logoutRedirect();
        });
  }

  logoutRedirect() {
      this.authenticationService.removeUser();
      this.info = 'Logout success';
      this.router.navigate(['/login']);
  }
</code>```

Everything works except the message. I believe it happens because when the user is redirected a new login class is used and this one does not have the info information.

How is the best approach for this problem: I will use it a lot in my application so I want to do it correctly.

答:
I solved this problem using a service. The service has a BehaviorSubject that is subscribed by the alert component. Basically:

```<code>export class AlertMessagesService {

public alertStatus: BehaviorSubject<AlertMessage>;

public addAlert(msg: string = null, type: string = 'info') {
    this.alertStatus.next({
        show: true,
        msg: msg,
        type: type
    });
}

}
</code>```

And here is the component where the alert is showed:

```<code>export class AlertMessages implements OnInit {

alerts: Array<AlertMessage> = [];

constructor(
    private alertService: AlertMessagesService) {
}

ngOnInit() {

    this.alertService.alertStatus.subscribe((alert: AlertMessage) => {

        if(alert.show) {
            this.alerts.push(alert);
        }

    });

}

}
</code>```

I hope it helps if someone run into this situation.

Title: Logout user with alert message

Body:
I have a login component that controls the login page and alerts (success, error, information,...). I can display alerts with no problems when I am in the page, for instance, to inform the user invalid credentials or to inform that the page is being updated. Basically this messages are variables in the login component class binded to the frontend:

export class Login {
  error;
  info;
}

Now when the user logouts I redirect to the login page:

this.router.navigate(['/login']);

I want to show an alert to the user informing the logout process was successful (actually I will use this same logic to inform if the user session expires). I created two methods in login component class:

  logout() {
    this.authenticationService.logout()
        .subscribe(response => {
            this.logoutRedirect();
        },
        error => {
            this.logoutRedirect();
        });
  }

  logoutRedirect() {
      this.authenticationService.removeUser();
      this.info = 'Logout success';
      this.router.navigate(['/login']);
  }

Everything works except the message. I believe it happens because when the user is redirected a new login class is used and this one does not have the info information.

How is the best approach for this problem: I will use it a lot in my application so I want to do it correctly.

Body:
I solved this problem using a service. The service has a BehaviorSubject that is subscribed by the alert component. Basically:

export class AlertMessagesService {

public alertStatus: BehaviorSubject<AlertMessage>;

public addAlert(msg: string = null, type: string = 'info') {
    this.alertStatus.next({
        show: true,
        msg: msg,
        type: type
    });
}

}

And here is the component where the alert is showed:

export class AlertMessages implements OnInit {

alerts: Array<AlertMessage> = [];

constructor(
    private alertService: AlertMessagesService) {
}

ngOnInit() {

    this.alertService.alertStatus.subscribe((alert: AlertMessage) => {

        if(alert.show) {
            this.alerts.push(alert);
        }

    });

}

}

I hope it helps if someone run into this situation.


问:
Range of size of tensor's dimension - tf.range
I'm trying to define an operation for a NN I'm implementing, but to do so I need to iterate over the dimension of a tensor. I have a small working example below.

```<code>X = tf.placeholder(tf.float32, shape=[None, 10])
idx = [[i] for i in tf.range(X.get_shape()[0])]
</code>```

This produces an error stating

```<code>ValueError: Cannot convert an unknown Dimension to a Tensor: ?
</code>```

When using the same code but using tf.shape instead, resulting in the code being

```<code>X = tf.placeholder(tf.float32, shape=[None, 10])
idx = [[i] for i in tf.range(tf.shape(X)[0])]
</code>```

Gives the following error

```<code>TypeError: 'Tensor' object is not iterable.
</code>```

The way that I'm implementing this NN, the batch_size isn't defined until the training function, which is at the end of the code. This is just where I'm building the graph itself, so the batch_size isn't known by this point, and it can't be fixed as the training batch_size and the test set batch_sizes are different.

What is the best way to fix this? This is the last thing keeping my code from running, as I got it to run with a fixed batch_size, though those results aren't useful. I've been pouring over the TensorFlow API Documentation and stack overflow for weeks to no avail.

I've also tried to feed in a placeholder into the range, so when I'm running the test/training set the code would be the following

```<code>X = tf.placeholder(tf.float32, shape=[None, 10])
bs = tf.placeholder(tf.int32)

def My_Function(X):
    # Do some stuff to X
    idx = [[i] for i in tf.range(bs)]
    # return some tensor

A = tf.nn.relu(My_Function(X))
</code>```

However, this gives the same error as above

```<code>TypeError: 'Tensor' object is not iterable.
</code>```

答:
Could tf.map_fn be what you are looking for?

```<code>x = tf.placeholder(tf.float32, shape=[None, 10])
f = tf.map_fn(lambda y: y, x) # or perhaps something more useful than identity
</code>```

EDIT

Now that I understand better, I think the problem is that you are trying to get the range while the graph is created, as opposed to when the graph is run.

Also, you need to use tf.range to query the shape at run time.

```<code>In [2]: import numpy as np
   ...: import tensorflow as tf
   ...: x = tf.placeholder(tf.float32, shape=[None, 10])
   ...: sess = tf.InteractiveSession()
   ...: sess.run(tf.range(tf.shape(x)[0]), {x: np.zeros((7,10))})
Out[2]: array([0, 1, 2, 3, 4, 5, 6])
</code>```

Body:
I'm trying to define an operation for a NN I'm implementing, but to do so I need to iterate over the dimension of a tensor. I have a small working example below.

X = tf.placeholder(tf.float32, shape=[None, 10])
idx = [[i] for i in tf.range(X.get_shape()[0])]

This produces an error stating

ValueError: Cannot convert an unknown Dimension to a Tensor: ?

When using the same code but using tf.shape instead, resulting in the code being

X = tf.placeholder(tf.float32, shape=[None, 10])
idx = [[i] for i in tf.range(tf.shape(X)[0])]

Gives the following error

TypeError: 'Tensor' object is not iterable.

The way that I'm implementing this NN, the batch_size isn't defined until the training function, which is at the end of the code. This is just where I'm building the graph itself, so the batch_size isn't known by this point, and it can't be fixed as the training batch_size and the test set batch_sizes are different.

What is the best way to fix this? This is the last thing keeping my code from running, as I got it to run with a fixed batch_size, though those results aren't useful. I've been pouring over the TensorFlow API Documentation and stack overflow for weeks to no avail.

I've also tried to feed in a placeholder into the range, so when I'm running the test/training set the code would be the following

X = tf.placeholder(tf.float32, shape=[None, 10])
bs = tf.placeholder(tf.int32)

def My_Function(X):
    # Do some stuff to X
    idx = [[i] for i in tf.range(bs)]
    # return some tensor

A = tf.nn.relu(My_Function(X))

However, this gives the same error as above

TypeError: 'Tensor' object is not iterable.

Body:
Could tf.map_fn be what you are looking for?

x = tf.placeholder(tf.float32, shape=[None, 10])
f = tf.map_fn(lambda y: y, x) # or perhaps something more useful than identity

EDIT

Now that I understand better, I think the problem is that you are trying to get the range while the graph is created, as opposed to when the graph is run.

Also, you need to use tf.range to query the shape at run time.

In [2]: import numpy as np
   ...: import tensorflow as tf
   ...: x = tf.placeholder(tf.float32, shape=[None, 10])
   ...: sess = tf.InteractiveSession()
   ...: sess.run(tf.range(tf.shape(x)[0]), {x: np.zeros((7,10))})
Out[2]: array([0, 1, 2, 3, 4, 5, 6])


问:
Concatenate two values from an object
I am building a place autocomplete address form like the demo seen here https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform

However in the demo the street number and street name are put into separated fields. What I want to do is concatenate those two values which are street_number: 'short_name' and route: 'long_name' and put them into a new field.

I'm trying to find where in the code those values are being stored and I see this array

```<code>var componentForm = {
    street_number: 'short_name',
    route: 'long_name',
    locality: 'long_name',
    administrative_area_level_1: 'long_name',
    administrative_area_level_2: 'long_name',
    postal_code: 'short_name'
};
</code>```

So if I do console.log(componentForm); it returns the whole thing. So I tried console.log(componentForm[route]); but the console says route is undefined

So my question is, how can I find value for street number and street name, then concatenate them into a new field in the form?

Posting my full script code, as it's slightly modified (I removed the geocode service and restricted suggestions to US addresses only, and also added the state county as one of the returned values)

```<code>// load google api
var placeSearch, autocomplete;
var componentForm = {
    street_number: 'short_name',
    route: 'long_name',
    locality: 'long_name',
    administrative_area_level_1: 'long_name',
    administrative_area_level_2: 'long_name',
    postal_code: 'short_name'
};

function initAutocomplete() {
    // Create the autocomplete object, restricting the search to US locations
    var input = document.getElementById('autocomplete');
    var options = {
        componentRestrictions: {
            country: 'us'
        }
    };

    autocomplete = new google.maps.places.Autocomplete(input, options);

    // When the user selects an address from the dropdown, populate the address
    // fields in the form.
    autocomplete.addListener('place_changed', fillInAddress);
}

function fillInAddress() {
    // Get the place details from the autocomplete object.
    var place = autocomplete.getPlace();

    for (var component in componentForm) {
        $(".autoSearch").hide(1000);
        $(".hiddenForm").show(1000);
        document.getElementById(component).value = '';
        document.getElementById(component).disabled = false;
    }

    // Get each component of the address from the place details
    // and fill the corresponding field on the form.
    for (var i = 0; i < place.address_components.length; i++) {
        var addressType = place.address_components[i].types[0];

        if (componentForm[addressType]) {
            var val = place.address_components[i][componentForm[addressType]];

            document.getElementById(addressType).value = val;

        }
    }
}
</code>```

答:
When you write componentForm[route] javascript will look for the route variable and use its content as the name of the property of the componentForm object, there is no route variable so javascript is telling you that it is undefined.

If you want to access the route property you should do this componentForm["route"] or this componentForm.route , to create this new field you should add a line like this:

```<code>componentForm.full_address = componentForm.route + " " + componentForm.street_number;
</code>```

Title: Concatenate two values from an object

Body:
I am building a place autocomplete address form like the demo seen here https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform

However in the demo the street number and street name are put into separated fields. What I want to do is concatenate those two values which are street_number: 'short_name' and route: 'long_name' and put them into a new field.

I'm trying to find where in the code those values are being stored and I see this array

var componentForm = {
    street_number: 'short_name',
    route: 'long_name',
    locality: 'long_name',
    administrative_area_level_1: 'long_name',
    administrative_area_level_2: 'long_name',
    postal_code: 'short_name'
};

So if I do console.log(componentForm); it returns the whole thing. So I tried console.log(componentForm[route]); but the console says route is undefined

So my question is, how can I find value for street number and street name, then concatenate them into a new field in the form?

Posting my full script code, as it's slightly modified (I removed the geocode service and restricted suggestions to US addresses only, and also added the state county as one of the returned values)

// load google api
var placeSearch, autocomplete;
var componentForm = {
    street_number: 'short_name',
    route: 'long_name',
    locality: 'long_name',
    administrative_area_level_1: 'long_name',
    administrative_area_level_2: 'long_name',
    postal_code: 'short_name'
};

function initAutocomplete() {
    // Create the autocomplete object, restricting the search to US locations
    var input = document.getElementById('autocomplete');
    var options = {
        componentRestrictions: {
            country: 'us'
        }
    };

    autocomplete = new google.maps.places.Autocomplete(input, options);

    // When the user selects an address from the dropdown, populate the address
    // fields in the form.
    autocomplete.addListener('place_changed', fillInAddress);
}

function fillInAddress() {
    // Get the place details from the autocomplete object.
    var place = autocomplete.getPlace();

    for (var component in componentForm) {
        $(".autoSearch").hide(1000);
        $(".hiddenForm").show(1000);
        document.getElementById(component).value = '';
        document.getElementById(component).disabled = false;
    }

    // Get each component of the address from the place details
    // and fill the corresponding field on the form.
    for (var i = 0; i < place.address_components.length; i++) {
        var addressType = place.address_components[i].types[0];

        if (componentForm[addressType]) {
            var val = place.address_components[i][componentForm[addressType]];

            document.getElementById(addressType).value = val;

        }
    }
}

Body:
When you write componentForm[route] javascript will look for the route variable and use its content as the name of the property of the componentForm object, there is no route variable so javascript is telling you that it is undefined.

If you want to access the route property you should do this componentForm["route"] or this componentForm.route , to create this new field you should add a line like this:

componentForm.full_address = componentForm.route + " " + componentForm.street_number;


问:
Wordpress get current page name or id within ajax request callback
I need to get current page id or name from ajax request callback. Initially at loading a page i made an ajax request. In its callback method i need to get the current page id or name. I used following code for ajax request.

```<code>$.ajax({
        type: "POST",
        url: my_site.home_url + '/wp-admin/admin-ajax.php',
        data: {
            action: "notes_select_page"
        },
        dataType: "html",
        success: function (Response) {
            if (Response == "OK") {
                Notes.renderBoardList();
            } else {

            }
        },
        async: true
    });
</code>```

I took the request from action hook.

```<code>add_action('wp_ajax_nopriv_notes_select_page', 'Notes::select_page');add_action('wp_ajax_optimal_notes_select_page', 'Notes::select_page');
</code>```

And the callback i used several code but doesn't work. Try 1.

```<code>public static function select_page(){
    global $pagename;
    die($pagename);
}
</code>```

Try 2

```<code>public static function select_page(){
    global $wp_query;
    $pagename = get_query_var( 'pagename' );
    if ( !$pagename) {
        $post = $wp_query->get_queried_object();
        $pagename = $post->post_name;
    }
    die($pagename);
}
</code>```

Try 3

```<code>public static function select_page(){
    global $post;
    die($post->ID);
}
</code>```

But unfortunately any of them doesn't work to get current page ID or name. Callback is working fine with other values.
Thanks in advance.

答:
You can obtain alternatively by the hidden field the post/page id in the following manner. This code is inserted in the template file (and then the value will be send to your ajax action hook as indicated above):

```<code>    <?php
    echo '<input type="hidden" name="activepost" id="activepost"
    value="'.get_the_ID().'" />'
    ;?>
</code>```

Check out this for reference: https://developer.wordpress.org/reference/functions/get_the_id/

Body:
I need to get current page id or name from ajax request callback. Initially at loading a page i made an ajax request. In its callback method i need to get the current page id or name. I used following code for ajax request.

$.ajax({
        type: "POST",
        url: my_site.home_url + '/wp-admin/admin-ajax.php',
        data: {
            action: "notes_select_page"
        },
        dataType: "html",
        success: function (Response) {
            if (Response == "OK") {
                Notes.renderBoardList();
            } else {

            }
        },
        async: true
    });

I took the request from action hook.

add_action('wp_ajax_nopriv_notes_select_page', 'Notes::select_page');add_action('wp_ajax_optimal_notes_select_page', 'Notes::select_page');

And the callback i used several code but doesn't work. Try 1.

public static function select_page(){
    global $pagename;
    die($pagename);
}

Try 2

public static function select_page(){
    global $wp_query;
    $pagename = get_query_var( 'pagename' );
    if ( !$pagename) {
        $post = $wp_query->get_queried_object();
        $pagename = $post->post_name;
    }
    die($pagename);
}

Try 3

public static function select_page(){
    global $post;
    die($post->ID);
}

But unfortunately any of them doesn't work to get current page ID or name. Callback is working fine with other values.
Thanks in advance.

Body:
You can obtain alternatively by the hidden field the post/page id in the following manner. This code is inserted in the template file (and then the value will be send to your ajax action hook as indicated above):

    <?php
    echo '<input type="hidden" name="activepost" id="activepost"
    value="'.get_the_ID().'" />'
    ;?>

Check out this for reference: https://developer.wordpress.org/reference/functions/get_the_id/


问:
Batch insert causing failure
I have a task where I need to insert a lot of data into the database using hibernate. I am currently testing with inserting 500,000 entities which each have one relation, so 1,000,000 inserts in total.
Based on this guide I have created the following code which actually works. All the data is inserted and committed without errors.

```<code>import javax.annotation.Resource;
import javax.ejb.*;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.*;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.TransformerException;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;

@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class StackoverflowExample {
    @PersistenceContext
    private EntityManager entityManager;

    @Resource
    private SessionContext sessionContext;

    @EJB
    private XmlProcessorFactory xmlProcessorFactory;

    @EJB
    private TaskManagerBean taskManagerBean;

    public void processFile(String[] args, Task task) throws HeuristicRollbackException, RollbackException, HeuristicMixedException, SystemException, IOException, TransformerException, ParseException, XMLStreamException, NotSupportedException {
        UserTransaction tx = null;

        XmlProcessor instance = xmlProcessorFactory.getInstance(new File("data.xml"));

        XmlElement nextElement = instance.getNextElement();
        int i = 0;
        int batchSize = 50;
        entityManager.setProperty("hibernate.jdbc.batch_size", batchSize);
        tx = sessionContext.getUserTransaction();
        tx.begin();
        while (nextElement != null) {
            Entry entry = new Entry(nextElement.getUserReference(), nextElement.getXml());

            entityManager.persist(entry);

            if (i % batchSize == 0) {
                entityManager.flush();
                entityManager.clear();
            }

            nextElement = instance.getNextElement();
            i++;
        }

        task.setStatus(status);
        task.setEndTime(now());
        // This gives the OutOfMemoryError
        entityManager.merge(task);

        tx.commit();
    }
}
</code>```

This will fail in the line where I call taskManagerBean.update() with the following error:

```<code>2017-03-31 08:49:30,212 ERROR [org.jboss.as.ejb3.invocation] (EJB default - 3) WFLYEJB0034:
EJB Invocation failed on component TaskManagerBean for method public void
TaskManagerBean.update(Task,TaskStatus):
javax.ejb.EJBTransactionRolledbackException: org.hibernate.exception.GenericJDBCException:
could not load an entity: [Task#3]
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.handleInCallerTx(CMTTxInterceptor.java:159)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:256)
    ...
    at TaskManagerBean$$$view18.update(Unknown Source)
    at StoreEntriesBean.processFile(StoreEntriesBean.java:117)
    ...
    at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not load an entity: [Task#3]
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692)
    ...
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:254)
    ... 104 more
Caused by: org.hibernate.exception.GenericJDBCException: could not load an entity: [Task#3]
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
    ...
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:1161)
    ... 135 more
Caused by: java.sql.SQLException: Error
    at org.jboss.jca.adapters.jdbc.WrappedConnection.checkException(WrappedConnection.java:1972)
    ...
    at org.hibernate.loader.Loader.loadEntity(Loader.java:2204)
    ... 155 more
Caused by: java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOfRange(Arrays.java:3664)
    ...
    at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)
</code>```

Runtime.getRuntime().freeMemory() returns 71540896 right before the error.

I start Wildfly with -Xmx2048m and a quick glance at memory usage shows that it only uses less than half of it.

I have tried committing the inserted Entries after every 1,000 inserts. This triggers the TaskManagerBean and it will fail the same way after a few updates.
In a few occasions I have also seen this error after I finished the huge batch job and the owning entity was to be updated.

I have tried with a file with just 5,000 entries and the entire process works fine.

Is this a bug in the MySQL driver or am I doing something wrong here?

答:
Do you close either session or entity manager?

I Never used EntityManager but when you deal with database in Java, you should always "explicitly" close connection when a job(transaction) is done

Title: Batch insert causing failure

Body:
I have a task where I need to insert a lot of data into the database using hibernate. I am currently testing with inserting 500,000 entities which each have one relation, so 1,000,000 inserts in total.
Based on this guide I have created the following code which actually works. All the data is inserted and committed without errors.

import javax.annotation.Resource;
import javax.ejb.*;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.*;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.TransformerException;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;

@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class StackoverflowExample {
    @PersistenceContext
    private EntityManager entityManager;

    @Resource
    private SessionContext sessionContext;

    @EJB
    private XmlProcessorFactory xmlProcessorFactory;

    @EJB
    private TaskManagerBean taskManagerBean;

    public void processFile(String[] args, Task task) throws HeuristicRollbackException, RollbackException, HeuristicMixedException, SystemException, IOException, TransformerException, ParseException, XMLStreamException, NotSupportedException {
        UserTransaction tx = null;

        XmlProcessor instance = xmlProcessorFactory.getInstance(new File("data.xml"));

        XmlElement nextElement = instance.getNextElement();
        int i = 0;
        int batchSize = 50;
        entityManager.setProperty("hibernate.jdbc.batch_size", batchSize);
        tx = sessionContext.getUserTransaction();
        tx.begin();
        while (nextElement != null) {
            Entry entry = new Entry(nextElement.getUserReference(), nextElement.getXml());

            entityManager.persist(entry);

            if (i % batchSize == 0) {
                entityManager.flush();
                entityManager.clear();
            }

            nextElement = instance.getNextElement();
            i++;
        }

        task.setStatus(status);
        task.setEndTime(now());
        // This gives the OutOfMemoryError
        entityManager.merge(task);

        tx.commit();
    }
}

This will fail in the line where I call taskManagerBean.update() with the following error:

2017-03-31 08:49:30,212 ERROR [org.jboss.as.ejb3.invocation] (EJB default - 3) WFLYEJB0034:
EJB Invocation failed on component TaskManagerBean for method public void
TaskManagerBean.update(Task,TaskStatus):
javax.ejb.EJBTransactionRolledbackException: org.hibernate.exception.GenericJDBCException:
could not load an entity: [Task#3]
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.handleInCallerTx(CMTTxInterceptor.java:159)
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:256)
    ...
    at TaskManagerBean$$$view18.update(Unknown Source)
    at StoreEntriesBean.processFile(StoreEntriesBean.java:117)
    ...
    at org.jboss.threads.JBossThread.run(JBossThread.java:320)
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not load an entity: [Task#3]
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1692)
    ...
    at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:254)
    ... 104 more
Caused by: org.hibernate.exception.GenericJDBCException: could not load an entity: [Task#3]
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
    ...
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.merge(AbstractEntityManagerImpl.java:1161)
    ... 135 more
Caused by: java.sql.SQLException: Error
    at org.jboss.jca.adapters.jdbc.WrappedConnection.checkException(WrappedConnection.java:1972)
    ...
    at org.hibernate.loader.Loader.loadEntity(Loader.java:2204)
    ... 155 more
Caused by: java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOfRange(Arrays.java:3664)
    ...
    at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)

Runtime.getRuntime().freeMemory() returns 71540896 right before the error.

I start Wildfly with -Xmx2048m and a quick glance at memory usage shows that it only uses less than half of it.

I have tried committing the inserted Entries after every 1,000 inserts. This triggers the TaskManagerBean and it will fail the same way after a few updates.
In a few occasions I have also seen this error after I finished the huge batch job and the owning entity was to be updated.

I have tried with a file with just 5,000 entries and the entire process works fine.

Is this a bug in the MySQL driver or am I doing something wrong here?


问:
How to create multiple instances to an implementation of an interface?
Let A be an interface which has a method a.
Let B be a class which implements A and has method a and has three fields 1,2,3.
I want to use two instances of A (meaning B), both of which have different values of 1,2,3 (present in cfg file) at two different places.  </p>

<p>Can someone provide a simple and elegant solution to this problem using Guice. </p>

答:
You don't tell how the class that uses your dependency references the interface. I assume that you want to reference it with an interface.

What you can use, is annotation that will denote which instance you want to use. Assume that these are your implementations:

```<code>interface A {
    void a();
}

class B implements A {
    private int value;

    void a() { ... }

    B(int value) { this.value = value; }
}
</code>```

And these are the classes that use the implementations:

```<code>class UserFirst {

    private A a;

    @Inject
    UserFirst(@Named("first") A a) { this.a = a; }
}

class UserSecond {

    private A a;

    @Inject
    UserSecond(@Named("second") A a) { this.a = a; }
}
</code>```

The thing that decides which implementation is going to be injected is the @Named annotation. You can also define your annotations, but usually it's an overkill.

Now, in order to bind that, you can do something like this:

class MyModule extends AbstractModule {
    @Override
    protected void configure() {

    A first = new B(1);
    B second = new B(2);

    bind(A.class)
        .annotatedWith(Names.named("first")).toInstance(first);

    bind(A.class)
        .annotatedWith(Names.named("second")).toInstance(second);
    }
}
```

Here's the full documentation: https://github.com/google/guice/wiki/BindingAnnotations

Body:
Let A be an interface which has a method a.
Let B be a class which implements A and has method a and has three fields 1,2,3.
I want to use two instances of A (meaning B), both of which have different values of 1,2,3 (present in cfg file) at two different places.

Can someone provide a simple and elegant solution to this problem using Guice.

Body:
You don't tell how the class that uses your dependency references the interface. I assume that you want to reference it with an interface.

What you can use, is annotation that will denote which instance you want to use. Assume that these are your implementations:

interface A {
    void a();
}

class B implements A {
    private int value;

    void a() { ... }

    B(int value) { this.value = value; }
}

And these are the classes that use the implementations:

class UserFirst {

    private A a;

    @Inject
    UserFirst(@Named("first") A a) { this.a = a; }
}

class UserSecond {

    private A a;

    @Inject
    UserSecond(@Named("second") A a) { this.a = a; }
}

The thing that decides which implementation is going to be injected is the @Named annotation. You can also define your annotations, but usually it's an overkill.

Now, in order to bind that, you can do something like this:

class MyModule extends AbstractModule {
    @Override
    protected void configure() {

    A first = new B(1);
    B second = new B(2);

    bind(A.class)
        .annotatedWith(Names.named("first")).toInstance(first);

    bind(A.class)
        .annotatedWith(Names.named("second")).toInstance(second);
    }
}

Here's the full documentation: https://github.com/google/guice/wiki/BindingAnnotations


问:
Appending blank rows to dataframe if column does not exist
This question is kind of odd and complex, so bear with me, please.

I have several massive CSV files (GB size) that I am importing with pandas.  These CSV files are dumps of data collected by a data acquisition system, and I don't need most of it, so I'm using the usecols parameter to filter out the relevant data.  The issue is that not all of the CSV files have all of the columns I need (a property of the data system being used).

The problem is that, if the column doesn't exist in the file but is specified in usecols, read_csv throws an error.

Is there a straightforward way to force a specified column set in a dataframe and have pandas just return blank rows if the column doesn't exist?  I thought about iterating over each column for each file and working the resulting series into the dataframe, but that seems inefficient and unwieldy.

答:
I thought about iterating over each column for each file and working the resulting series into the dataframe, but that seems inefficient and unwieldy.

Assuming some kind of master list all_cols_to_use, can you do something like:

```<code>def parse_big_csv(csvpath):
    with open(csvpath, 'r') as infile:
        header = infile.readline().strip().split(',')
        cols_to_use = sorted(set(header) & set(all_cols_to_use))
        missing_cols = sorted(set(all_cols_to_use) - set(header))
    df = pd.read_csv(csvpath, usecols=cols_to_use)
    df.loc[:, missing_cols] = np.nan
    return df
</code>```

This assumes that you're okay with filling the missing columns with np.nan, but should work. (Also, if you’re concatenating the data frames, the missing columns will be in the final df and filled with np.nan as appropriate.)

Body:
I thought about iterating over each column for each file and working the resulting series into the dataframe, but that seems inefficient and unwieldy.

Assuming some kind of master list all_cols_to_use, can you do something like:

def parse_big_csv(csvpath):
    with open(csvpath, 'r') as infile:
        header = infile.readline().strip().split(',')
        cols_to_use = sorted(set(header) & set(all_cols_to_use))
        missing_cols = sorted(set(all_cols_to_use) - set(header))
    df = pd.read_csv(csvpath, usecols=cols_to_use)
    df.loc[:, missing_cols] = np.nan
    return df

This assumes that you're okay with filling the missing columns with np.nan, but should work. (Also, if you’re concatenating the data frames, the missing columns will be in the final df and filled with np.nan as appropriate.)


问:
Parsing csv file in scala
How can i parse this csv file in Scala, to extract an object Data contain (date,time,longitude,latitude)

*M…….:Dy4.5

*N……….:14_540

*V…..:N

*S….:1.2.1

*yyyy/mm/dd;hh:mm:ss;long;lat

2016/05/09;12:50:19;-122.45006;38.47320

2016/05/09;13:04:10;-122.45011;38.47317

i already wrote this function but it just read the file, i don't know how to transform it into object

```<code>def readData(fileName:String): Vector[Array[String]] = {
      for {
        line <- Source.fromFile(fileName).getLines().toVector
        values = line.split(";").map(_.trim)
      } yield values
    }
</code>```

答:
You can use scala type matching for this to build up on Anastasiia Kharchenko's response</p>

```<code>def readData(fileName:String): Vector[Data] = {
  for {
    line <- Source.fromFile(fileName).getLines().toVector
    data <- parseCsvLine(line)
  } yield data
}

def parseCsvLine(line: String): Option[Data] = {
    line.split(";").toVector.map(_.trim) match {
             case Vector(date, time, longitude, latitude) => Some(Data(date, time, longitude, latitude))
             case _ => println(s"WARNING UNKNOWN DATA FORMAT FOR LINE: $line")
                       None
         }

    }
}
</code>```

Title: Parsing csv file in scala

Body:
How can i parse this csv file in Scala, to extract an object Data contain (date,time,longitude,latitude)

*M…….:Dy4.5

*N……….:14_540

*V…..:N

*S….:1.2.1

*yyyy/mm/dd;hh:mm:ss;long;lat

2016/05/09;12:50:19;-122.45006;38.47320

2016/05/09;13:04:10;-122.45011;38.47317

i already wrote this function but it just read the file, i don't know how to transform it into object

def readData(fileName:String): Vector[Array[String]] = {
      for {
        line <- Source.fromFile(fileName).getLines().toVector
        values = line.split(";").map(_.trim)
      } yield values
    }

Body:
You can use scala type matching for this to build up on Anastasiia Kharchenko's response

def readData(fileName:String): Vector[Data] = {
  for {
    line <- Source.fromFile(fileName).getLines().toVector
    data <- parseCsvLine(line)
  } yield data
}

def parseCsvLine(line: String): Option[Data] = {
    line.split(";").toVector.map(_.trim) match {
             case Vector(date, time, longitude, latitude) => Some(Data(date, time, longitude, latitude))
             case _ => println(s"WARNING UNKNOWN DATA FORMAT FOR LINE: $line")
                       None
         }

    }
}


问:
Repeat system() command in C++?
What is the easiest way to repeat a simple system command on multiple CMD's in C++?  For instance, how could I repeat this code on multiple terminal windows from my C++ code?

system( ("ping "+ ip +" -t -l 32").c_str() );

答:
From a networking perspective, I don't think that pinging a single system from multiple terminals will be as effective as pinging that system from multiple remote systems.

Anyways, in regards to the easiest way to ping a system from multiple processes... just use the shell directly. Something like:

```<code>target=s4
for remotehost in s1 s2 s3; do (ssh -n $remotehost ping $target -t -l 32 & ) ; done
</code>```

The "remotehost" doesn't have to really be a remote host either. You can just use "localhost" multiple times (instead of multiple names of remote hosts).

Alternatively if you really want to use C++ from a single host:

```<code>#include <cstdlib>
#include <string>

int main()
{
    const std::string ip = "foo";
    for (int i = 0; i < 3; ++i)
    {
        std::system(("ping " + ip + " -t -l 32 & ").c_str());
    }
}
</code>```

Note the usage of the ampersand (&) character in the input string to the system function. That instructs the shell to run the given task in the background. That way system returns immediately and the ping command basically runs at the same time as the two other instances of the command.

Hope this helps answer your question.

Title: Repeat system() command in C++?

Body:
From a networking perspective, I don't think that pinging a single system from multiple terminals will be as effective as pinging that system from multiple remote systems.

Anyways, in regards to the easiest way to ping a system from multiple processes... just use the shell directly. Something like:

target=s4
for remotehost in s1 s2 s3; do (ssh -n $remotehost ping $target -t -l 32 & ) ; done

The "remotehost" doesn't have to really be a remote host either. You can just use "localhost" multiple times (instead of multiple names of remote hosts).

Alternatively if you really want to use C++ from a single host:

#include <cstdlib>
#include <string>

int main()
{
    const std::string ip = "foo";
    for (int i = 0; i < 3; ++i)
    {
        std::system(("ping " + ip + " -t -l 32 & ").c_str());
    }
}

Note the usage of the ampersand (&) character in the input string to the system function. That instructs the shell to run the given task in the background. That way system returns immediately and the ping command basically runs at the same time as the two other instances of the command.

Hope this helps answer your question.


问:
Get json from request flask
Client code:

```<code>import requests
import json

url = 'http://127.0.0.1:5050/login'
user = "newUser"
password = "password"
headers = {'content-type': 'application/json'}
response = requests.post(url, data={"user": user,"pass": password}, headers = headers)
</code>```

Server code:

```<code>from flask import Flask, request, make_response

app = Flask(__name__)

@app.route('/login', methods=['GET','POST'])
def login():
 if request.method == 'POST':

    username = request.form.get("user")
    password = request.form.get("pass")
    //more code
    return make_response("",200)

if __name__ == "__main__":
     app.run(host = "127.0.0.1", port = 5050)
</code>```

The problem is that my username and password are always None.

I also tried using:

```<code>content = request.get_json(force = True)
password = content['pass']
</code>```

and

```<code>request.form['user']
</code>```

When I print the content I have: < Request 'http://127.0.0.1:5050/login' [POST]> .So I cannot find the json send from the client.

EDIT:

I did add json.dumps and used request.get_json() and it worked

答:
You are sending form encoded data, not JSON. Just setting the content-type doesn't turn your request into JSON. Use json= to send JSON data.

```<code>response = requests.post(url, json={"user": user,"pass": password})
</code>```

Retrieve the data in Flask with:

```<code>data = request.get_json()
</code>```

Title: Get json from request flask

Body:
Client code:

import requests
import json

url = 'http://127.0.0.1:5050/login'
user = "newUser"
password = "password"
headers = {'content-type': 'application/json'}
response = requests.post(url, data={"user": user,"pass": password}, headers = headers)

Server code:

from flask import Flask, request, make_response

app = Flask(__name__)

@app.route('/login', methods=['GET','POST'])
def login():
 if request.method == 'POST':

    username = request.form.get("user")
    password = request.form.get("pass")
    //more code
    return make_response("",200)

if __name__ == "__main__":
     app.run(host = "127.0.0.1", port = 5050)

The problem is that my username and password are always None.

I also tried using:

content = request.get_json(force = True)
password = content['pass']

and

request.form['user']

When I print the content I have: < Request 'http://127.0.0.1:5050/login' [POST]> .So I cannot find the json send from the client.

EDIT:

I did add json.dumps and used request.get_json() and it worked

Body:
You are sending form encoded data, not JSON. Just setting the content-type doesn't turn your request into JSON. Use json= to send JSON data.

response = requests.post(url, json={"user": user,"pass": password})

Retrieve the data in Flask with:

data = request.get_json()


问:
How to set min width on GtkScrollbar?
I want to develop new features in Quod Libet music player.

I need to increase size of specific scrollbar.
There's a function already exists to apply css to a widget:

```<code>def add_css(widget, css):
    """Add css for the widget, overriding the theme.

    Can raise GLib.GError in case the css is invalid
    """

    if not isinstance(css, bytes):
        css = css.encode("utf-8")

    provider = Gtk.CssProvider()
    provider.load_from_data(css)
    context = widget.get_style_context()
    context.add_provider(provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
</code>```

So I try to apply css as this:

```<code>    self.scrollwin = sw = ScrolledWindow()
    sw.set_shadow_type(Gtk.ShadowType.IN)
    #get scrollbar
    vscrollbar = sw.get_vscrollbar()

    # 1rst attempt
    # qltk.add_css(vscrollbar, '* slider {min-width: 20px;}')

    #2nd attempt
    qltk.add_css(vscrollbar, 'scrollbar.vertical slider {min-width: 20px;}')
</code>```

I've got same error with 2 attempts:

'min-width' is not a valid property name (3)

Update 1

I try @Herbalist solution, scrollbar component is resized but "slider" always have same size. It add spaces on right and on left of "slider".

```<code>vscrollbar.set_size_request(50,-1)
</code>```

Is it possible to resize slider of scrollbar ?

Screenshot of result (I outline part of scrollbar in green):

答:
I'm not able to success with css, so I use deprecated method:

GtkRange:slider-width has been deprecated since version 3.20 and
  should not be used in newly-written code.

Use the min-height/min-width CSS properties on the slider element. The
  value of this style property is ignored.

As this:

```<code>qltk.add_css(vscrollbar, '* {-GtkRange-slider-width:40px}')
</code>```

Title: How to set min width on GtkScrollbar?

Body:
I want to develop new features in Quod Libet music player.

I need to increase size of specific scrollbar.
There's a function already exists to apply css to a widget:

def add_css(widget, css):
    """Add css for the widget, overriding the theme.

    Can raise GLib.GError in case the css is invalid
    """

    if not isinstance(css, bytes):
        css = css.encode("utf-8")

    provider = Gtk.CssProvider()
    provider.load_from_data(css)
    context = widget.get_style_context()
    context.add_provider(provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

So I try to apply css as this:

    self.scrollwin = sw = ScrolledWindow()
    sw.set_shadow_type(Gtk.ShadowType.IN)
    #get scrollbar
    vscrollbar = sw.get_vscrollbar()

    # 1rst attempt
    # qltk.add_css(vscrollbar, '* slider {min-width: 20px;}')

    #2nd attempt
    qltk.add_css(vscrollbar, 'scrollbar.vertical slider {min-width: 20px;}')

I've got same error with 2 attempts:

'min-width' is not a valid property name (3)

Update 1

I try @Herbalist solution, scrollbar component is resized but "slider" always have same size. It add spaces on right and on left of "slider".

vscrollbar.set_size_request(50,-1)

Is it possible to resize slider of scrollbar ?

Screenshot of result (I outline part of scrollbar in green):

Body:
I'm not able to success with css, so I use deprecated method:

GtkRange:slider-width has been deprecated since version 3.20 and
  should not be used in newly-written code.

Use the min-height/min-width CSS properties on the slider element. The
  value of this style property is ignored.

As this:

qltk.add_css(vscrollbar, '* {-GtkRange-slider-width:40px}')


问:
How to add javascript to my php MVC framework
I created a simple PHP MVC framework and I'm familiar with PHP. I think I understand the basics of JavaScript, but I have no idea how to use it with my MVC framework. Right now I have a folder in my root directory called scripts, a file inside of it called javascript.js and I put the appropriate source thing in my template. All I want to do right now is make a simple confirm box in the admin panel before accepting/deleting an application to join my site. Obviously there are two buttons (accept/delete) and I use onclick to call a function (AdminModel::acceptApplication). This is the AdminModel:acceptApplication function up to this point:

```<code>    public function acceptApplication($id) {
    $confirm=AdminModel::confirm();
    if($confirm) {
        $mysqli = BaseModel::dbConnect();
        $sql = "SELECT * FROM applications WHERE id=" . $id;
        $result = mysqli_query($mysqli, $sql);
        $row = mysqli_fetch_array($result);

        $sql = "INSERT INTO users (fname, lname, email, password) VALUES (" . $row['fname'] . ", " . $row['lname'] . ", " . $row['email'] . ", " . $row['password'] . ")";
        mysqli_query($mysqli, $sql);

        $sql = "DELETE FROM applications WHERE id=" . $id;
        mysqli_query($mysqli, $sql);

        header('Location: http://www.canforce.org/' . $_SESSION['language'] . '/admin/applications');
    }
    public function confirm() {
    $confirm = echo '<script> areYouSure(); </script>';
    return($confirm);
     }
</code>```

The JavaScript areYouSure() function returns true if you click yes:

```<code>function areYouSure() {
if(<?php echo $_SESSION['language'] ?> == "fr") {
    confirm("Êtes-vous sûr");
}
else {
    confirm("Are you Sure?");
}
</code>```

}

I'm guessing there's allot wrong with what I've done here, simply bc of the whole server side/client side thing, but then I have no idea how to use javascript properly within my website. I want this to work, but if anybody has any tips or links to tutorial on how I can incorporate javascript into my php mvc framework, that would be appreciated as well. Thanks

答:
PHP runs on a server. Javascript for the purpose of this conversation runs in the browser. You are trying to get the results of a browser level call on the server, another computer, it will not work. Your Model code exists on the server.

You need to have the js file included in your html file, in this case whatever passes for your view.

PS. The purpose of prepared statements is to prevent someone being able to run queries against your database, including deletes and getting all of your user info.

Body:
I created a simple PHP MVC framework and I'm familiar with PHP. I think I understand the basics of JavaScript, but I have no idea how to use it with my MVC framework. Right now I have a folder in my root directory called scripts, a file inside of it called javascript.js and I put the appropriate source thing in my template. All I want to do right now is make a simple confirm box in the admin panel before accepting/deleting an application to join my site. Obviously there are two buttons (accept/delete) and I use onclick to call a function (AdminModel::acceptApplication). This is the AdminModel:acceptApplication function up to this point:

    public function acceptApplication($id) {
    $confirm=AdminModel::confirm();
    if($confirm) {
        $mysqli = BaseModel::dbConnect();
        $sql = "SELECT * FROM applications WHERE id=" . $id;
        $result = mysqli_query($mysqli, $sql);
        $row = mysqli_fetch_array($result);

        $sql = "INSERT INTO users (fname, lname, email, password) VALUES (" . $row['fname'] . ", " . $row['lname'] . ", " . $row['email'] . ", " . $row['password'] . ")";
        mysqli_query($mysqli, $sql);

        $sql = "DELETE FROM applications WHERE id=" . $id;
        mysqli_query($mysqli, $sql);

        header('Location: http://www.canforce.org/' . $_SESSION['language'] . '/admin/applications');
    }
    public function confirm() {
    $confirm = echo '';
    return($confirm);
     }

The JavaScript areYouSure() function returns true if you click yes:

function areYouSure() {
if(<?php echo $_SESSION['language'] ?> == "fr") {
    confirm("Êtes-vous sûr");
}
else {
    confirm("Are you Sure?");
}

}

I'm guessing there's allot wrong with what I've done here, simply bc of the whole server side/client side thing, but then I have no idea how to use javascript properly within my website. I want this to work, but if anybody has any tips or links to tutorial on how I can incorporate javascript into my php mvc framework, that would be appreciated as well. Thanks


问:
Page View controller in container view with data from model
I have a container view that shows a page view controller. This view controller then shows 2 of the same view controllers and I can page back and forth.

```<code>        import UIKit

class ViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {

var pages = [UIViewController]()

override func viewDidLoad() {
super.viewDidLoad()

self.delegate = self
self.dataSource = self

let page1: UIViewController! = storyboard?.instantiateViewController(withIdentifier: "page1")
let page2: UIViewController! = storyboard?.instantiateViewController(withIdentifier: "page2")

pages.append(page1)
pages.append(page2)

setViewControllers([page1], direction: UIPageViewControllerNavigationDirection.forward, animated: true, completion: nil)
}

func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let currentIndex = pages.index(of: viewController)!
let previousIndex = abs((currentIndex - 1) % pages.count)
print("previous Index", pages[previousIndex])
return pages[previousIndex]
}

func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
let currentIndex = pages.index(of: viewController)!
let nextIndex = abs((currentIndex + 1) % pages.count)
print("next Index", pages[nextIndex])
return pages[nextIndex]
}

func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return pages.count
}

func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
return 0
}
}
</code>```

What I would like to do is create only one view controller, and then populate that view controller with data from an array

Array:

```<code>var pageTitles : Array<String> = ["God vs Man", "Cool Breeze", "Fire Sky"]
var pageImages : Array<String> = ["page1.png", "page2.png", "page3.png"]
</code>```

Is this possible with a container view controller presenting a page view controller?

Any help would be appreciated...

Denis Angell

答:
If you want to manage only one controller with multi data and UIPageController, you should create a view controller and to do something like that:

```<code>class PageViewController: UIViewController { // Id: 'PageViewController'
    // MARK: @IBOutlet

    /// Menu button item.
    @IBOutlet weak var image: UIImageView!

    /// Pagination controller.
    @IBOutlet weak var pagination: UIPageControl!

    // MARK: Variable
    struct Page {
        var title: String
        var image: String
        init(title: String, image: String) {
            self.title = title
            self.image = image
        }
    }
    let data: [Page] = []
    var currentIndex = 0

    override func viewDidLoad() {
        // Init data
        data.append(Page(title: "title1" , image: "page1.png"))
        data.append(Page(title: "title2" , image: "page2.png"))

        setValues(currentIndex)

        // Setup slide handler
        let leftSwipe = UISwipeGestureRecognizer(target: self,
                                                 action: #selector(PageViewController(_:)))
        let rightSwipe = UISwipeGestureRecognizer(target: self,
                                                  action: #selector(PageViewController(_:)))
        leftSwipe.direction = .left
        rightSwipe.direction = .right
        self.view.addGestureRecognizer(leftSwipe)
        self.view.addGestureRecognizer(rightSwipe)
    }

    /**
     Handle swipes allows to switch page.
     */
    func handleSwipes(_ sender: UISwipeGestureRecognizer) {
        let size = self.data.count
        let currentPosition = self.pagination.currentPage

        if sender.direction == .left && currentPosition < size-1 {
            nextPage()
        } else if sender.direction == .right && currentPosition > 0 {
            previousPage()
        }
    }

    private func setValues(index: Int) {
        self.pagination.currentPage = currentIndex
        self.title = pageTitles[index]
        self.image = pageImages[index]
    }

    // Button or see UIPageControl @IBOutlet
    private func nextPage() {
        currentIndex = abs((currentIndex + 1) % pages.count)
        print("next Index", pages[currentIndex])
        setValues(currentIndex)
    }

    // Button or see UIPageControl @IBOutlet
    private func previousPage() {
        currentIndex = abs((currentIndex - 1) % pages.count)
        print("next Index", pages[currentIndex])
        setValues(currentIndex)
    }

    // Other functions...
    // ...

}
</code>```

Body:
I have a container view that shows a page view controller. This view controller then shows 2 of the same view controllers and I can page back and forth.

        import UIKit

class ViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {

var pages = [UIViewController]()

override func viewDidLoad() {
super.viewDidLoad()

self.delegate = self
self.dataSource = self

let page1: UIViewController! = storyboard?.instantiateViewController(withIdentifier: "page1")
let page2: UIViewController! = storyboard?.instantiateViewController(withIdentifier: "page2")

pages.append(page1)
pages.append(page2)

setViewControllers([page1], direction: UIPageViewControllerNavigationDirection.forward, animated: true, completion: nil)
}

func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
let currentIndex = pages.index(of: viewController)!
let previousIndex = abs((currentIndex - 1) % pages.count)
print("previous Index", pages[previousIndex])
return pages[previousIndex]
}

func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
let currentIndex = pages.index(of: viewController)!
let nextIndex = abs((currentIndex + 1) % pages.count)
print("next Index", pages[nextIndex])
return pages[nextIndex]
}

func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return pages.count
}

func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
return 0
}
}

What I would like to do is create only one view controller, and then populate that view controller with data from an array

Array:

var pageTitles : Array<String> = ["God vs Man", "Cool Breeze", "Fire Sky"]
var pageImages : Array<String> = ["page1.png", "page2.png", "page3.png"]

Is this possible with a container view controller presenting a page view controller?

Any help would be appreciated...

Denis Angell

Body:
If you want to manage only one controller with multi data and UIPageController, you should create a view controller and to do something like that:

class PageViewController: UIViewController { // Id: 'PageViewController'
    // MARK: @IBOutlet

    /// Menu button item.
    @IBOutlet weak var image: UIImageView!

    /// Pagination controller.
    @IBOutlet weak var pagination: UIPageControl!

    // MARK: Variable
    struct Page {
        var title: String
        var image: String
        init(title: String, image: String) {
            self.title = title
            self.image = image
        }
    }
    let data: [Page] = []
    var currentIndex = 0

    override func viewDidLoad() {
        // Init data
        data.append(Page(title: "title1" , image: "page1.png"))
        data.append(Page(title: "title2" , image: "page2.png"))

        setValues(currentIndex)

        // Setup slide handler
        let leftSwipe = UISwipeGestureRecognizer(target: self,
                                                 action: #selector(PageViewController(_:)))
        let rightSwipe = UISwipeGestureRecognizer(target: self,
                                                  action: #selector(PageViewController(_:)))
        leftSwipe.direction = .left
        rightSwipe.direction = .right
        self.view.addGestureRecognizer(leftSwipe)
        self.view.addGestureRecognizer(rightSwipe)
    }

    /**
     Handle swipes allows to switch page.
     */
    func handleSwipes(_ sender: UISwipeGestureRecognizer) {
        let size = self.data.count
        let currentPosition = self.pagination.currentPage

        if sender.direction == .left && currentPosition < size-1 {
            nextPage()
        } else if sender.direction == .right && currentPosition > 0 {
            previousPage()
        }
    }

    private func setValues(index: Int) {
        self.pagination.currentPage = currentIndex
        self.title = pageTitles[index]
        self.image = pageImages[index]
    }

    // Button or see UIPageControl @IBOutlet
    private func nextPage() {
        currentIndex = abs((currentIndex + 1) % pages.count)
        print("next Index", pages[currentIndex])
        setValues(currentIndex)
    }

    // Button or see UIPageControl @IBOutlet
    private func previousPage() {
        currentIndex = abs((currentIndex - 1) % pages.count)
        print("next Index", pages[currentIndex])
        setValues(currentIndex)
    }

    // Other functions...
    // ...

}