问:
How to straighten curved line using OpenCV?
I have image with curved line like this :

I couldn't find a technique to straighten curved line using OpenCV. It is similar to this post Straightening a curved contour, but my question is specific to coding using opencv (in C++ is better).

So far, I'm only able to find the contour of the curved line.

```<code>int main()
{
    Mat src; Mat src_gray;
    src = imread("D:/2.jpg");
    cvtColor(src, src_gray, COLOR_BGR2GRAY);
    cv::blur(src_gray, src_gray, Size(1, 15));

    Canny(src_gray, src_gray, 100, 200, 3);
    /// Find contours
    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;
    RNG rng(12345);
    findContours(src_gray, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
    /// Draw contours
    Mat drawing = Mat::zeros(src_gray.size(), CV_8UC3);
    for (int i = 0; i < contours.size(); i++)
    {
        drawContours(drawing, contours, i, (255), 1, 8, hierarchy, 0, Point());
    }

    imshow("Result window", drawing);
    imwrite("D:/C_Backup_Folder/Ivan_codes/VideoStitcher/result/2_res.jpg", drawing);

    cv::waitKey();
    return 0;
}
</code>```

But I have no idea how to determine which line is curved and not, and how to straighten it. Is it possible? Any help would be appreciated.

答:
Here is my suggestion:

Before everything, resize your image into a much bigger image (for example 5 times bigger). Then do what you did before,  and get the contours. Find the right-most pixel of each contour, and then survey all pixel of that contour and count the horizontal distance of each pixels to the right-most pixel and make a shift for that row (entire row). This method makes a right shift to some rows and left shift to the others.

If you have multiple contours, calculate this shift value for every one of them in every single row and compute their "mean" value, and do the shift according to that mean value for each row.

At the end resize back your image. This is the simplest and fastest thing I could think of.

Body:
I have image with curved line like this :

I couldn't find a technique to straighten curved line using OpenCV. It is similar to this post Straightening a curved contour, but my question is specific to coding using opencv (in C++ is better).

So far, I'm only able to find the contour of the curved line.

int main()
{
    Mat src; Mat src_gray;
    src = imread("D:/2.jpg");
    cvtColor(src, src_gray, COLOR_BGR2GRAY);
    cv::blur(src_gray, src_gray, Size(1, 15));

    Canny(src_gray, src_gray, 100, 200, 3);
    /// Find contours
    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;
    RNG rng(12345);
    findContours(src_gray, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
    /// Draw contours
    Mat drawing = Mat::zeros(src_gray.size(), CV_8UC3);
    for (int i = 0; i < contours.size(); i++)
    {
        drawContours(drawing, contours, i, (255), 1, 8, hierarchy, 0, Point());
    }

    imshow("Result window", drawing);
    imwrite("D:/C_Backup_Folder/Ivan_codes/VideoStitcher/result/2_res.jpg", drawing);

    cv::waitKey();
    return 0;
}

But I have no idea how to determine which line is curved and not, and how to straighten it. Is it possible? Any help would be appreciated.


来源: stackexchange

问:
Tower of Hanoi maximum counts of 100 allowed
I've recently coded on python3 the famous Tower of Hanoi problem. I would like to ask how to add an additional condition: if there are more than 100 movements, then exit the program and print "Tedious computational power".

```<code># Tower of Hanoi problem
print('Tower of Hanoi')

no_discs = int(input('Please input number of discs: '))

column_1 = 1
column_2 = 2
column_3 = 3

def thaphanoi(no_discs, column_1, column_2, column_3):
    if no_discs == 1:
        print("Disc in column {} -> column {}".format(column_1, column_2))
    else:
        thaphanoi(no_discs - 1, column_1, column_3, column_2)
        thaphanoi(1, column_1, column_2, column_3)
        thaphanoi(no_discs - 1, column_3, column_2, column_1)

thaphanoi(no_discs, column_1, column_3, column_2)
print('Program ended')
</code>```

I expect this code to print 7.

答:
Tower of Hanoi problem can be solved with minimum of (2^n)-1 moves.

That is

```<code>No of move required for 1 disk -->  1
No of move required for 2 disks -->  3
No of move required for 3 disks -->  7
No of move required for 4 disks -->  15
No of move required for 5 disks -->  31
No of move required for 6 disks -->  63
No of move required for 7 disks -->  127
and so on..
</code>```

So you can calculate number of movements required after getting the number of required.

like,

```<code>min_moves = math.pow(2, no_discs) - 1
if min_moves > 100:
  print("Too many moves")
  sys.exit()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've recently coded on python3 the famous Tower of Hanoi problem. I would like to ask how to add an additional condition: if there are more than 100 movements, then exit the program and print "Tedious computational power".

# Tower of Hanoi problem
print('Tower of Hanoi')

no_discs = int(input('Please input number of discs: '))

column_1 = 1
column_2 = 2
column_3 = 3

def thaphanoi(no_discs, column_1, column_2, column_3):
    if no_discs == 1:
        print("Disc in column {} -> column {}".format(column_1, column_2))
    else:
        thaphanoi(no_discs - 1, column_1, column_3, column_2)
        thaphanoi(1, column_1, column_2, column_3)
        thaphanoi(no_discs - 1, column_3, column_2, column_1)

thaphanoi(no_discs, column_1, column_3, column_2)
print('Program ended')

I expect this code to print 7.

Body:
Tower of Hanoi problem can be solved with minimum of (2^n)-1 moves.

That is

No of move required for 1 disk -->  1
No of move required for 2 disks -->  3
No of move required for 3 disks -->  7
No of move required for 4 disks -->  15
No of move required for 5 disks -->  31
No of move required for 6 disks -->  63
No of move required for 7 disks -->  127
and so on..

So you can calculate number of movements required after getting the number of required.

like,

min_moves = math.pow(2, no_discs) - 1
if min_moves > 100:
  print("Too many moves")
  sys.exit()


问:
How to get pictures or inline shapes from clipboard right before pasting?
i've got a problem with my vba application.

I want to know if it's possible to detect and remove pictures from what I've copied in word right before pasting it in a richtextbox or ink-edit component?

My approach is :

I copy what I need in word (text, picture, etc.)

I paste it on my userform using the Ctrl+ V action

And at this point, I want to remove the picture from the clipboard but keep the text

Is this even possible? Thanks!

答:
Try:</p>

```<code>Public Declare Function OpenClipboard Lib "user32" (ByVal hwnd As
Long) As Long
Public Declare Function EmptyClipboard Lib "user32" () As Long
Public Declare Function CloseClipboard Lib "user32" () As Long

Sub EmptyClip()
OpenClipboard (0&)
EmptyClipboard
CloseClipboard
End Sub
</code>```

Body:
Try:

Public Declare Function OpenClipboard Lib "user32" (ByVal hwnd As
Long) As Long
Public Declare Function EmptyClipboard Lib "user32" () As Long
Public Declare Function CloseClipboard Lib "user32" () As Long

Sub EmptyClip()
OpenClipboard (0&)
EmptyClipboard
CloseClipboard
End Sub


问:
Is there a way to enable tor as system proxy settings through Python in Linux
I am working on a project which requires accessing some websites with and without tor enabled, and record the content differences.
I am working on deepin (which is a linux based debian distro), and using Python 2.7 to accomplish the task. The problem is that I have to manually enable/disable tor, and change the system proxy settings every time I run the script. Now, I am aware that I can issue a shell command from Python itself to enable tor (service tor start), but I cannot figure out how to enable/disable the system proxy settings from Python.

I have already tried this, but no luck.

答:
Got the thing working, posting here in case someone else has the same problem:

```<code>from selenium import webdriver
import stem.process
from stem import Signal
from stem.control import Controller
from splinter import Browser
proxyIP = "127.0.0.1"
proxyPort = 9050
proxy_settings = {"network.proxy.type":0,
    "network.proxy.socks": proxyIP,
    "network.proxy.socks_port": proxyPort
}
browser = Browser('firefox', profile_preferences=proxy_settings)
driver = browser.driver
driver.get('https://whatismyip.com')
</code>```

changing network.proxy.type to 1 resets the proxy settings. Solution found here

Body:
Got the thing working, posting here in case someone else has the same problem:

from selenium import webdriver
import stem.process
from stem import Signal
from stem.control import Controller
from splinter import Browser
proxyIP = "127.0.0.1"
proxyPort = 9050
proxy_settings = {"network.proxy.type":0,
    "network.proxy.socks": proxyIP,
    "network.proxy.socks_port": proxyPort
}
browser = Browser('firefox', profile_preferences=proxy_settings)
driver = browser.driver
driver.get('https://whatismyip.com')

changing network.proxy.type to 1 resets the proxy settings. Solution found here


问:
I can't load data from Database to display the results of the UIPickerView
I can't load data from Database to display the results of the UIPickerView. I test by fix array value UIPicker can load data in to pickerView  but when I use array load json UIPickerViewDataSource cannot load into picker view

can load

```<code>var team = ["Apple", "Banana", "Tomato", "Corn", "Bean", "Orange", "Mango", "Mangoteen"]
</code>```

canot load

```<code>var team: [AnyObject] = []
</code>```

```<code>import UIKit

class getAllTeamViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate, UITextFieldDelegate {

var selectValue: String?

@IBOutlet weak var showSelectValuePickerView: UITextField!

// Array
    //var team = ["Apple", "Banana", "Tomato", "Corn", "Bean", "Orange", "Mango", "Mangoteen"]
    var team: [AnyObject] = []

//Function getValue from database
func getvalue() -> Void {
    //get the values from sql/Json
    let url = NSURL(string: "http://www.test.com/myWebService/getteamPickView.php")

    let data = NSData(contentsOf: url! as URL)
    var jsonResponse = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
        jsonResponse = jsonResponse.reversed() as NSArray
        reloadInputViews()
        print("jsonResponse ==> \(jsonResponse)")

    for candidate in jsonResponse {
        if let cdict = candidate as? NSDictionary {
            //fullName is the column name in sql/json
            let names = cdict["NameTeam"]
            self.selectValue?.append(((names! as AnyObject) as! String))
            print("Names ==> \(String(describing: names))")
        }//if
    }//for
}//getvalue

//  Picker View Function
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return self.team.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    let titleRow = (team[row] )
    return titleRow as? String
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    if team.count > 0 && team.count >= row{
        self.showSelectValuePickerView.text = self.team[row] as? String
        self.showSelectValuePickerView.isHidden = true
    }
}
</code>```

}

答:
Sorry, this is really bad code. There are so many bad practices.

Don't declare an array as [AnyObject] if it's clearly [String].

This avoids horrible type cast like names! as AnyObject) as! String

Don't use NSData, NSURL, NSArray, NSDictionary in Swift. Use native types.

.mutableContainers is pointless in Swift, omit the entire parameter.

Never load data synchronously from a remote URL with Data(contentsOf.

Reload UI always on the main thread.

Handle all errors! At least print them.

The error occurs because you call reloadInputViews() – which I assume reloads the picker view – before populating the data source array.

And rather than populating the data source array team you append the strings to selectValue which makes no sense.

This is a slightly optimized version of your code

```<code>@IBOutlet weak var showSelectValuePickerView: UITextField!

var team = [String]()

//Function getValue from database
func getvalue() {
    //get the values from sql/Json
    let url = URL(string: "http://www.test.com/myWebService/getteamPickView.php")!
    let task = URLSession.shared.dataTask(with: url) { (data, _ , error) in
        if let error = error { print(error); return }
        do {
            if let jsonResponse = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
                self.team = jsonResponse.compactMap{ $0["NameTeam"] as? String }
                DispatchQueue.main.async {
                    self.reloadInputViews()
                }
            } else { print("JSON is not an array") }
        } catch { print(error) }
    }
    task.resume()
}

//  Picker View Function
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return self.team.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return team[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    self.showSelectValuePickerView.text = self.team[row]
    self.showSelectValuePickerView.isHidden = true // Are you serious ??? This hides the text field
}
</code>```

Body:
I can't load data from Database to display the results of the UIPickerView. I test by fix array value UIPicker can load data in to pickerView  but when I use array load json UIPickerViewDataSource cannot load into picker view

can load

var team = ["Apple", "Banana", "Tomato", "Corn", "Bean", "Orange", "Mango", "Mangoteen"]

canot load

var team: [AnyObject] = []

import UIKit

class getAllTeamViewController: UIViewController,UIPickerViewDataSource,UIPickerViewDelegate, UITextFieldDelegate {

var selectValue: String?

@IBOutlet weak var showSelectValuePickerView: UITextField!

// Array
    //var team = ["Apple", "Banana", "Tomato", "Corn", "Bean", "Orange", "Mango", "Mangoteen"]
    var team: [AnyObject] = []

//Function getValue from database
func getvalue() -> Void {
    //get the values from sql/Json
    let url = NSURL(string: "http://www.test.com/myWebService/getteamPickView.php")

    let data = NSData(contentsOf: url! as URL)
    var jsonResponse = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
        jsonResponse = jsonResponse.reversed() as NSArray
        reloadInputViews()
        print("jsonResponse ==> \(jsonResponse)")

    for candidate in jsonResponse {
        if let cdict = candidate as? NSDictionary {
            //fullName is the column name in sql/json
            let names = cdict["NameTeam"]
            self.selectValue?.append(((names! as AnyObject) as! String))
            print("Names ==> \(String(describing: names))")
        }//if
    }//for
}//getvalue

//  Picker View Function
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return self.team.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    let titleRow = (team[row] )
    return titleRow as? String
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    if team.count > 0 && team.count >= row{
        self.showSelectValuePickerView.text = self.team[row] as? String
        self.showSelectValuePickerView.isHidden = true
    }
}

}

Body:
Sorry, this is really bad code. There are so many bad practices.

Don't declare an array as [AnyObject] if it's clearly [String].

This avoids horrible type cast like names! as AnyObject) as! String

Don't use NSData, NSURL, NSArray, NSDictionary in Swift. Use native types.

.mutableContainers is pointless in Swift, omit the entire parameter.

Never load data synchronously from a remote URL with Data(contentsOf.

Reload UI always on the main thread.

Handle all errors! At least print them.

The error occurs because you call reloadInputViews() – which I assume reloads the picker view – before populating the data source array.

And rather than populating the data source array team you append the strings to selectValue which makes no sense.

This is a slightly optimized version of your code

@IBOutlet weak var showSelectValuePickerView: UITextField!

var team = [String]()

//Function getValue from database
func getvalue() {
    //get the values from sql/Json
    let url = URL(string: "http://www.test.com/myWebService/getteamPickView.php")!
    let task = URLSession.shared.dataTask(with: url) { (data, _ , error) in
        if let error = error { print(error); return }
        do {
            if let jsonResponse = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
                self.team = jsonResponse.compactMap{ $0["NameTeam"] as? String }
                DispatchQueue.main.async {
                    self.reloadInputViews()
                }
            } else { print("JSON is not an array") }
        } catch { print(error) }
    }
    task.resume()
}

//  Picker View Function
func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return self.team.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return team[row]
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    self.showSelectValuePickerView.text = self.team[row]
    self.showSelectValuePickerView.isHidden = true // Are you serious ??? This hides the text field
}


问:
How to extend HTMLButtonAttribute type in JSX
I'm creating a simple button component using StencilJS which uses JSX and TypeScript. The current stable version doesn't have a type for the attribute part. Basically I'm trying to do this:

```<code>render() {
   return <button part="live-chat-button">{this.getStartButtonText()} </button>;
}
</code>```

But Typescript errors with:

```<code>Type '{ part: string; }' is not assignable to type
'ButtonHTMLAttributes<HTMLButtonElement>'. Property
'part' does not exist on type 'ButtonHTMLAttributes<HTMLButtonElement>'.
</code>```

Apart from upgrading to the fixed alpha version, how can I fix this?

Thanks in advance for any help!

答:
You should be able to add attributes to any jsx element using module augmentation:

```<code>declare module '@stencil/core' {
  namespace JSXElements {
    interface ButtonHTMLAttributes<T> {
      part?: string
    }
  }
}
</code>```

This should work for button.

Body:
I'm creating a simple button component using StencilJS which uses JSX and TypeScript. The current stable version doesn't have a type for the attribute part. Basically I'm trying to do this:

render() {
   return <button part="live-chat-button">{this.getStartButtonText()} </button>;
}

But Typescript errors with:

Type '{ part: string; }' is not assignable to type
'ButtonHTMLAttributes<HTMLButtonElement>'. Property
'part' does not exist on type 'ButtonHTMLAttributes<HTMLButtonElement>'.

Apart from upgrading to the fixed alpha version, how can I fix this?

Thanks in advance for any help!

Body:
You should be able to add attributes to any jsx element using module augmentation:

declare module '@stencil/core' {
  namespace JSXElements {
    interface ButtonHTMLAttributes<T> {
      part?: string
    }
  }
}

This should work for button.


问:
how to add raft instead of kafka in hyperledger fabric?
How to add raft instead of kafka in hyperledger fabric altoros fabric-supply-chain project ?
    here's my configtxtemplate-OneOrg-orderer.yaml file

```<code>---
################################################################################
#
#   Profile
#
#   - Different configuration profiles may be encoded here to be specified
#   as parameters to the configtxgen tool
#
################################################################################
Profiles:

    OrdererGenesis:
        Orderer:
            <<: *OrdererDefaults
            Organizations:
                - *OrdererOrg
        Consortiums:
            SampleConsortium:
                Organizations:
                    - *ORG1
    common:
        Consortium: SampleConsortium
        Application:
            <<: *ApplicationDefaults
            Organizations:
                - *ORG1

    CHANNEL_NAME:
        Consortium: SampleConsortium
        Application:
            Organizations:
                - *ORG1

################################################################################
#
#   Section: Organizations
#
#   - This section defines the different organizational identities which will
#   be referenced later in the configuration.
#
################################################################################
Organizations:

    # SampleOrg defines an MSP using the sampleconfig.  It should never be used
    # in production but may be used as a template for other definitions
    - &OrdererOrg
        # DefaultOrg defines the organization which is used in the sampleconfig
        # of the fabric.git development environment
        Name: OrdererMSP

        # ID to load the MSP definition as
        ID: OrdererMSP

        # MSPDir is the filesystem path which contains the MSP configuration
        MSPDir: crypto-config/ordererOrganizations/DOMAIN/msp

    - &ORG1
        # DefaultOrg defines the organization which is used in the sampleconfig
        # of the fabric.git development environment
        Name: ORG1MSP

        # ID to load the MSP definition as
        ID: ORG1MSP

        MSPDir: crypto-config/peerOrganizations/ORG1.DOMAIN/msp

        AnchorPeers:
            # AnchorPeers defines the location of peers which can be used
            # for cross org gossip communication.  Note, this value is only
            # encoded in the genesis block in the Application section context
            - Host: peer0.ORG1.DOMAIN
              Port: 7051

################################################################################
#
#   SECTION: Orderer
#
#   - This section defines the values to encode into a config transaction or
#   genesis block for orderer related parameters
#
################################################################################
Orderer: &OrdererDefaults

    # Orderer Type: The orderer implementation to start
    # Available types are "solo" and "kafka"
    OrdererType: solo

    Addresses:
        - orderer.DOMAIN:7050

    # Batch Timeout: The amount of time to wait before creating a batch
    BatchTimeout: 2s

    # Batch Size: Controls the number of messages batched into a block
    BatchSize:

        # Max Message Count: The maximum number of messages to permit in a batch
        MaxMessageCount: 10

        # Absolute Max Bytes: The absolute maximum number of bytes allowed for
        # the serialized messages in a batch.
        AbsoluteMaxBytes: 98 MB

        # Preferred Max Bytes: The preferred maximum number of bytes allowed for
        # the serialized messages in a batch. A message larger than the preferred
        # max bytes will result in a batch larger than preferred max bytes.
        PreferredMaxBytes: 512 KB

    Kafka:
        # Brokers: A list of Kafka brokers to which the orderer connects
        # NOTE: Use IP:port notation
        Brokers:
            - 127.0.0.1:9092

    # Organizations is the list of orgs which are defined as participants on
    # the orderer side of the network
    Organizations:

################################################################################
#
#   SECTION: Application
#
#   - This section defines the values to encode into a config transaction or
#   genesis block for application related parameters
#
################################################################################
Application: &ApplicationDefaults

    # Organizations is the list of orgs which are defined as participants on
    # the application side of the network
    Organizations:
</code>```

Can you please check where I'm going wrong and in which files i have to make changes.
I went through the docs of raft but i couldn't understand it well and there is no good source or tutorial that i could go through. If you know any good source or example then please help.
I see the hyperledger fabric community is not as strong as bitcoin or ethereum like blockchains. I am facing lot of trouble to build an application on it. I would request you to help me from where i can learn the best.

答:
You can read in documentation for more details and explanations, while key concepts are:

In order to work with Raft you need to configure your ordering service to work with TLS.

Change orderer type to be

```<code>OrdererType: etcdraft
</code>```

You need to setup your concenters set (Raft replicas) by adding into configuration following section:

```<code>Consenters:

    - Host: raft0.example.com
      Port: 7050
      ClientTLSCert: path/to/ClientTLSCert0
      ServerTLSCert: path/to/ServerTLSCert0
    - Host: raft1.example.com
      Port: 7050
      ClientTLSCert: path/to/ClientTLSCert1
      ServerTLSCert: path/to/ServerTLSCert1
    - Host: raft2.example.com
      Port: 7050
      ClientTLSCert: path/to/ClientTLSCert2
      ServerTLSCert: path/to/ServerTLSCert2
</code>```

where you provide configuration to setup your cluster including TLS certificates for your concenters.

For example profile for Raft might look as following, SampleDevModeEtcdRaft profile:

```<code>SampleDevModeEtcdRaft:
  <<: *ChannelDefaults
Capabilities:
  <<: *ChannelCapabilities
  Orderer:
    <<: *OrdererDefaults
    OrdererType: etcdraft
    EtcdRaft:
    Consenters:
        - Host: raft0.example.com
          Port: 7050
          ClientTLSCert: path/to/ClientTLSCert0
          ServerTLSCert: path/to/ServerTLSCert0
        - Host: raft1.example.com
          Port: 7050
          ClientTLSCert: path/to/ClientTLSCert1
          ServerTLSCert: path/to/ServerTLSCert1
        - Host: raft2.example.com
          Port: 7050
          ClientTLSCert: path/to/ClientTLSCert2
          ServerTLSCert: path/to/ServerTLSCert2
  Organizations:
      - *OrdererOrg
    Capabilities:
      <<: *OrdererCapabilities
  Application:
    <<: *ApplicationDefaults
    Organizations:
    - <<: *OrdererOrg
  Consortiums:
    SampleConsortium:
      Organizations:
      - *Org1
      - *Org2
</code>```

Body:
How to add raft instead of kafka in hyperledger fabric altoros fabric-supply-chain project ?
    here's my configtxtemplate-OneOrg-orderer.yaml file

---
################################################################################
#
#   Profile
#
#   - Different configuration profiles may be encoded here to be specified
#   as parameters to the configtxgen tool
#
################################################################################
Profiles:

    OrdererGenesis:
        Orderer:
            <<: *OrdererDefaults
            Organizations:
                - *OrdererOrg
        Consortiums:
            SampleConsortium:
                Organizations:
                    - *ORG1
    common:
        Consortium: SampleConsortium
        Application:
            <<: *ApplicationDefaults
            Organizations:
                - *ORG1

    CHANNEL_NAME:
        Consortium: SampleConsortium
        Application:
            Organizations:
                - *ORG1

################################################################################
#
#   Section: Organizations
#
#   - This section defines the different organizational identities which will
#   be referenced later in the configuration.
#
################################################################################
Organizations:

    # SampleOrg defines an MSP using the sampleconfig.  It should never be used
    # in production but may be used as a template for other definitions
    - &OrdererOrg
        # DefaultOrg defines the organization which is used in the sampleconfig
        # of the fabric.git development environment
        Name: OrdererMSP

        # ID to load the MSP definition as
        ID: OrdererMSP

        # MSPDir is the filesystem path which contains the MSP configuration
        MSPDir: crypto-config/ordererOrganizations/DOMAIN/msp

    - &ORG1
        # DefaultOrg defines the organization which is used in the sampleconfig
        # of the fabric.git development environment
        Name: ORG1MSP

        # ID to load the MSP definition as
        ID: ORG1MSP

        MSPDir: crypto-config/peerOrganizations/ORG1.DOMAIN/msp

        AnchorPeers:
            # AnchorPeers defines the location of peers which can be used
            # for cross org gossip communication.  Note, this value is only
            # encoded in the genesis block in the Application section context
            - Host: peer0.ORG1.DOMAIN
              Port: 7051

################################################################################
#
#   SECTION: Orderer
#
#   - This section defines the values to encode into a config transaction or
#   genesis block for orderer related parameters
#
################################################################################
Orderer: &OrdererDefaults

    # Orderer Type: The orderer implementation to start
    # Available types are "solo" and "kafka"
    OrdererType: solo

    Addresses:
        - orderer.DOMAIN:7050

    # Batch Timeout: The amount of time to wait before creating a batch
    BatchTimeout: 2s

    # Batch Size: Controls the number of messages batched into a block
    BatchSize:

        # Max Message Count: The maximum number of messages to permit in a batch
        MaxMessageCount: 10

        # Absolute Max Bytes: The absolute maximum number of bytes allowed for
        # the serialized messages in a batch.
        AbsoluteMaxBytes: 98 MB

        # Preferred Max Bytes: The preferred maximum number of bytes allowed for
        # the serialized messages in a batch. A message larger than the preferred
        # max bytes will result in a batch larger than preferred max bytes.
        PreferredMaxBytes: 512 KB

    Kafka:
        # Brokers: A list of Kafka brokers to which the orderer connects
        # NOTE: Use IP:port notation
        Brokers:
            - 127.0.0.1:9092

    # Organizations is the list of orgs which are defined as participants on
    # the orderer side of the network
    Organizations:

################################################################################
#
#   SECTION: Application
#
#   - This section defines the values to encode into a config transaction or
#   genesis block for application related parameters
#
################################################################################
Application: &ApplicationDefaults

    # Organizations is the list of orgs which are defined as participants on
    # the application side of the network
    Organizations:

Can you please check where I'm going wrong and in which files i have to make changes.
I went through the docs of raft but i couldn't understand it well and there is no good source or tutorial that i could go through. If you know any good source or example then please help.
I see the hyperledger fabric community is not as strong as bitcoin or ethereum like blockchains. I am facing lot of trouble to build an application on it. I would request you to help me from where i can learn the best.

Body:
You can read in documentation for more details and explanations, while key concepts are:

In order to work with Raft you need to configure your ordering service to work with TLS.

Change orderer type to be

OrdererType: etcdraft

You need to setup your concenters set (Raft replicas) by adding into configuration following section:

Consenters:

    - Host: raft0.example.com
      Port: 7050
      ClientTLSCert: path/to/ClientTLSCert0
      ServerTLSCert: path/to/ServerTLSCert0
    - Host: raft1.example.com
      Port: 7050
      ClientTLSCert: path/to/ClientTLSCert1
      ServerTLSCert: path/to/ServerTLSCert1
    - Host: raft2.example.com
      Port: 7050
      ClientTLSCert: path/to/ClientTLSCert2
      ServerTLSCert: path/to/ServerTLSCert2

where you provide configuration to setup your cluster including TLS certificates for your concenters.

For example profile for Raft might look as following, SampleDevModeEtcdRaft profile:

SampleDevModeEtcdRaft:
  <<: *ChannelDefaults
Capabilities:
  <<: *ChannelCapabilities
  Orderer:
    <<: *OrdererDefaults
    OrdererType: etcdraft
    EtcdRaft:
    Consenters:
        - Host: raft0.example.com
          Port: 7050
          ClientTLSCert: path/to/ClientTLSCert0
          ServerTLSCert: path/to/ServerTLSCert0
        - Host: raft1.example.com
          Port: 7050
          ClientTLSCert: path/to/ClientTLSCert1
          ServerTLSCert: path/to/ServerTLSCert1
        - Host: raft2.example.com
          Port: 7050
          ClientTLSCert: path/to/ClientTLSCert2
          ServerTLSCert: path/to/ServerTLSCert2
  Organizations:
      - *OrdererOrg
    Capabilities:
      <<: *OrdererCapabilities
  Application:
    <<: *ApplicationDefaults
    Organizations:
    - <<: *OrdererOrg
  Consortiums:
    SampleConsortium:
      Organizations:
      - *Org1
      - *Org2


问:
svn: external failed directory error Can't obtain lock on non-directory 'directory'
I have just loaded some old files and directories of an old project onto my PC from SVN to debug an issue.

I am getting the following when trying to update the working directory:

```<code>external failed directory error Can't obtain lock on non-directory 'directory'
</code>```

I have tried svn cleanup as suggested by some posts but to no avail.

Anyone got any pointers as to how I might resolve this?

答: I solved the error by not creating the directory which the external references before I perform SVN Update.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have just loaded some old files and directories of an old project onto my PC from SVN to debug an issue.

I am getting the following when trying to update the working directory:

external failed directory error Can't obtain lock on non-directory 'directory'

I have tried svn cleanup as suggested by some posts but to no avail.

Anyone got any pointers as to how I might resolve this?


问:
unable to install php 7.2 in my ubuntu 14.04 repo error occred
I am unable to install php 7.2 on my Ubuntu 14.04</p>

```<code>root@OD033:/etc/php# sudo apt-get install php7.2
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package php7.2
E: Couldn't find any package by regex 'php7.2'
root@OD033:/etc/php#
</code>```

答:
Do not add version, simply run sudo apt install php it would install latest. if you want add versions in apt install do as below

```<code>sudo add-apt-repository ppa:ondrej/php
sudo apt update
</code>```

then you will be able to install whatever version you need to.

Body:
I am unable to install php 7.2 on my Ubuntu 14.04

root@OD033:/etc/php# sudo apt-get install php7.2
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package php7.2
E: Couldn't find any package by regex 'php7.2'
root@OD033:/etc/php#

Body:
Do not add version, simply run sudo apt install php it would install latest. if you want add versions in apt install do as below

sudo add-apt-repository ppa:ondrej/php
sudo apt update

then you will be able to install whatever version you need to.


问:
What is a good algorithm for mapping random (barcode values) numbers to an String in a collection?
Say that my application has a finite number of "stuff", in my case they will be items in my game but for the purposes of this question I'll use Strings.

Say I have 5 Strings :

James

Dave

John

Steve

Jack

There will be a set list of them, however I will increase that list in the future.

Question : What is a good algorithm I can use, to go from a random number (generated from a barcode) into one of those values from above?

For example, if I have the value 4523542354254, then what algorithm could I use to map that onto Dave? If I have that same number again, I need to make sure it maps to Dave and not to something else each time.

One option I did consider was taking the last digit of the barcode and using the 0-9 that would map onto 10 items, but its not very future proof if I added an 11th item.

Any suggestions?

答:
With the clarification that "If I have that same number again, I need to make sure it maps to Dave and not to something else each time." only applies as long as the set of strings doesn't change.

Simplest is what Maverik says, name = names[barcode % names.length];

A Java long is big enough to store any UPC barcode, int isn't, so I assume here barcode is a long. Note that the last digit of a UPC barcode is base-11, it can be X. I leave it as an exercise for the reader how you actually map barcodes to numbers. One option is just discard the check digit once you've established that it's correct - it's computed from the others, so it doesn't add any information or discriminate between any otherwise-equal codes.

But as Stephen C says, barcodes aren't random, so this might not give you a uniform distribution across the names.

To get a better distribution, you could first hash the barcode. For example name = names[String.valueOf(barcode).hashCode() % names.length];

This still might not be entirely uniform -- there are better but usually slower hash functions than String.hashCode -- but it probably avoids any major biases that there may be in real-life barcodes.

Also, I can't remember whether the Java modulus operator returns negative results for negative input - if so then you need to coerce it into a positive range:

```<code>int idx = String.valueOf(barcode).hashCode() % names.length;
if (idx < 0) idx += names.length;
</code>```

Body:
With the clarification that "If I have that same number again, I need to make sure it maps to Dave and not to something else each time." only applies as long as the set of strings doesn't change.

Simplest is what Maverik says, name = names[barcode % names.length];

A Java long is big enough to store any UPC barcode, int isn't, so I assume here barcode is a long. Note that the last digit of a UPC barcode is base-11, it can be X. I leave it as an exercise for the reader how you actually map barcodes to numbers. One option is just discard the check digit once you've established that it's correct - it's computed from the others, so it doesn't add any information or discriminate between any otherwise-equal codes.

But as Stephen C says, barcodes aren't random, so this might not give you a uniform distribution across the names.

To get a better distribution, you could first hash the barcode. For example name = names[String.valueOf(barcode).hashCode() % names.length];

This still might not be entirely uniform -- there are better but usually slower hash functions than String.hashCode -- but it probably avoids any major biases that there may be in real-life barcodes.

Also, I can't remember whether the Java modulus operator returns negative results for negative input - if so then you need to coerce it into a positive range:

int idx = String.valueOf(barcode).hashCode() % names.length;
if (idx < 0) idx += names.length;


问:
PHPmyadmin pop-up error notice keeps appearing when clicking on columns of databases
I keep receiving a pop-up error, when clicking on columns in databases:

Some errors have been detected on the server, please look at the
  bottom of this window.

Notice in .\libraries\tbl_columns_definition_form.inc.php#55 Undefined
  variable: server

Backtrace

.\libraries\structure.lib.php#2433:
  include(.\libraries\tbl_columns_definition_form.inc.php)
  .\tbl_structure.php#45: PMA_displayHtmlForColumnChange( string
  'registration', string 'users', NULL, string 'tbl_structure.php', )

How to solve this matter?

答:
if exists then update other wise add this line in  /etc/phpmyadmin/config.inc.php file

```<code>$cfg['SendErrorReports'] = 'never';
</code>```

Body:
if exists then update other wise add this line in  /etc/phpmyadmin/config.inc.php file

$cfg['SendErrorReports'] = 'never';


问:
How to manipulate the values of Hashtable for just specific key in powershell?
I might need a second set of ideas here.

This is what 'd to achieve:
I need to perform a task in a Hashtable (Powershell) to each value of a particular Key

I am scripting a portion of enabling a dfsr replication and I am stuck because

the follow command  needs to be executed:

New-DfsReplicationGroup -GroupName "" | New-DfsReplicatedFolder -FolderName "" | Add-DfsrMember -ComputerName Server1,Server2

If I run the command it self on a powershell terminal works without any problem.

On a Hashtable I already have the follow:

Content of Grouping  servers list

Name                           Value

----                           -----

Group Name1         {Server1, Server2}

Group Name2         {Server6, Server9}

Which now has to be easier right?
Thinking as Array:

```<code>Write-Verbose "Configuring a full-DFSr connection "
       for ($i = 0 ; $i -lt $server_list.Count ; $i++)
       {
           for ($j = $i + 1 ; $j -lt $server_list.Count ; $j++)
            {
              Write-Verbose ("Adding bidirectional connections between the member computers named {0} and {1}" -f $server_list[$i],$server_list[$j])
                 $dfs_connection_status = Add-DfsrConnection -GroupName $GroupName -SourceComputerName $server_list[$i] -DestinationComputerName $server_list[$j]
                  Write-Output $dfs_connection_status
            }

       }
</code>```

However I can't figure it out how to manipulate the content once the key is found

Then I took a break from that script portion and decided to break it down a simple a+b

Take a look on the follow:

where $($key.Name) has
the key value:d and the Value content is:1,4,5

lines as follow

```<code>$num = @{a= "Test"
         b= "Test2"
         c= "Test3"
         }

$num.d = @() #adds to an array
$num.d+= '1'
$num.d+= '4'
$num.d+= '5'

$result= $num[0]+$num[1] or if decided $result= $num[0]+$num[2]
</code>```

result should be '5' or  '6' if (1+5)

```<code> $num.GetEnumerator() | Sort-Object -Property Value | Where-Object {$_.Key}
</code>```

Name                           Value

----                           -----

d                              {1, 4, 5}

a                              Test

b                              Test2

c                              Test3

```<code>   #$sum+= $num.ContainsKey("d")+$num.ContainsKey("d")+1
   $num.GetEnumerator() | Sort-Object -Property Value | Where-Object {$_.Key}
      if ($num.ContainsKey("d")) { $num['d'] }
</code>```

if the d key is found then manipulate the value content as needed . Thinking on my original script for dfsr would be once the group name is found enable the bidirectional replication Server1  -> Server2  and Server2 -> Server1

I could not make it to work so I decided to create a new array (probably is not really needed) what I was thinking okay so you found the d key now lets move all the content to a new array so we can manipulate it.

$vm_list+= $num.Values | Where-Object {$num.ContainsKey("d")} | % ToString

Write-Host "nnt VM_list:t" $($vm_list)

Hope you guys can help

Any idea would it be more than appreciated.

答:
So  I found the answer , can't believe it was that easy maybe was loosing my mind.

I am sharing a possible solution to the community ;)

"there is always a multiple ways to get to a place so this could
be one;)"

```<code>  $script:vmlist = @{}     #Hashtable
    $vm_list = @()           #Array

    $vmlist.d = @()
    $vmlist.d+= 'Server1'
    $vmlist.d+= 'Server2'

    if ($vmlist.ContainsKey("d"))  #Looking for a particular Key
{
$vmlist['d']
    $vm_list+= $vmlist['d']
    Write-Host "`n`n`t VM_list:`t`t $($vm_list)`n`n$($vm_list[0])`n$($vm_list[1])`n$($vm_list[2])"
    Test-Connection $vm_list[0+1]
}
     else {Write-Host "Value not found"}
</code>```

Printing the content of Hashtable

```<code>VM_list:  Server1 Server2
</code>```

Printing the content of the new Array , noted that it will contain the values from the Key d

```<code>VM_list[0]:Server1
VM_list[1]:Server2
</code>```

result:

Source        Destination     IPV4Address      IPV6Address     Bytes    Time(ms)
------        -----------     -----------      -----------     -----    --------
Server source  Server2      10.114.x.y                          32       0

Server source  Server2      10.114.x.y                          32       0

Server source  Server2      10.114.x.y                          32       0

Server source  Server2      10.114.x.y                          32       0

Hope you guys can use it

Regards
JCayetano

Body:
I might need a second set of ideas here.

This is what 'd to achieve:
I need to perform a task in a Hashtable (Powershell) to each value of a particular Key

I am scripting a portion of enabling a dfsr replication and I am stuck because

the follow command  needs to be executed:

New-DfsReplicationGroup -GroupName "" | New-DfsReplicatedFolder -FolderName "" | Add-DfsrMember -ComputerName Server1,Server2

If I run the command it self on a powershell terminal works without any problem.

On a Hashtable I already have the follow:

Content of Grouping  servers list

Name                           Value

----                           -----

Group Name1         {Server1, Server2}

Group Name2         {Server6, Server9}

Which now has to be easier right?
Thinking as Array:

Write-Verbose "Configuring a full-DFSr connection "
       for ($i = 0 ; $i -lt $server_list.Count ; $i++)
       {
           for ($j = $i + 1 ; $j -lt $server_list.Count ; $j++)
            {
              Write-Verbose ("Adding bidirectional connections between the member computers named {0} and {1}" -f $server_list[$i],$server_list[$j])
                 $dfs_connection_status = Add-DfsrConnection -GroupName $GroupName -SourceComputerName $server_list[$i] -DestinationComputerName $server_list[$j]
                  Write-Output $dfs_connection_status
            }

       }

However I can't figure it out how to manipulate the content once the key is found

Then I took a break from that script portion and decided to break it down a simple a+b

Take a look on the follow:

where $($key.Name) has
the key value:d and the Value content is:1,4,5

lines as follow

$num = @{a= "Test"
         b= "Test2"
         c= "Test3"
         }

$num.d = @() #adds to an array
$num.d+= '1'
$num.d+= '4'
$num.d+= '5'

$result= $num[0]+$num[1] or if decided $result= $num[0]+$num[2]

result should be '5' or  '6' if (1+5)

 $num.GetEnumerator() | Sort-Object -Property Value | Where-Object {$_.Key}

Name                           Value

----                           -----

d                              {1, 4, 5}

a                              Test

b                              Test2

c                              Test3

   #$sum+= $num.ContainsKey("d")+$num.ContainsKey("d")+1
   $num.GetEnumerator() | Sort-Object -Property Value | Where-Object {$_.Key}
      if ($num.ContainsKey("d")) { $num['d'] }

if the d key is found then manipulate the value content as needed . Thinking on my original script for dfsr would be once the group name is found enable the bidirectional replication Server1  -> Server2  and Server2 -> Server1

I could not make it to work so I decided to create a new array (probably is not really needed) what I was thinking okay so you found the d key now lets move all the content to a new array so we can manipulate it.

$vm_list+= $num.Values | Where-Object {$num.ContainsKey("d")} | % ToString

Write-Host "nnt VM_list:t" $($vm_list)

Hope you guys can help

Any idea would it be more than appreciated.

Body:
So  I found the answer , can't believe it was that easy maybe was loosing my mind.

I am sharing a possible solution to the community ;)

"there is always a multiple ways to get to a place so this could
be one;)"

  $script:vmlist = @{}     #Hashtable
    $vm_list = @()           #Array

    $vmlist.d = @()
    $vmlist.d+= 'Server1'
    $vmlist.d+= 'Server2'

    if ($vmlist.ContainsKey("d"))  #Looking for a particular Key
{
$vmlist['d']
    $vm_list+= $vmlist['d']
    Write-Host "`n`n`t VM_list:`t`t $($vm_list)`n`n$($vm_list[0])`n$($vm_list[1])`n$($vm_list[2])"
    Test-Connection $vm_list[0+1]
}
     else {Write-Host "Value not found"}

Printing the content of Hashtable

VM_list:  Server1 Server2

Printing the content of the new Array , noted that it will contain the values from the Key d

VM_list[0]:Server1
VM_list[1]:Server2

result:

Source        Destination     IPV4Address      IPV6Address     Bytes    Time(ms)
------        -----------     -----------      -----------     -----    --------
Server source  Server2      10.114.x.y                          32       0

Server source  Server2      10.114.x.y                          32       0

Server source  Server2      10.114.x.y                          32       0

Server source  Server2      10.114.x.y                          32       0

Hope you guys can use it

Regards
JCayetano


问:
Is GPS activated - Flutter
Is there a way to find out in Flutter if the GPS is activated or deactivated?
I use the plugin location however there I get only the location and not the state of the GPS.</p>

答:
Using the latest version of Geolocator 5.0

```<code>var isGpsEnabled = await Geolocator().isLocationServiceEnabled();
</code>```

I use this method to check and enable the Gps if disabled.

```<code>  Future _checkGps() async {
    if (!(await Geolocator().isLocationServiceEnabled())) {
      if (Theme.of(context).platform == TargetPlatform.android) {
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("Can't get gurrent location"),
              content:
                  const Text('Please make sure you enable GPS and try again'),
              actions: <Widget>[
                FlatButton(
                  child: Text('Ok'),
                  onPressed: () {
                    final AndroidIntent intent = AndroidIntent(
                        action: 'android.settings.LOCATION_SOURCE_SETTINGS');

                    intent.launch();
                    Navigator.of(context, rootNavigator: true).pop();
                  },
                ),
              ],
            );
          },
        );
      }
    }
  }
</code>```

Title: Is GPS activated - Flutter

Body:
Using the latest version of Geolocator 5.0

var isGpsEnabled = await Geolocator().isLocationServiceEnabled();

I use this method to check and enable the Gps if disabled.

  Future _checkGps() async {
    if (!(await Geolocator().isLocationServiceEnabled())) {
      if (Theme.of(context).platform == TargetPlatform.android) {
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text("Can't get gurrent location"),
              content:
                  const Text('Please make sure you enable GPS and try again'),
              actions: <Widget>[
                FlatButton(
                  child: Text('Ok'),
                  onPressed: () {
                    final AndroidIntent intent = AndroidIntent(
                        action: 'android.settings.LOCATION_SOURCE_SETTINGS');

                    intent.launch();
                    Navigator.of(context, rootNavigator: true).pop();
                  },
                ),
              ],
            );
          },
        );
      }
    }
  }


问:
App name is show in Transparent Activity
Actually i am creating transparent overlay Application but when the the activity starts the application name is showing in the middle of screen rest everything is working fine...
So how can i remove the application name

Check Screnshot : the Screenhot text is the Application Name

Manifest file Code :

```<code><activity
        android:name=".activity.ServiceManagement"
        android:theme="@style/Theme.Transparent"></activity>
</code>```

Style sheet :

```<code><style name="Theme.Transparent" parent="AppTheme">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:backgroundDimEnabled">false</item>
</code>```

答:
If your transparent activity is an AppCompatActivity, then use Theme.AppCompat.NoActionBar as its parent theme. Directly adding these attributes to your activity's theme will also work.

```<code><!-- no 'android:' prefix -->
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</code>```

Body:
Actually i am creating transparent overlay Application but when the the activity starts the application name is showing in the middle of screen rest everything is working fine...
So how can i remove the application name

Check Screnshot : the Screenhot text is the Application Name

Manifest file Code :

<activity
        android:name=".activity.ServiceManagement"
        android:theme="@style/Theme.Transparent"></activity>

Style sheet :

Body:
If your transparent activity is an AppCompatActivity, then use Theme.AppCompat.NoActionBar as its parent theme. Directly adding these attributes to your activity's theme will also work.

<!-- no 'android:' prefix -->
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>


问:
Lucky Tickets (count an amount of lucky numbers, having the specified sum of ALL digits)
Here is the problem

You are given a number 1 ≤ N ≤ 50. Every ticket has its 2N-digit number. We call a ticket lucky, if the sum of its first N digits is equal to the sum of its last N digits. You are also given the sum of ALL digits in the number. Your task is to count an amount of lucky numbers, having the specified sum of ALL digits.

For input 2 2 output is 4 (0101, 0110, 1001, 1010)

Can you help me to solve this problem? What is the minimum complexity ?

答:
```<code>private static boolean isLucky(int n) {

    int sum1 = 0;
    int sum2 =0;
    String s = String.valueOf(n);
    System.out.println("After Conversion in String= " + s);
    for (int i = 0; i < (s.length()) / 2; i++) {
        System.out.println("half string === " + s.charAt(i));
        sum1 = sum1 + Character.getNumericValue(s.charAt(i));
    }
    System.out.println("half sum === " + sum1);
    for(int j=(s.length()) / 2 ; j< s.length();j++){
        System.out.println("half string === " + s.charAt(j));
        sum2 = sum2 + Character.getNumericValue(s.charAt(j));
    }
    System.out.println("another half sum === " + sum2);
    if(sum1 == sum2){
        return true;
    }
    return false;
}
</code>```

ContentLicense: CC BY-SA 2.5


问:
jQuery drag and drop - how to get at element being dragged
I am using the jQuery library to implement drag and drop.

How do I get at the element that is being dragged when it is dropped?

I want to get the id of the image inside the div. The following element is dragged:

```<code><div class="block">
    <asp:Image ID="Image9" AlternateText="10/12/2008 - Retina" Width=81 Height=84 ImageUrl="~/uploads/ImageModifier/retina.jpg" runat=server />
</div>
</code>```

I have the standard dropped function from their example:

```<code>$(".drop").droppable({
                 accept: ".block",
                 activeClass: 'droppable-active',
                 hoverClass: 'droppable-hover',
                 drop: function(ev, ui) { }
});
</code>```

I have tried various ui.id etc. which doesn't seem to work.

答:
The ui.draggable() does not seem to work any more. To get the id one can use</p>

```<code>$(event.target).attr("id");
</code>```

OwnerDisplayName: alexmac

Body:
I am using the jQuery library to implement drag and drop.

How do I get at the element that is being dragged when it is dropped?

I want to get the id of the image inside the div. The following element is dragged:

    <asp:Image ID="Image9" AlternateText="10/12/2008 - Retina" Width=81 Height=84 ImageUrl="~/uploads/ImageModifier/retina.jpg" runat=server />

I have the standard dropped function from their example:

$(".drop").droppable({
                 accept: ".block",
                 activeClass: 'droppable-active',
                 hoverClass: 'droppable-hover',
                 drop: function(ev, ui) { }
});

I have tried various ui.id etc. which doesn't seem to work.

LastEditorDisplayName: Adam Bellaire

Body:
The ui.draggable() does not seem to work any more. To get the id one can use

$(event.target).attr("id");


问:
Python code to read CSV file based on user input
I have two separate CSV files that I need to have imported and read based on user input. We'll call the two files test1.csv and test2.csv. The user will be prompted to input if they want test1 or test2.

After inputting which CSV file they want, the user will be prompted a few other questions to select which rows of data they need. My CSV file data looks like this:

```<code>     Column A, Column B, Column C, Column D`
     Row 1, 1, 2, 3
     Row 2, 4, 5, 6
</code>```

If the user inputs Row 2, I'd like to return Columns B, C, and D as the result.

I'm new to python and unsure the coding to print the correct rows based off user input. I'm also unsure how to pick which CSV file gets pulled based on input.

As a work around, I wrote all the CSV data out in if/else statements within the code, but would prefer to keep the data in CSV format.

```<code>    'vehicle = input('Enter CSV File:')
         if vehicle == 'Test2':
         print ("Row Titles")
         print ("1.Row 1")
         print ("2.Row 2")
         choice = input('Row #:')
         Column B= '1'if choice == '1' else '2' if choice == '2' else
</code>```

0'
             Column C= '2' if choice == '1' else '5' if choice == '2' else '0'
             Column D= '3' if choice == '1' else '6' if choice == '2' else '0'

```<code>        print (column b+ column c+ column D)
</code>```

elif vehicle == "Test2":

repeat code above with options for CSV Test2 file

else: print ('invalid input')'

答:
In terms of picking the csv, just have that be a prompt and place it in the file string.

fileinput = str(input("Which file do you want?"))
if not ".csv" in fileinput:
  fileinput += ".csv"
```

<p>You'll want to import it as a pandas dataframe so you can easily call rows and columns.</p>

<pre class="lang-py prettyprint-override"><code>import pandas as pd
data = pd.read_csv(fileinput)
</code>```

Then you can use iloc to return a row or column in the dataframe.

rowcol = input("Column or row?")
if rowcol == "column":
  column = int(input("Which column?"))
  result = data.iloc([column])
elif rowcol == "row":
  row = int(input("Which row?"))
  result = data.iloc[[row]]
else:
  print("Invalid response.")

print(result)
```

Body:
I have two separate CSV files that I need to have imported and read based on user input. We'll call the two files test1.csv and test2.csv. The user will be prompted to input if they want test1 or test2.

After inputting which CSV file they want, the user will be prompted a few other questions to select which rows of data they need. My CSV file data looks like this:

     Column A, Column B, Column C, Column D`
     Row 1, 1, 2, 3
     Row 2, 4, 5, 6

If the user inputs Row 2, I'd like to return Columns B, C, and D as the result.

I'm new to python and unsure the coding to print the correct rows based off user input. I'm also unsure how to pick which CSV file gets pulled based on input.

As a work around, I wrote all the CSV data out in if/else statements within the code, but would prefer to keep the data in CSV format.

    'vehicle = input('Enter CSV File:')
         if vehicle == 'Test2':
         print ("Row Titles")
         print ("1.Row 1")
         print ("2.Row 2")
         choice = input('Row #:')
         Column B= '1'if choice == '1' else '2' if choice == '2' else

0'
             Column C= '2' if choice == '1' else '5' if choice == '2' else '0'
             Column D= '3' if choice == '1' else '6' if choice == '2' else '0'

        print (column b+ column c+ column D)

elif vehicle == "Test2":

repeat code above with options for CSV Test2 file

else: print ('invalid input')'

Body:
In terms of picking the csv, just have that be a prompt and place it in the file string.

fileinput = str(input("Which file do you want?"))
if not ".csv" in fileinput:
  fileinput += ".csv"

You'll want to import it as a pandas dataframe so you can easily call rows and columns.

import pandas as pd
data = pd.read_csv(fileinput)

Then you can use iloc to return a row or column in the dataframe.

rowcol = input("Column or row?")
if rowcol == "column":
  column = int(input("Which column?"))
  result = data.iloc([column])
elif rowcol == "row":
  row = int(input("Which row?"))
  result = data.iloc[[row]]
else:
  print("Invalid response.")

print(result)


问:
Firebase create user with email and password and put data in database
I want to create users with the function createUserWithEmailAndPassword and then put the data of that user into my database but it doesn't work.. the user is added to my authentication tab in firebase but not in my database. I also don't get an error.</p>

```<code>registerUser.addEventListener('click', function (user) {
    event.preventDefault();
    closeRegisterForm();

    email = registerEmail.value;
    password = registerPassword.value;

    firebase.auth().createUserWithEmailAndPassword(email, password)
        .then(function (event) {
            var ref = firebase.database().ref("users").child(user.uid).set({
                email: user.email,
                uid: user.uid
            });
        })
        .catch(function (error) {
            var errorCode = error.code;
            var errorMessage = error.message;
        });
});
</code>```

答:
Working for me:</p>

```<code>        const val = this.signupForm.value;
        this.authService.doRegister(val)
            .then(res => {
                this.msg = 'You have registered successfully!';
                this.msgType = 'success';
                this.authService.updateUser(val.name, null)
                    .then(suc => {
                        const created = firebase.firestore.FieldValue.serverTimestamp();
                        const user = {
                            first_name: val.name,
                            last_name: '',
                            email_personal: val.email,
                            created: created,
                            updated: created
                        };
                        this.userCollection = this.afs.collection<User>('users');
                        this.userCollection.doc(suc).set(user);
                    }, err => {
                        // console.log(err);
                    });
                this.router.navigate(['/']);
            }, err => {
                this.msg = err.message;
            })
</code>```

Body:
I want to create users with the function createUserWithEmailAndPassword and then put the data of that user into my database but it doesn't work.. the user is added to my authentication tab in firebase but not in my database. I also don't get an error.

registerUser.addEventListener('click', function (user) {
    event.preventDefault();
    closeRegisterForm();

    email = registerEmail.value;
    password = registerPassword.value;

    firebase.auth().createUserWithEmailAndPassword(email, password)
        .then(function (event) {
            var ref = firebase.database().ref("users").child(user.uid).set({
                email: user.email,
                uid: user.uid
            });
        })
        .catch(function (error) {
            var errorCode = error.code;
            var errorMessage = error.message;
        });
});

Body:
Working for me:

        const val = this.signupForm.value;
        this.authService.doRegister(val)
            .then(res => {
                this.msg = 'You have registered successfully!';
                this.msgType = 'success';
                this.authService.updateUser(val.name, null)
                    .then(suc => {
                        const created = firebase.firestore.FieldValue.serverTimestamp();
                        const user = {
                            first_name: val.name,
                            last_name: '',
                            email_personal: val.email,
                            created: created,
                            updated: created
                        };
                        this.userCollection = this.afs.collection<User>('users');
                        this.userCollection.doc(suc).set(user);
                    }, err => {
                        // console.log(err);
                    });
                this.router.navigate(['/']);
            }, err => {
                this.msg = err.message;
            })


问:
How to properly highlight text in React Native?
I would like to highlight a multiline text in a React Native app by changing the text's background color. The problem is that the background color changes in the whole text area, not just under the words.

```<code>class Example extends Component {
  render() {
    const text = '...';

    return (
      <View style={styles.textContainer}>
        <Text style={styles.textStyle}>
          {text}
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  textContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    width: 200,
  },
  textStyle: {
    backgroundColor: 'red',
  },
});
</code>```

The code above results in something that looks like this:

But I would like it to look like this:

I can get that result by splitting the text and adding the background color to the individual words:

```<code>class Example extends Component {
  render() {
    const text = '...';

    const brokenText = text.split(' ').map(word => (
      <Text style={styles.textStyle}>{word} </Text>
    ));

    return (
      <View style={styles.textContainer}>
        {brokenText}
      </View>
    );
  }
}
</code>```

But splitting the text into individual words doesn't seem like the best solution, and has a huge performance cost. Is there any cleaner way to do it?

答:
This is still not proper but I had it rendering as you expect by adding an invisible character (no-width space here) between each word, so the text breaks on it which has no background color. Here is the code :

```<code>const NO_WIDTH_SPACE = ''; // This is a special char you should copy and paste, not an empty string!

const Example = () => {
  const highlight = string =>
    string.split(' ').map((word, i) => (
      <Text key={i}>
        <Text style={styles.highlighted}>{word} </Text>
        {NO_WIDTH_SPACE}
      </Text>
    ));

  return (
    <Text>
      Some regular text {highlight('with some properly highlighted text')}
    </Text>
  );
}

const styles = StyleSheet.create({
  highlighted: {
    backgroundColor: 'yellow',
  },
});
</code>```

Here is a Snack where you can see the result and play with it : https://snack.expo.io/@adesurirey/properly-highlight-text-with-react-native

It can surely be improved, I'll be happy to have feedback.

Body:
I would like to highlight a multiline text in a React Native app by changing the text's background color. The problem is that the background color changes in the whole text area, not just under the words.

class Example extends Component {
  render() {
    const text = '...';

    return (
      <View style={styles.textContainer}>
        <Text style={styles.textStyle}>
          {text}
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  textContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    width: 200,
  },
  textStyle: {
    backgroundColor: 'red',
  },
});

The code above results in something that looks like this:

But I would like it to look like this:

I can get that result by splitting the text and adding the background color to the individual words:

class Example extends Component {
  render() {
    const text = '...';

    const brokenText = text.split(' ').map(word => (
      <Text style={styles.textStyle}>{word} </Text>
    ));

    return (
      <View style={styles.textContainer}>
        {brokenText}
      </View>
    );
  }
}

But splitting the text into individual words doesn't seem like the best solution, and has a huge performance cost. Is there any cleaner way to do it?

Body:
This is still not proper but I had it rendering as you expect by adding an invisible character (no-width space here) between each word, so the text breaks on it which has no background color. Here is the code :

const NO_WIDTH_SPACE = ''; // This is a special char you should copy and paste, not an empty string!

const Example = () => {
  const highlight = string =>
    string.split(' ').map((word, i) => (
      <Text key={i}>
        <Text style={styles.highlighted}>{word} </Text>
        {NO_WIDTH_SPACE}
      </Text>
    ));

  return (
    <Text>
      Some regular text {highlight('with some properly highlighted text')}
    </Text>
  );
}

const styles = StyleSheet.create({
  highlighted: {
    backgroundColor: 'yellow',
  },
});

Here is a Snack where you can see the result and play with it : https://snack.expo.io/@adesurirey/properly-highlight-text-with-react-native

It can surely be improved, I'll be happy to have feedback.


问:
Loop timer thread
I would like to create thread pool for loop timer: for each n seconds, we will run task.

In my example, we have two tasks. For each task, I will create one thread to run. I add the condition of status for each task, if the status is false, we do nothing. I need the status to control the timer, I can call the timer start/stop (sorry, in this code, there is only start function).

Here is my code:

```<code> #include <iostream>
#include <list>
#include <functional>
#include <map>
#include <thread>
#include <chrono>
#include <vector>
#include <mutex>

//using namespace std::chrono_literals;

void print_time()
{
    std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
    std::chrono::system_clock::duration tp = now.time_since_epoch();
    tp -= std::chrono::duration_cast<std::chrono::seconds>(tp);
    std::time_t ttp = std::chrono::system_clock::to_time_t(now);
    tm t = *gmtime(&ttp);

    std::printf("[%04u-%02u-%02u %02u:%02u:%02u.%03u]: ", t.tm_year + 1900,
                t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec,
                static_cast<unsigned>(tp/std::chrono::milliseconds(1)));
}

typedef std::function<void()> Callback;

enum E_NUM {
    NUM_ONE = 0,
    NUM_TWO
};

class Foo {
    public:
        static Foo& getInstance()
        {
            static Foo instance;
            return instance;
        }

        void init() {
            m_mapThreadStatus[NUM_ONE] = false;
            m_mapThreadStatus[NUM_TWO] = false;
            m_mapCallback[NUM_ONE] = std::bind(&Foo::test, this);
            m_mapCallback[NUM_TWO] = std::bind(&Foo::foo_test, this);
        }

        void addTimer(E_NUM id, int num_seconds) {
            std::thread th ([id, num_seconds] () {
                    std::cout << std::this_thread::get_id() << " id: " << id << "\tseconds: " << num_seconds << std::endl;
                    while (1)
                    {
                        if ( Foo::getInstance().getStatus(id) == true)
                        {
                            Foo::getInstance().callfunctor(id);
                            std::this_thread::sleep_for(std::chrono::seconds(num_seconds));
                        }
                        else
                        {
                        }
                        //std::this_thread::sleep_for(std::chrono::seconds(num_seconds));
                    }
                });
            m_mapThreads[id] = std::move(th);
        }

        void callfunctor(E_NUM id) {
            m_mapCallback[id]();
        }

        void startTimers(E_NUM id) {
            m_mapThreadStatus[id] = true;
            if (m_mapThreads[id].joinable())
            {
                m_mapThreads[id].join();
            }
        }

        bool getStatus(E_NUM id) {
            return m_mapThreadStatus[id];}

    private:
        void test() {
            print_time();
            std::cout << std::this_thread::get_id() << std::endl;
            std::cout << "\033[1;31m" << __PRETTY_FUNCTION__ << "\033[0m" << std::endl;
        }
        void foo_test() {
            print_time();
            std::cout << std::this_thread::get_id() << std::endl;
            std::cout << "\033[1;32m" << __PRETTY_FUNCTION__ << "\033[0m" << std::endl;
        }
        Foo() {init();}
        std::map<E_NUM, Callback> m_mapCallback;
        std::vector<std::thread> m_threads;
        std::map<E_NUM, std::thread> m_mapThreads;
        std::map<E_NUM, bool> m_mapThreadStatus;
};

int main()
{
    Foo::getInstance().addTimer(NUM_ONE, 1);
    Foo::getInstance().addTimer(NUM_TWO, 2);
    Foo::getInstance().startTimers(NUM_ONE);
    Foo::getInstance().startTimers(NUM_TWO);
    return 0;
}
</code>```

But my problem:
1. it seems that only one task run, not two as expect.

```<code>40557398533888 id: 0    seconds: 1140557390141184 id: 1 seconds: 2
[2019-05-28 11:56:49.770]: 140557398533888
void Foo::test()

[2019-05-28 11:56:50.770]: 140557398533888
void Foo::test()
[2019-05-28 11:56:51.771]: 140557398533888
void Foo::test()
[2019-05-28 11:56:52.771]: 140557398533888
void Foo::test()
[2019-05-28 11:56:53.772]: 140557398533888
void Foo::test()
</code>```

The classical question: when we create the std::thread, it runs immediately, right? For example, link. So, how can I improve my code to start after adding timer?

EDIT 1:

I added the function in Foo:

```<code>class Foo {
    ...
    void startTimers() {
        m_mapThreads[NUM_ONE].join();
        m_mapThreads[NUM_TWO].join();
    }
};
</code>```

And I call this function at the END of main, it works like a charm. Thank you.

答:
Consider your Foo::startTimers implementation...

```<code>void startTimers (E_NUM id)
{
    m_mapThreadStatus[id] = true;
    if (m_mapThreads[id].joinable()) {
        m_mapThreads[id].join();
    }
}
</code>```

You start the thread identified by id with...

```<code>m_mapThreadStatus[id] = true;
</code>```

But you then join that thread.  The end result being that when you start a given thread your code will block until that thread has finished.  So, with...

```<code>int main()
{
    Foo::getInstance().addTimer(NUM_ONE, 1);
    Foo::getInstance().addTimer(NUM_TWO, 2);
    Foo::getInstance().startTimers(NUM_ONE);
    Foo::getInstance().startTimers(NUM_TWO);
    return 0;
}
</code>```

The line...

```<code>Foo::getInstance().startTimers(NUM_ONE);
</code>```

will block until the thread associated with NUM_ONE finishes -- never in the present case -- and Foo::getInstance().startTimers(NUM_TWO) is never called.

Title: Loop timer thread

Body:
I would like to create thread pool for loop timer: for each n seconds, we will run task.

In my example, we have two tasks. For each task, I will create one thread to run. I add the condition of status for each task, if the status is false, we do nothing. I need the status to control the timer, I can call the timer start/stop (sorry, in this code, there is only start function).

Here is my code:

 #include <iostream>
#include <list>
#include <functional>
#include <map>
#include <thread>
#include <chrono>
#include <vector>
#include <mutex>

//using namespace std::chrono_literals;

void print_time()
{
    std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
    std::chrono::system_clock::duration tp = now.time_since_epoch();
    tp -= std::chrono::duration_cast<std::chrono::seconds>(tp);
    std::time_t ttp = std::chrono::system_clock::to_time_t(now);
    tm t = *gmtime(&ttp);

    std::printf("[%04u-%02u-%02u %02u:%02u:%02u.%03u]: ", t.tm_year + 1900,
                t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec,
                static_cast<unsigned>(tp/std::chrono::milliseconds(1)));
}

typedef std::function<void()> Callback;

enum E_NUM {
    NUM_ONE = 0,
    NUM_TWO
};

class Foo {
    public:
        static Foo& getInstance()
        {
            static Foo instance;
            return instance;
        }

        void init() {
            m_mapThreadStatus[NUM_ONE] = false;
            m_mapThreadStatus[NUM_TWO] = false;
            m_mapCallback[NUM_ONE] = std::bind(&Foo::test, this);
            m_mapCallback[NUM_TWO] = std::bind(&Foo::foo_test, this);
        }

        void addTimer(E_NUM id, int num_seconds) {
            std::thread th ([id, num_seconds] () {
                    std::cout << std::this_thread::get_id() << " id: " << id << "\tseconds: " << num_seconds << std::endl;
                    while (1)
                    {
                        if ( Foo::getInstance().getStatus(id) == true)
                        {
                            Foo::getInstance().callfunctor(id);
                            std::this_thread::sleep_for(std::chrono::seconds(num_seconds));
                        }
                        else
                        {
                        }
                        //std::this_thread::sleep_for(std::chrono::seconds(num_seconds));
                    }
                });
            m_mapThreads[id] = std::move(th);
        }

        void callfunctor(E_NUM id) {
            m_mapCallback[id]();
        }

        void startTimers(E_NUM id) {
            m_mapThreadStatus[id] = true;
            if (m_mapThreads[id].joinable())
            {
                m_mapThreads[id].join();
            }
        }

        bool getStatus(E_NUM id) {
            return m_mapThreadStatus[id];}

    private:
        void test() {
            print_time();
            std::cout << std::this_thread::get_id() << std::endl;
            std::cout << "\033[1;31m" << __PRETTY_FUNCTION__ << "\033[0m" << std::endl;
        }
        void foo_test() {
            print_time();
            std::cout << std::this_thread::get_id() << std::endl;
            std::cout << "\033[1;32m" << __PRETTY_FUNCTION__ << "\033[0m" << std::endl;
        }
        Foo() {init();}
        std::map<E_NUM, Callback> m_mapCallback;
        std::vector<std::thread> m_threads;
        std::map<E_NUM, std::thread> m_mapThreads;
        std::map<E_NUM, bool> m_mapThreadStatus;
};

int main()
{
    Foo::getInstance().addTimer(NUM_ONE, 1);
    Foo::getInstance().addTimer(NUM_TWO, 2);
    Foo::getInstance().startTimers(NUM_ONE);
    Foo::getInstance().startTimers(NUM_TWO);
    return 0;
}

But my problem:
1. it seems that only one task run, not two as expect.

40557398533888 id: 0    seconds: 1140557390141184 id: 1 seconds: 2
[2019-05-28 11:56:49.770]: 140557398533888
void Foo::test()

[2019-05-28 11:56:50.770]: 140557398533888
void Foo::test()
[2019-05-28 11:56:51.771]: 140557398533888
void Foo::test()
[2019-05-28 11:56:52.771]: 140557398533888
void Foo::test()
[2019-05-28 11:56:53.772]: 140557398533888
void Foo::test()

The classical question: when we create the std::thread, it runs immediately, right? For example, link. So, how can I improve my code to start after adding timer?

EDIT 1:

I added the function in Foo:

class Foo {
    ...
    void startTimers() {
        m_mapThreads[NUM_ONE].join();
        m_mapThreads[NUM_TWO].join();
    }
};

And I call this function at the END of main, it works like a charm. Thank you.

Body:
Consider your Foo::startTimers implementation...

void startTimers (E_NUM id)
{
    m_mapThreadStatus[id] = true;
    if (m_mapThreads[id].joinable()) {
        m_mapThreads[id].join();
    }
}

You start the thread identified by id with...

m_mapThreadStatus[id] = true;

But you then join that thread.  The end result being that when you start a given thread your code will block until that thread has finished.  So, with...

int main()
{
    Foo::getInstance().addTimer(NUM_ONE, 1);
    Foo::getInstance().addTimer(NUM_TWO, 2);
    Foo::getInstance().startTimers(NUM_ONE);
    Foo::getInstance().startTimers(NUM_TWO);
    return 0;
}

The line...

Foo::getInstance().startTimers(NUM_ONE);

will block until the thread associated with NUM_ONE finishes -- never in the present case -- and Foo::getInstance().startTimers(NUM_TWO) is never called.


问:
How do I close a sheet opened with golang lib excelize?
I followed the repo (https://github.com/360EntSecGroup-Skylar/excelize) tutorial to open a file:

```<code>f, err := excelize.OpenFile("./Book1.xlsx")
if err != nil {
    fmt.Println(err)
    return
}enter code here
</code>```

But i couldn't find  a tutorial about closing, something like:

```<code>defer f.Close()
</code>```

Is there a way to do that?

答:
You don't have to close it.
Just open it, and save it if you need to.

myFile, err := excelize.OpenFile("./Book1.xlsx")
    if err != nil {
        fmt.Println(err)
    return
}

Then, do what you want.

Finally, just save it with the origin path :

err = myFile.Save()
    if err != nil {
        fmt.Println(err)
}

Or, an other path :

err := myFile.SaveAs("./myFolder/Book2.xlsx")
    if err != nil {
        fmt.Println(err)
}

Body:
I followed the repo (https://github.com/360EntSecGroup-Skylar/excelize) tutorial to open a file:

f, err := excelize.OpenFile("./Book1.xlsx")
if err != nil {
    fmt.Println(err)
    return
}enter code here

But i couldn't find  a tutorial about closing, something like:

defer f.Close()

Is there a way to do that?


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

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

答: Maybe a list is not the ideal data structure for your use case - would you be better off using a HashSet if the ordering of elements is not imporant?</p>

Title: Vector option in Java


问:
Eloquent Relation with foreign key
I have issues by connecting to tables

I have 2 Model

First Model called PodioBorgerNotat with columns in the table called podio_borger_notats

id

user_id

item_id

app_item_id

borger_item_id (foreign key)

medarbejder_item_id

status

The second Model called PodioBorgerStamark with columns in the table podio_borger_stamarks

id

item_id (local key)

app_item_id

status

initials

name

I want to make a connection between PodioBorgerNotat and PodioBorgerStamark

so this is what I do in PodioBorgerNotat Model

```<code>public function borger()
    {
        return $this->belongsTo(PodioBorgerStamark::class, 'borger_item_id', 'item_id');
    }
</code>```

Now I want to output the result by executing this output

```<code>$borgernotater = PodioBorgerNotat::orderBy('created_at', 'acs')->orderBy('id', 'desc')->with('PodioBorgerStamark')->paginate(10);
</code>```

This wont work and i get this error messsage

```<code>Call to undefined relationship [PodioBorgerStamark] on model [App\PodioBorgerNotat].
</code>```

答:
Your relation name is borger:

```<code>public function borger(){
    ...
}
</code>```

You should call borger in with():

```<code>$borgernotater = PodioBorgerNotat
    ::orderBy('created_at', 'acs')
    ->orderBy('id', 'desc')
    ->with('borger')
    ->paginate(10);
</code>```

Title: Eloquent Relation with foreign key

Body:
I have issues by connecting to tables

I have 2 Model

First Model called PodioBorgerNotat with columns in the table called podio_borger_notats

id

user_id

item_id

app_item_id

borger_item_id (foreign key)

medarbejder_item_id

status

The second Model called PodioBorgerStamark with columns in the table podio_borger_stamarks

id

item_id (local key)

app_item_id

status

initials

name

I want to make a connection between PodioBorgerNotat and PodioBorgerStamark

so this is what I do in PodioBorgerNotat Model

public function borger()
    {
        return $this->belongsTo(PodioBorgerStamark::class, 'borger_item_id', 'item_id');
    }

Now I want to output the result by executing this output

$borgernotater = PodioBorgerNotat::orderBy('created_at', 'acs')->orderBy('id', 'desc')->with('PodioBorgerStamark')->paginate(10);

This wont work and i get this error messsage

Call to undefined relationship [PodioBorgerStamark] on model [App\PodioBorgerNotat].

Body:
Your relation name is borger:

public function borger(){
    ...
}

You should call borger in with():

$borgernotater = PodioBorgerNotat
    ::orderBy('created_at', 'acs')
    ->orderBy('id', 'desc')
    ->with('borger')
    ->paginate(10);


问:
Apache-spark - Error launching pyspark on windows
I am trying to run pyspark on windows. However, I received following error:

```<code>c:\spark>pyspark
Python 3.6.0 |Anaconda 4.3.1 (64-bit)| (default, Dec 23 2016, 11:57:41) [MSC
v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Traceback (most recent call last):
File "C:\spark\bin\..\python\pyspark\shell.py", line 38, in <module>
   SparkContext._ensure_initialized()
File "C:\spark\python\pyspark\context.py", line 259, in _ensure_initialized
   SparkContext._gateway = gateway or launch_gateway(conf)
File "C:\spark\python\pyspark\java_gateway.py", line 80, in launch_gateway
   proc = Popen(command, stdin=PIPE, env=env)
File "C:\Users\shuzhe\Anaconda3\lib\subprocess.py", line 707, in __init__
   restore_signals, start_new_session)
File "C:\Users\shuzhe\Anaconda3\lib\subprocess.py", line 990, in _execute_child
startupinfo)
PermissionError: [WinError 5] Access is denied
</code>```

I have searched for hours, but I could not find a solution to this problem. Any help is greatly appreciated!

Thanks!

答:
Hi I ran into the same problem.  I ditched the SPARK_HOME folder (which in my case was C:\spark-2.4.3-bin-hadoop2.7) that I created previously using cygwin tar and tried unpacking the folder again (from spark-2.4.3-bin-hadoop2.7.tgz), but this time using 7zip instead of cygwin tar and then problem went away.  Note that with 7zip the unpacking is done in two step, first extract the ...tar from ...tgz, and then extract the whole directory tree from ...tar

Some other discussion on the Internet (e.g. here) suggested that the problem was due to cygwin tar got some permission wrong.  This explanation is consistent with what I tested and experienced above.

Body:
I am trying to run pyspark on windows. However, I received following error:

c:\spark>pyspark
Python 3.6.0 |Anaconda 4.3.1 (64-bit)| (default, Dec 23 2016, 11:57:41) [MSC
v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Traceback (most recent call last):
File "C:\spark\bin\..\python\pyspark\shell.py", line 38, in <module>
   SparkContext._ensure_initialized()
File "C:\spark\python\pyspark\context.py", line 259, in _ensure_initialized
   SparkContext._gateway = gateway or launch_gateway(conf)
File "C:\spark\python\pyspark\java_gateway.py", line 80, in launch_gateway
   proc = Popen(command, stdin=PIPE, env=env)
File "C:\Users\shuzhe\Anaconda3\lib\subprocess.py", line 707, in __init__
   restore_signals, start_new_session)
File "C:\Users\shuzhe\Anaconda3\lib\subprocess.py", line 990, in _execute_child
startupinfo)
PermissionError: [WinError 5] Access is denied

I have searched for hours, but I could not find a solution to this problem. Any help is greatly appreciated!

Thanks!


问:
Store un-submitted data using Shared Preferences
I need to store data which hasn't been saved yet using Shared Preferences. To give a quick example, in my application I want that if the user filled the sign-up form and closed the application, his information will still be filled up when he re-enters the application. Would you suggest any tutorials?

答:
You can save that data in Bundle using onSaveInstanceState
e.g. </p>

```<code>@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    textView.setText(savedInstanceState.getString(TEXT_VIEW_KEY));
}

// invoked when the activity may be temporarily destroyed, save the instance state here
@Override
public void onSaveInstanceState(Bundle outState) {
    outState.putString(GAME_STATE_KEY, gameState);
    outState.putString(TEXT_VIEW_KEY, textView.getText());

    // call superclass to save any view hierarchy
    super.onSaveInstanceState(outState);
}
</code>```

Body:
You can save that data in Bundle using onSaveInstanceState
e.g.

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
    textView.setText(savedInstanceState.getString(TEXT_VIEW_KEY));
}

// invoked when the activity may be temporarily destroyed, save the instance state here
@Override
public void onSaveInstanceState(Bundle outState) {
    outState.putString(GAME_STATE_KEY, gameState);
    outState.putString(TEXT_VIEW_KEY, textView.getText());

    // call superclass to save any view hierarchy
    super.onSaveInstanceState(outState);
}


问:
Why do some elements remain even if the condition matches for each one?
I have created a small store application in Ruby. The concept is simple: I want to be able to add, remove, and view the 'database' in this example. The code seems to work; however, it does not behave like one would expect. I can add any product just fine, but when I try to remove them by a certain criterion that matches each item, only some are removed.

```<code>class Store
  PRODUCT = Struct.new(:identifier, :parameters)

  def initialize(database = [])
    @database = database
  end

  def increment
    # Increment the unique identifier if the database is not empty
    # Otherwise, set the initial value for the unique identifier
    @database.any? ? @database.map { |object| object[:identifier] }.max + 1 : 1
  end

  def add(product)
    @database.push(identifier: increment, parameters: product)
  end

  def remove(product)
    @database.each do |object|
      product.each do |key, value|
        @database.delete(object) if object[key] == value
        @database.delete(object) if object[:parameters][key] == value
      end
    end
  end

  def view
    puts @database
    puts "\n"
  end
end

store = Store.new

store.add(name: 'Fanta', volume: 33, unit: 'centiliter', count: 48, price: 9.95, currency: 'SEK')
store.add(name: 'Sprite', volume: 33, unit: 'centiliter', count: 48, price: 9.95, currency: 'SEK')
store.add(name: 'Coca-Cola', volume: 33, unit: 'centiliter', count: 48, price: 9.95, currency: 'SEK')

store.view

store.remove(price: 9.95)

store.view
</code>```

This example will add three arbitrary items to the Store instance and list the contents found in the @database array. This array will of course hold the values:

```<code>{:identifier=>1, :parameters=>{:name=>"Fanta", :volume=>33, :unit=>"centiliter", :count=>48, :price=>9.95, :currency=>"SEK"}}
{:identifier=>2, :parameters=>{:name=>"Sprite", :volume=>33, :unit=>"centiliter", :count=>48, :price=>9.95, :currency=>"SEK"}}
{:identifier=>3, :parameters=>{:name=>"Coca-Cola", :volume=>33, :unit=>"centiliter", :count=>48, :price=>9.95, :currency=>"SEK"}}
</code>```

The code then proceeds to remove any product with a price of 9.95, which should match all the products in the @database array. However, when I list its contents once more, one product remains:

```<code>{:identifier=>2, :parameters=>{:name=>"Sprite", :volume=>33, :unit=>"centiliter", :count=>48, :price=>9.95, :currency=>"SEK"}}
</code>```

I cannot find any logic to this. Why does my remove method not remove all the elements if the condition holds true for each comparison?

答:
I think that this problem comes from float comparison. There are many ways to approach this. One of them: </p>

```<code>  def remove(product)
    @database.delete_if do |object|
      product.any? do |key, value|
        matches?(object[key], value) || matches?(object[:parameters][key], value)
      end
    end
  end

  def matches?(obj1, obj2)
    if obj1.is_a?(Float) || obj2.is_a?(Float)
      (obj1-obj2).abs < 0.001
    else
      obj1 == obj2
    end
  end
</code>```

Body:
I have created a small store application in Ruby. The concept is simple: I want to be able to add, remove, and view the 'database' in this example. The code seems to work; however, it does not behave like one would expect. I can add any product just fine, but when I try to remove them by a certain criterion that matches each item, only some are removed.

class Store
  PRODUCT = Struct.new(:identifier, :parameters)

  def initialize(database = [])
    @database = database
  end

  def increment
    # Increment the unique identifier if the database is not empty
    # Otherwise, set the initial value for the unique identifier
    @database.any? ? @database.map { |object| object[:identifier] }.max + 1 : 1
  end

  def add(product)
    @database.push(identifier: increment, parameters: product)
  end

  def remove(product)
    @database.each do |object|
      product.each do |key, value|
        @database.delete(object) if object[key] == value
        @database.delete(object) if object[:parameters][key] == value
      end
    end
  end

  def view
    puts @database
    puts "\n"
  end
end

store = Store.new

store.add(name: 'Fanta', volume: 33, unit: 'centiliter', count: 48, price: 9.95, currency: 'SEK')
store.add(name: 'Sprite', volume: 33, unit: 'centiliter', count: 48, price: 9.95, currency: 'SEK')
store.add(name: 'Coca-Cola', volume: 33, unit: 'centiliter', count: 48, price: 9.95, currency: 'SEK')

store.view

store.remove(price: 9.95)

store.view

This example will add three arbitrary items to the Store instance and list the contents found in the @database array. This array will of course hold the values:

{:identifier=>1, :parameters=>{:name=>"Fanta", :volume=>33, :unit=>"centiliter", :count=>48, :price=>9.95, :currency=>"SEK"}}
{:identifier=>2, :parameters=>{:name=>"Sprite", :volume=>33, :unit=>"centiliter", :count=>48, :price=>9.95, :currency=>"SEK"}}
{:identifier=>3, :parameters=>{:name=>"Coca-Cola", :volume=>33, :unit=>"centiliter", :count=>48, :price=>9.95, :currency=>"SEK"}}

The code then proceeds to remove any product with a price of 9.95, which should match all the products in the @database array. However, when I list its contents once more, one product remains:

{:identifier=>2, :parameters=>{:name=>"Sprite", :volume=>33, :unit=>"centiliter", :count=>48, :price=>9.95, :currency=>"SEK"}}

I cannot find any logic to this. Why does my remove method not remove all the elements if the condition holds true for each comparison?

Body:
I think that this problem comes from float comparison. There are many ways to approach this. One of them:

  def remove(product)
    @database.delete_if do |object|
      product.any? do |key, value|
        matches?(object[key], value) || matches?(object[:parameters][key], value)
      end
    end
  end

  def matches?(obj1, obj2)
    if obj1.is_a?(Float) || obj2.is_a?(Float)
      (obj1-obj2).abs < 0.001
    else
      obj1 == obj2
    end
  end