问:
Insert 120 second wait in Visual studio Webtest
I want to add a delay of 120 second between the execution of two web requests. I have tried using think time but it won't pause the execution for 120 sec.

Can anyone please let me know how to add wait to pause the execution for 120 second (after say 2 web request execution) and then proceed the execution for next request.

I am using visual studio 2015.

答:
Think times are processed after the response is received. So to have a delay between two requests set the think time on the first request. I have successfully used long sleep times. Think times can be disabled in a test so make sure they are enabled:

1 In the ".testsettings" file, in the Web test section.

2 In the Think profile property of the scenario. If the delay should be (as near as possible to) exactly 120 seconds then set the profile to On.

3 The default for when Visual Studio runs a standalone web test is to not use think times. Thus everything runs as fast as possible. The setting in (1) above can be used to change the default. A temporary change to the default can be made from the "Edit test settings" command of the web test results window; this change only applies to test runs started by the "Click here to run again" in the same window.

If the two requests are actually different web tests then the Think time between test iterations property of the scenario may be useful.

Do not use any of the task or thread delay (or sleep) methods if there is any chance that this test will be used as part of a load test as they will stop many virtual users from running. See the first part of this answer for a fuller explanation. A delay or sleep call might be used if the web test will never be used within a load test.


来源: stackexchange

问:
Python nested loops do not continue with the subprocess
I tried to run below code but it just loops in the very inner one and then stops, I do not understand why it doesn't continue to the outer loops?</p>

```<code>#!/usr/bin/python3

import os
import sys
import subprocess

p1 = subprocess.Popen([find...],stdout=subprocess.PIPE)
for i in range(...):
        p2 = subprocess.Popen([grep...],stdin=p1.stdout,stdout=subprocess.PIPE)
        for e in range(...):
               p3=subprocess.Popen([grep...],stdin=p2.stdout,stdout=subprocess.PIPE)
               for file in p3.stdout:
                        print(str(i)+str(e)+str(file))
</code>```

答:
the concept is wrong

```<code>p1 = subprocess.Popen([find...],stdout=subprocess.PIPE)
for i in range(...):
        p2 = subprocess.Popen([grep...],stdin=p1.stdout,stdout=subprocess.PIPE)
</code>```

when running this code (first iteration), p1.stdout is consumed fully by p2. So next spawns of p2 get an empty output.

(same goes for the inner loop)

I would write that in pure python.

First loop to match the files you want to grep on:

```<code>files_to_process = []
for root,dirs,files in os.walk(start_directory):
    files_to_process += [f for f in files if <some condition> ]
</code>```

Once you have the list of files, you can open them in a lot of loops and search their content. I would advise to avoid grep and do something like:

```<code>with open(filename) as f:
    contents = f.read()
    results = re.search(regexp,contents)
</code>```

(or line by line)

ContentLicense: CC BY-SA 3.0

Body:
I tried to run below code but it just loops in the very inner one and then stops, I do not understand why it doesn't continue to the outer loops?

#!/usr/bin/python3

import os
import sys
import subprocess

p1 = subprocess.Popen([find...],stdout=subprocess.PIPE)
for i in range(...):
        p2 = subprocess.Popen([grep...],stdin=p1.stdout,stdout=subprocess.PIPE)
        for e in range(...):
               p3=subprocess.Popen([grep...],stdin=p2.stdout,stdout=subprocess.PIPE)
               for file in p3.stdout:
                        print(str(i)+str(e)+str(file))

Body:
the concept is wrong

p1 = subprocess.Popen([find...],stdout=subprocess.PIPE)
for i in range(...):
        p2 = subprocess.Popen([grep...],stdin=p1.stdout,stdout=subprocess.PIPE)

when running this code (first iteration), p1.stdout is consumed fully by p2. So next spawns of p2 get an empty output.

(same goes for the inner loop)

I would write that in pure python.

First loop to match the files you want to grep on:

files_to_process = []
for root,dirs,files in os.walk(start_directory):
    files_to_process += [f for f in files if <some condition> ]

Once you have the list of files, you can open them in a lot of loops and search their content. I would advise to avoid grep and do something like:

with open(filename) as f:
    contents = f.read()
    results = re.search(regexp,contents)

(or line by line)


问:
Update SonarQube rules in SonarLint eclipse
When I change my quality profile on SonarQube, there is a problem to update my profile in SonarLint for Eclipse. I have already link my SonarLint to my SonarQube and it works fine. But when I change rules in SonarQube, for example I disable one there is no update in Eclipse.</p>

答:
SonarLint for Eclipse doesn't pick up immediately changes to the quality profile of a connected project. It checks from time to time and gives you a warning to update your bindings.

You can manually update your bindings if you right-click on the server configuration in SonarLint for Eclipse, in the SonarQube Servers view. After that, on the next analysis of your files in Eclipse, the change should be visible.

To open the SonarQube Servers view, go to Window / Show View / Other... / SonarLint / SonarQube Servers.


问:
Java: Adding events to dynamically created components
I'm building a UI in Java. I want to create new components, like a JLabel, using a button. So every time I click a button it creates a new JLabel and places them in a specific JPanel.

Then, I want to be able to do some things with the labels based on how the user clicks on them.

With a left mouse press I want them to be able to drag the labels around the screen.

With a right mouse click I want to be open a new window where certain data can be entered, tied to the label (which might involve dynamically creating variables).

I've been toying around with some code I've Googled around for. I can get a button to create new labels in a panel, but when I try to get them to drag, I can only get one label at a time to appear, and after a second button press, moving the label isn't smooth, it jumps around.

I haven't even tried to implement any of the right mouse click things yet. If anyone can point me in the right direction, I'd appreciate it.

```<code>public class Testing {

    JFrame frame;

 //Launch the application.

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {
                    Testing window = new Testing();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    });
}

 //Create the application.

public Testing() {
    initialize();
    }

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    JPanel area;
    JButton btnCreate;
    JLabel dragLabel;

    frame = new JFrame();
    frame.setBounds(100, 100, 511, 542);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);
    frame.setVisible(true);

    area = new JPanel();
    area.setBounds(10, 11, 477, 404);
    frame.getContentPane().add(area);
    area.setLayout(new BorderLayout());

    btnCreate = new JButton("Create Label");
    dragLabel = new JLabel("Drag Me");
    btnCreate.setBounds(10, 425, 477, 67);
    frame.getContentPane().add(btnCreate);
    btnCreate.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
            area.add(dragLabel);
            area.revalidate();

    DragListener drag = new DragListener();
    dragLabel.addMouseListener(drag);
    dragLabel.addMouseMotionListener(drag);
    }
    });

  }
}

class DragListener extends MouseInputAdapter
{
Point location;
MouseEvent pressed;

public void mousePressed(MouseEvent me) {
    pressed = me;
}

public void mouseDragged(MouseEvent me)
{
    if(SwingUtilities.isLeftMouseButton(me)){
        Component component = me.getComponent();
        location = component.getLocation(location);
        int x = location.x - pressed.getX() + me.getX();
        int y = location.y - pressed.getY() + me.getY();
        component.setLocation(x, y);
         }
     }
}
</code>```

EDIT - I'm fairly certain the primary issue is in how the JLabel itself is being added to the panel. Every time the button is being pushed it's adding the same label over again, and this is gumming up the works.

Unfortunately, I'm not sure how to deal with that. I've done a bit more digging, and since dynamic variables aren't possible, I'm going to have to use an array or a map or some sort. With that, it appears I can declare arrays of components. Would something like that be necessary for my purposes?

答:
Really odd stuff in your code. I don't want to go everything, and I'm not an expert by any stretch of the imagination, but I tried to remove redundant or contradictory stuff. I suspect a part of what you did was just copy pasting bits without really fitting them into the code.

Anyway, you needed to create the label inside the listener, so that it creates a new one everytime you click. Otherwise you only ever create one label and just reuse the same everytime.

I implemented a dialog on right click to enter the label name, don't know what you wanted to do but at least it detects right clicks.

Also in general it's easier to use layout managers instead of hardcoding everything. Here you had a borderlayout but were ignoring it.

```<code>class Main {

    //Launch the application.
    public static void main(String[] args) {
        DrageableLabel window = new DrageableLabel();
    }
}

public class DrageableLabel {

    public DrageableLabel() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        JFrame frame = new JFrame();
        Container area = frame.getContentPane();
        area.setLayout(new BorderLayout());

        JButton btnCreate = new JButton("Create Label");
        btnCreate.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                if (SwingUtilities.isRightMouseButton(e)) {
                    /*
                    This is where you create your new window
                    for now I've added a dialog that takes a string parameter and creates a label with that string
                    I moved the method code to create a new drageable label outside the actionlistener to make it less confusing and reuseable
                    Either build w-e you want directly in here
                    or call a method that does it (which I prefer)
                     */
                    String string = JOptionPane.showInputDialog(frame, "Enter your message", "Messages", JOptionPane.CANCEL_OPTION);
                    addDrageableLabel(string, area);
                } else if (SwingUtilities.isLeftMouseButton(e)) {
                    addDrageableLabel("Drag me", area);
                }
            }
        });
        area.add(btnCreate, BorderLayout.SOUTH);

        frame.setBounds(100, 100, 511, 542);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    // This is the method that creates and adds a drageable label
    public void addDrageableLabel(String labelName, Container container) {
        JLabel dragLabel = new JLabel(labelName);
        container.add(dragLabel, BorderLayout.CENTER);
        container.validate();

        DragListener drag = new DragListener();
        dragLabel.addMouseListener(drag);
        dragLabel.addMouseMotionListener(drag);
    }
}

class DragListener extends MouseInputAdapter {

    Point location;
    MouseEvent pressed;

    @Override
    public void mousePressed(MouseEvent me) {
        pressed = me;
    }

    @Override
    public void mouseDragged(MouseEvent me) {
        Component component = me.getComponent();
        location = component.getLocation(location);
        int x = location.x - pressed.getX() + me.getX();
        int y = location.y - pressed.getY() + me.getY();
        component.setLocation(x, y);
    }
}
</code>```

Body:
I'm building a UI in Java. I want to create new components, like a JLabel, using a button. So every time I click a button it creates a new JLabel and places them in a specific JPanel.

Then, I want to be able to do some things with the labels based on how the user clicks on them.

With a left mouse press I want them to be able to drag the labels around the screen.

With a right mouse click I want to be open a new window where certain data can be entered, tied to the label (which might involve dynamically creating variables).

I've been toying around with some code I've Googled around for. I can get a button to create new labels in a panel, but when I try to get them to drag, I can only get one label at a time to appear, and after a second button press, moving the label isn't smooth, it jumps around.

I haven't even tried to implement any of the right mouse click things yet. If anyone can point me in the right direction, I'd appreciate it.

public class Testing {

    JFrame frame;

 //Launch the application.

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                try {
                    Testing window = new Testing();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    });
}

 //Create the application.

public Testing() {
    initialize();
    }

/**
 * Initialize the contents of the frame.
 */
private void initialize() {
    JPanel area;
    JButton btnCreate;
    JLabel dragLabel;

    frame = new JFrame();
    frame.setBounds(100, 100, 511, 542);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);
    frame.setVisible(true);

    area = new JPanel();
    area.setBounds(10, 11, 477, 404);
    frame.getContentPane().add(area);
    area.setLayout(new BorderLayout());

    btnCreate = new JButton("Create Label");
    dragLabel = new JLabel("Drag Me");
    btnCreate.setBounds(10, 425, 477, 67);
    frame.getContentPane().add(btnCreate);
    btnCreate.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
            area.add(dragLabel);
            area.revalidate();

    DragListener drag = new DragListener();
    dragLabel.addMouseListener(drag);
    dragLabel.addMouseMotionListener(drag);
    }
    });

  }
}

class DragListener extends MouseInputAdapter
{
Point location;
MouseEvent pressed;

public void mousePressed(MouseEvent me) {
    pressed = me;
}

public void mouseDragged(MouseEvent me)
{
    if(SwingUtilities.isLeftMouseButton(me)){
        Component component = me.getComponent();
        location = component.getLocation(location);
        int x = location.x - pressed.getX() + me.getX();
        int y = location.y - pressed.getY() + me.getY();
        component.setLocation(x, y);
         }
     }
}

EDIT - I'm fairly certain the primary issue is in how the JLabel itself is being added to the panel. Every time the button is being pushed it's adding the same label over again, and this is gumming up the works.

Unfortunately, I'm not sure how to deal with that. I've done a bit more digging, and since dynamic variables aren't possible, I'm going to have to use an array or a map or some sort. With that, it appears I can declare arrays of components. Would something like that be necessary for my purposes?

Body:
Really odd stuff in your code. I don't want to go everything, and I'm not an expert by any stretch of the imagination, but I tried to remove redundant or contradictory stuff. I suspect a part of what you did was just copy pasting bits without really fitting them into the code.

Anyway, you needed to create the label inside the listener, so that it creates a new one everytime you click. Otherwise you only ever create one label and just reuse the same everytime.

I implemented a dialog on right click to enter the label name, don't know what you wanted to do but at least it detects right clicks.

Also in general it's easier to use layout managers instead of hardcoding everything. Here you had a borderlayout but were ignoring it.

class Main {

    //Launch the application.
    public static void main(String[] args) {
        DrageableLabel window = new DrageableLabel();
    }
}

public class DrageableLabel {

    public DrageableLabel() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        JFrame frame = new JFrame();
        Container area = frame.getContentPane();
        area.setLayout(new BorderLayout());

        JButton btnCreate = new JButton("Create Label");
        btnCreate.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                if (SwingUtilities.isRightMouseButton(e)) {
                    /*
                    This is where you create your new window
                    for now I've added a dialog that takes a string parameter and creates a label with that string
                    I moved the method code to create a new drageable label outside the actionlistener to make it less confusing and reuseable
                    Either build w-e you want directly in here
                    or call a method that does it (which I prefer)
                     */
                    String string = JOptionPane.showInputDialog(frame, "Enter your message", "Messages", JOptionPane.CANCEL_OPTION);
                    addDrageableLabel(string, area);
                } else if (SwingUtilities.isLeftMouseButton(e)) {
                    addDrageableLabel("Drag me", area);
                }
            }
        });
        area.add(btnCreate, BorderLayout.SOUTH);

        frame.setBounds(100, 100, 511, 542);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    // This is the method that creates and adds a drageable label
    public void addDrageableLabel(String labelName, Container container) {
        JLabel dragLabel = new JLabel(labelName);
        container.add(dragLabel, BorderLayout.CENTER);
        container.validate();

        DragListener drag = new DragListener();
        dragLabel.addMouseListener(drag);
        dragLabel.addMouseMotionListener(drag);
    }
}

class DragListener extends MouseInputAdapter {

    Point location;
    MouseEvent pressed;

    @Override
    public void mousePressed(MouseEvent me) {
        pressed = me;
    }

    @Override
    public void mouseDragged(MouseEvent me) {
        Component component = me.getComponent();
        location = component.getLocation(location);
        int x = location.x - pressed.getX() + me.getX();
        int y = location.y - pressed.getY() + me.getY();
        component.setLocation(x, y);
    }
}


问:
BLE Peripheral delegate not called
I recently upgraded from Swift 3 to Swift 4 and iOS 10.3.3 to iOS 11.1.

I'm developing an application that uses BLE to communicate bi-directionally. The workflow is as follows:

PERIPHERAL - Advertise Identity

CENTRAL - Receive Identity (process it...)

CENTRAL - Respond to peripheral

PERIPHERAL - Receive response from central

Done

My code was working perfectly before the update but now it's not. At the end of step 4, I execute the following line:

```<code>peripheral.writeValue(encryptedData!, for: characteristic, type: .withResponse)
</code>```

This should call the following delegate method but it doesn't:

```<code>public func peripheral(_ peripheral: CBPeripheral, didWriteValueFor descriptor: CBDescriptor, error: Error?) {
        print("Did Write")
        print("Error=\(error?.localizedDescription)")
    }
</code>```

It should also (and was calling) the following delegate method on the PERIPHERAL device but it doesn't:

```<code>public func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
        print("did receive write request")
}
</code>```

The service and characteristic are set as follows :

```<code>let prefs = Preferences()
            let strServiceUUID = prefs.GetString(key: Preferences.PREF_IDENTITY_SERVICE_UUID, defaultVal: "")!
            let strCharacteristicUUID = prefs.GetString(key: Preferences.PREF_IDENTITY_CHARACTERISTIC_UUID, defaultVal: "")!
            print("ServiceUUID=\(strServiceUUID)")
            print("CharacteristicUUID=\(strCharacteristicUUID)")
            mServiceUUID = CBUUID(string: strServiceUUID)
            mCharacterUUID = CBUUID(string: strCharacteristicUUID)
            mCBBluetoothServices = CBMutableService(type: mServiceUUID, primary: true)

            //lets configure the data we want to advertise for
            var characteristics : [CBCharacteristic] = []

            //let strData : String = "933911"
            //let data = strData.data(using: .utf8)
            let cbProperties: CBCharacteristicProperties = [.read, .write, .notify]
            let cbPermissions: CBAttributePermissions = [.readable, .writeable]
            mIdentityObjectCharacteristic = CBMutableCharacteristic(type: mCharacterUUID,
                                                                    properties: cbProperties,
                                                                    value: nil,
                                                                    permissions: cbPermissions)

            characteristics.append(mIdentityObjectCharacteristic)
            mCBBluetoothServices.characteristics = characteristics
            mCBPeripheralManager.add(mCBBluetoothServices)
</code>```

答:
I am not sure why upgrading the OS and Swift versions broke your code, however, it looks to me like you may be using the wrong delegate method?

Try using this

```<code>func peripheral(CBPeripheral, didWriteValueFor: CBCharacteristic, error: Error?)
</code>```

instead of this

```<code>func peripheral(CBPeripheral, didWriteValueFor: CBDescriptor, error: Error?)
</code>```

ContentLicense: CC BY-SA 4.0

Title: BLE Peripheral delegate not called

Body:
I recently upgraded from Swift 3 to Swift 4 and iOS 10.3.3 to iOS 11.1.

I'm developing an application that uses BLE to communicate bi-directionally. The workflow is as follows:

PERIPHERAL - Advertise Identity

CENTRAL - Receive Identity (process it...)

CENTRAL - Respond to peripheral

PERIPHERAL - Receive response from central

Done

My code was working perfectly before the update but now it's not. At the end of step 4, I execute the following line:

peripheral.writeValue(encryptedData!, for: characteristic, type: .withResponse)

This should call the following delegate method but it doesn't:

public func peripheral(_ peripheral: CBPeripheral, didWriteValueFor descriptor: CBDescriptor, error: Error?) {
        print("Did Write")
        print("Error=\(error?.localizedDescription)")
    }

It should also (and was calling) the following delegate method on the PERIPHERAL device but it doesn't:

public func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
        print("did receive write request")
}

The service and characteristic are set as follows :

let prefs = Preferences()
            let strServiceUUID = prefs.GetString(key: Preferences.PREF_IDENTITY_SERVICE_UUID, defaultVal: "")!
            let strCharacteristicUUID = prefs.GetString(key: Preferences.PREF_IDENTITY_CHARACTERISTIC_UUID, defaultVal: "")!
            print("ServiceUUID=\(strServiceUUID)")
            print("CharacteristicUUID=\(strCharacteristicUUID)")
            mServiceUUID = CBUUID(string: strServiceUUID)
            mCharacterUUID = CBUUID(string: strCharacteristicUUID)
            mCBBluetoothServices = CBMutableService(type: mServiceUUID, primary: true)

            //lets configure the data we want to advertise for
            var characteristics : [CBCharacteristic] = []

            //let strData : String = "933911"
            //let data = strData.data(using: .utf8)
            let cbProperties: CBCharacteristicProperties = [.read, .write, .notify]
            let cbPermissions: CBAttributePermissions = [.readable, .writeable]
            mIdentityObjectCharacteristic = CBMutableCharacteristic(type: mCharacterUUID,
                                                                    properties: cbProperties,
                                                                    value: nil,
                                                                    permissions: cbPermissions)

            characteristics.append(mIdentityObjectCharacteristic)
            mCBBluetoothServices.characteristics = characteristics
            mCBPeripheralManager.add(mCBBluetoothServices)

Body:
I am not sure why upgrading the OS and Swift versions broke your code, however, it looks to me like you may be using the wrong delegate method?

Try using this

func peripheral(CBPeripheral, didWriteValueFor: CBCharacteristic, error: Error?)

instead of this

func peripheral(CBPeripheral, didWriteValueFor: CBDescriptor, error: Error?)


问:
Odoo - How to show multi list or form in one view at same time?
With Odoo10, I want to make a department-managed view. The left side of the view is a department hierarchical tree, the right side is a list of employees according to the choice of the left. So it looks like two tree view in one view. How to implement this in odoo? Is there some code examples can reference？Or if anyone can give me some advice. Thanks very much.

The view should be like this.

答:
you can adapt the code model from the odoo custom addon in community MUK.
Please have a look here</p>


问:
Ionic 3 make promise funtion in constructor
How can we make a promise function in constructor that run line by line and wait for it's result then go to next line. Currently my promise function is not running and it runs in last.

```<code>constructor(){
    console.log("Start");
    this.getData();
    console.log("End");
}

getData() {
   return new Promise(data => {
     this.db.database.ref().child('/category').orderByChild('parent_id').
       equalTo(this.idn).once('value').then(function (snapshot) {
         console.log("Mid")
       })
   });
}
</code>```

output of above is

```<code>Start
End
Mid
</code>```

Expected output is

```<code>Start
Mid
End
</code>```

答:
Calling getData() method  in Constructor is not a good practice & harms the app performance. I would recommend using ionViewDidLoad instead for ionic, this is what you need in almost all cases. </p>

```<code>ionViewDidLoad(){
    console.log("Start");
    this.getData();
}

getData() {
   return new Promise(data => {
     this.db.database.ref().child('/category').orderByChild('parent_id').
       equalTo(this.idn).once('value').then(function (snapshot) {
         console.log("Mid"),
         //put the code you want to execute after Mid here
         console.log("End");

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

Body:
How can we make a promise function in constructor that run line by line and wait for it's result then go to next line. Currently my promise function is not running and it runs in last.

constructor(){
    console.log("Start");
    this.getData();
    console.log("End");
}

getData() {
   return new Promise(data => {
     this.db.database.ref().child('/category').orderByChild('parent_id').
       equalTo(this.idn).once('value').then(function (snapshot) {
         console.log("Mid")
       })
   });
}

output of above is

Start
End
Mid

Expected output is

Start
Mid
End

Body:
Calling getData() method  in Constructor is not a good practice & harms the app performance. I would recommend using ionViewDidLoad instead for ionic, this is what you need in almost all cases.

ionViewDidLoad(){
    console.log("Start");
    this.getData();
}

getData() {
   return new Promise(data => {
     this.db.database.ref().child('/category').orderByChild('parent_id').
       equalTo(this.idn).once('value').then(function (snapshot) {
         console.log("Mid"),
         //put the code you want to execute after Mid here
         console.log("End");

       })
   });
}


问:
Remove first char from string - Regex
I have started using Workflow on iOS to help speed up tasks at work. One of those is entering delivery records into the computer (via the iPad barcode scan function) instead of manually writting down the ref code and then typing it in.

Workflow has a "Replace Text" function that can be used with regexs to strip out characters etc.

I have managed to find a regex to get rid of the last digit in a scan (a checksum digit, always a capital letter).

The regex is simple.

```<code>.{0}-$.
</code>```

This goes in the "Find Text" field. The "Replace With" is left empty. It works wonderfully.

How can adapt this to work with other scan types with other scan types where I want to specically get rid of the FIRST character only?  I've searched the forums but can only find long and difficult to interpret regexes that I am sure won't do what I am trying to achive, something simple by comparison.

An example is of what I mean is to convert "Y300006944" to "300006944"

答:
Thanks to those who contributed somehting useful :)

I got the it resolved by using the "Split Text" function in Workflow for iOS.

I gave it the command to split based on a customer char, "Y" in this case. It's enough in this simple case.

Title: Remove first char from string - Regex

Body:
I have started using Workflow on iOS to help speed up tasks at work. One of those is entering delivery records into the computer (via the iPad barcode scan function) instead of manually writting down the ref code and then typing it in.

Workflow has a "Replace Text" function that can be used with regexs to strip out characters etc.

I have managed to find a regex to get rid of the last digit in a scan (a checksum digit, always a capital letter).

The regex is simple.

.{0}-$.

This goes in the "Find Text" field. The "Replace With" is left empty. It works wonderfully.

How can adapt this to work with other scan types with other scan types where I want to specically get rid of the FIRST character only?  I've searched the forums but can only find long and difficult to interpret regexes that I am sure won't do what I am trying to achive, something simple by comparison.

An example is of what I mean is to convert "Y300006944" to "300006944"


问:
Javascript: String search for regex, starting at the end of the string
Is there a javascript string function that search a regex and it will start the search at the end?

If not, what is the fastest and/or cleanest way to search the index of a regex starting from the end?

example of regex:

```<code>/<\/?([a-z][a-z0-9]*)\b[^>]*>?/gi
</code>```

答:
Maybe this can be useful and easier:</p>

```<code>str.lastIndexOf(str.match(<your_regex_here>).pop());
</code>```

Body:
Is there a javascript string function that search a regex and it will start the search at the end?

If not, what is the fastest and/or cleanest way to search the index of a regex starting from the end?

example of regex:

/<\/?([a-z][a-z0-9]*)\b[^>]*>?/gi

Body:
Maybe this can be useful and easier:

str.lastIndexOf(str.match(<your_regex_here>).pop());


问:
node cluster share data between master and clusters
I started to using node cluster package and i quickly found that data is not being shared between master and clusters. Lets take this example:

```<code>var cluster = require('cluster');
var numCPUs = require('os').cpus().length;

var my_array = [];

if(cluster.isMaster) {
    for (var i = 0; i < numCPUs && i < 8; i++) {
        cluster.fork();
    }

    my_array.push('test');

    cluster.on('exit', function(worker, code, signal) {
        console.log('worker ' + worker.process.pid + ' died');
    });
} else {
    setInterval(function() {
        console.log(my_array); // my_array is always empty
    }, 500);
}
</code>```

how do i define variables that can be shared between master and clusters?

答:
cluster just open more process (child process) that way they listing to the same port . in order to communicant you need so send massages between them. here is an example
node-cluster-messaging.js</p>

Body:
I started to using node cluster package and i quickly found that data is not being shared between master and clusters. Lets take this example:

var cluster = require('cluster');
var numCPUs = require('os').cpus().length;

var my_array = [];

if(cluster.isMaster) {
    for (var i = 0; i < numCPUs && i < 8; i++) {
        cluster.fork();
    }

    my_array.push('test');

    cluster.on('exit', function(worker, code, signal) {
        console.log('worker ' + worker.process.pid + ' died');
    });
} else {
    setInterval(function() {
        console.log(my_array); // my_array is always empty
    }, 500);
}

how do i define variables that can be shared between master and clusters?


问:
Trouble with detecting gestures over ListView
I have an Activity that contains a ViewFlipper.  The ViewFlipper includes 2 layouts, both of which are essentially just ListViews.

So the idea here is that I have two lists and to navigate from one to the other I would use a horizontal swipe.

I have that working.  However, what ever list item your finger is on when the swipe begins executing, that item will also be long-clicked.

Here is the relevant code I have:

```<code>public class MyActivity extends Activity implements OnItemClickListener, OnClickListener {

    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;

    private GestureDetector mGestureDetector;
    View.OnTouchListener mGestureListener;

    class MyGestureDetector extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                    return false;
                // right to left swipe
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    if (mCurrentScreen != SCREEN_SECONDLIST) {
                        mCurrentScreen = SCREEN_SECONDLIST;
                        mFlipper.setInAnimation(inFromRightAnimation());
                        mFlipper.setOutAnimation(outToLeftAnimation());
                        mFlipper.showNext();
                        updateNavigationBar();
                    }
                }
                else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    if (mCurrentScreen != SCREEN_FIRSTLIST) {
                        mCurrentScreen = SCREEN_FIRSTLIST;
                        mFlipper.setInAnimation(inFromLeftAnimation());
                        mFlipper.setOutAnimation(outToRightAnimation());
                        mFlipper.showPrevious();
                        updateNavigationBar();
                    }
                }
            } catch (Exception e) {
                // nothing
            }
            return true;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mGestureDetector.onTouchEvent(event))
            return true;
        else
            return false;
    }

    ViewFlipper mFlipper;

    private int mCurrentScreen = SCREEN_FIRSTLIST;

    private ListView mList1;
    private ListView mList2;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.layout_flipper);

        mFlipper = (ViewFlipper) findViewById(R.id.flipper);

        mGestureDetector = new GestureDetector(new MyGestureDetector());
        mGestureListener = new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (mGestureDetector.onTouchEvent(event)) {
                    return true;
                }
                return false;
            }
        };

        // set up List1 screen

        mList1List = (ListView)findViewById(R.id.list1);
        mList1List.setOnItemClickListener(this);
        mList1List.setOnTouchListener(mGestureListener);

        // set up List2 screen
        mList2List = (ListView)findViewById(R.id.list2);
        mList2List.setOnItemClickListener(this);
        mList2List.setOnTouchListener(mGestureListener);

    }

    …
}
</code>```

If I change the "return true;" statement from the GestureDetector to "return false;", I do not get long-clicks.  Unfortunately, I get regular clicks.

Does anyone know how I can get around this?

答:
Go you your gestureDetector and set

```<code> mGestureDetector.setIsLongpressEnabled(false);
</code>```

This will prevent long press events from being detected.

ContentLicense: CC BY-SA 2.5

Body:
I have an Activity that contains a ViewFlipper.  The ViewFlipper includes 2 layouts, both of which are essentially just ListViews.

So the idea here is that I have two lists and to navigate from one to the other I would use a horizontal swipe.

I have that working.  However, what ever list item your finger is on when the swipe begins executing, that item will also be long-clicked.

Here is the relevant code I have:

public class MyActivity extends Activity implements OnItemClickListener, OnClickListener {

    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;

    private GestureDetector mGestureDetector;
    View.OnTouchListener mGestureListener;

    class MyGestureDetector extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                    return false;
                // right to left swipe
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    if (mCurrentScreen != SCREEN_SECONDLIST) {
                        mCurrentScreen = SCREEN_SECONDLIST;
                        mFlipper.setInAnimation(inFromRightAnimation());
                        mFlipper.setOutAnimation(outToLeftAnimation());
                        mFlipper.showNext();
                        updateNavigationBar();
                    }
                }
                else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    if (mCurrentScreen != SCREEN_FIRSTLIST) {
                        mCurrentScreen = SCREEN_FIRSTLIST;
                        mFlipper.setInAnimation(inFromLeftAnimation());
                        mFlipper.setOutAnimation(outToRightAnimation());
                        mFlipper.showPrevious();
                        updateNavigationBar();
                    }
                }
            } catch (Exception e) {
                // nothing
            }
            return true;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mGestureDetector.onTouchEvent(event))
            return true;
        else
            return false;
    }

    ViewFlipper mFlipper;

    private int mCurrentScreen = SCREEN_FIRSTLIST;

    private ListView mList1;
    private ListView mList2;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.layout_flipper);

        mFlipper = (ViewFlipper) findViewById(R.id.flipper);

        mGestureDetector = new GestureDetector(new MyGestureDetector());
        mGestureListener = new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (mGestureDetector.onTouchEvent(event)) {
                    return true;
                }
                return false;
            }
        };

        // set up List1 screen

        mList1List = (ListView)findViewById(R.id.list1);
        mList1List.setOnItemClickListener(this);
        mList1List.setOnTouchListener(mGestureListener);

        // set up List2 screen
        mList2List = (ListView)findViewById(R.id.list2);
        mList2List.setOnItemClickListener(this);
        mList2List.setOnTouchListener(mGestureListener);

    }

    …
}

If I change the "return true;" statement from the GestureDetector to "return false;", I do not get long-clicks.  Unfortunately, I get regular clicks.

Does anyone know how I can get around this?

Body:
Go you your gestureDetector and set

 mGestureDetector.setIsLongpressEnabled(false);

This will prevent long press events from being detected.


问:
How to prevent Idle Timeout in IIS Application Pool on a shared host
I have my ASP.Net application uploaded on a shared host (godaddy plesk windows server). The Idle timeout on the shared host is set to 5 minutes and cannot be changed.

I have heard that the session timer can be reset by pinging the server before the timeout period has elapsed and I am trying to do this but my code doesn't seem to work. I am using this as a guideline:

Keeping ASP.NET Session Open / Alive (The post by Maryan)
and

https://gist.github.com/KyleMit/aa4f576fa32bf36fbedab5540c18211d

Basically in my Home controller I have put this code:

```<code> [HttpPost]
 public JsonResult KeepSessionAlive()
 {
     return new JsonResult {Data = "Success"};
 }
</code>```

In my Scripts folder I have put this script titled SessionUpdater.js

```<code> SessionUpdater = (function () {
var clientMovedSinceLastTimeout = true; //I want it to be always on so if statement fires
var keepSessionAliveUrl = null;
var timeout = 1 * 1000 * 60; // 1 minutes

function setupSessionUpdater(actionUrl) {
    // store local value
    keepSessionAliveUrl = actionUrl;
    // setup handlers
    listenForChanges();
    // start timeout - it'll run after n minutes
    checkToKeepSessionAlive();
}

function listenForChanges() {
    $("body").one("mousemove keydown", function () {
        clientMovedSinceLastTimeout = true;
    });
}
// fires every n minutes - if there's been movement ping server and restart timer
function checkToKeepSessionAlive() {
    setTimeout(function () { keepSessionAlive(); }, timeout);
}

function keepSessionAlive() {
    // if we've had any movement since last run, ping the server
    if (clientMovedSinceLastTimeout == true) {
        $.ajax({
            type: "POST",
            url: keepSessionAliveUrl,
            success: function (data) {
                // reset movement flag
                clientMovedSinceLastTimeout = true; //always on
                // start listening for changes again
                listenForChanges();
                // restart timeout to check again in n minutes
                checkToKeepSessionAlive();

            },
            error: function (data) {
                console.log("Error posting to " & keepSessionAliveUrl);
            }
        });
    }
}

// export setup method
return {
    Setup: setupSessionUpdater
};
 })();
</code>```

And then in both my layout page and in my home\index page (in case partial view doesnt work for some reason) I put this reference:

```<code> <script type="text/javascript">
// initialize Session Updater on page
SetupSessionUpdater('/Home/KeepSessionAlive');
SessionUpdater.Setup('@Url.Action("KeepSessionAlive","Home")');
 </script>
</code>```

My Problem is that despite doing this the session still logs me out every 5 minutes of being idle and I can tell that the app pool recycles because the website takes forever to fire up again. What am I doing wrong? How can I get this to stop logging me out.

Any information or being pointed in the right direction is appreciated.

答: As an alternative, you can use an external uptime monitor service to continuously query your website with GET requests, which will also keep it alive. Most uptime monitors don't actually send requests, however the Availability feature in Application Insights does and works perfectly for this.

Body:
I have my ASP.Net application uploaded on a shared host (godaddy plesk windows server). The Idle timeout on the shared host is set to 5 minutes and cannot be changed.

I have heard that the session timer can be reset by pinging the server before the timeout period has elapsed and I am trying to do this but my code doesn't seem to work. I am using this as a guideline:

Keeping ASP.NET Session Open / Alive (The post by Maryan)
and

https://gist.github.com/KyleMit/aa4f576fa32bf36fbedab5540c18211d

Basically in my Home controller I have put this code:

 [HttpPost]
 public JsonResult KeepSessionAlive()
 {
     return new JsonResult {Data = "Success"};
 }

In my Scripts folder I have put this script titled SessionUpdater.js

 SessionUpdater = (function () {
var clientMovedSinceLastTimeout = true; //I want it to be always on so if statement fires
var keepSessionAliveUrl = null;
var timeout = 1 * 1000 * 60; // 1 minutes

function setupSessionUpdater(actionUrl) {
    // store local value
    keepSessionAliveUrl = actionUrl;
    // setup handlers
    listenForChanges();
    // start timeout - it'll run after n minutes
    checkToKeepSessionAlive();
}

function listenForChanges() {
    $("body").one("mousemove keydown", function () {
        clientMovedSinceLastTimeout = true;
    });
}
// fires every n minutes - if there's been movement ping server and restart timer
function checkToKeepSessionAlive() {
    setTimeout(function () { keepSessionAlive(); }, timeout);
}

function keepSessionAlive() {
    // if we've had any movement since last run, ping the server
    if (clientMovedSinceLastTimeout == true) {
        $.ajax({
            type: "POST",
            url: keepSessionAliveUrl,
            success: function (data) {
                // reset movement flag
                clientMovedSinceLastTimeout = true; //always on
                // start listening for changes again
                listenForChanges();
                // restart timeout to check again in n minutes
                checkToKeepSessionAlive();

            },
            error: function (data) {
                console.log("Error posting to " & keepSessionAliveUrl);
            }
        });
    }
}

// export setup method
return {
    Setup: setupSessionUpdater
};
 })();

And then in both my layout page and in my home\index page (in case partial view doesnt work for some reason) I put this reference:

My Problem is that despite doing this the session still logs me out every 5 minutes of being idle and I can tell that the app pool recycles because the website takes forever to fire up again. What am I doing wrong? How can I get this to stop logging me out.

Any information or being pointed in the right direction is appreciated.


问:
Liferay Service Builder
First i had download Liferay with Eclipse. I had create a Liferay project and i add a service.xml in my portlet (in my project Liferay) to use Service Builder.
When i click on Build Service button (look image) Button Build Service

I have that error :
`

```<code>[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Build Order:
[INFO]
[INFO] Net'COFILMO - Pom parent
[INFO] Net'AVEO - Portlets - Pom parent
[INFO] app_chequier
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Net'COFILMO - Pom parent 1.0.0.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] Net'COFILMO - Pom parent ........................... FAILURE [  0.002 s]
[INFO] Net'AVEO - Portlets - Pom parent ................... SKIPPED
[INFO] app_chequier ....................................... SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.206 s
[INFO] Finished at: 2017-11-16T14:13:33+01:00
[INFO] Final Memory: 6M/77M
[INFO] ------------------------------------------------------------------------
[ERROR] Unknown lifecycle phase "build-service". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/LifecyclePhaseNotFoundException
</code>```

`

I don't know how i can resolve the problem.

Thanks in advance.

答:
```<code>I use the Liferay version 7 and that it's my POM.xml

`<?xml version="1.0"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.utlimate</groupId>
    <artifactId>UltimateTesting</artifactId>
    <packaging>pom</packaging>
    <name>UltimateTesting</name>
    <version>1.0.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>com.liferay</groupId>
                <artifactId>com.liferay.portal.tools.service.builder</artifactId>
                <version>1.0.175</version>
            </plugin>
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <modules>
        <module>UltimateTesting-portlet</module>
        <module>UltimateTesting-portlet-service</module>
    </modules>
 </project>`
</code>```

Title: Liferay Service Builder

Body:
First i had download Liferay with Eclipse. I had create a Liferay project and i add a service.xml in my portlet (in my project Liferay) to use Service Builder.
When i click on Build Service button (look image) Button Build Service

I have that error :
`

[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Build Order:
[INFO]
[INFO] Net'COFILMO - Pom parent
[INFO] Net'AVEO - Portlets - Pom parent
[INFO] app_chequier
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Net'COFILMO - Pom parent 1.0.0.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] Net'COFILMO - Pom parent ........................... FAILURE [  0.002 s]
[INFO] Net'AVEO - Portlets - Pom parent ................... SKIPPED
[INFO] app_chequier ....................................... SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.206 s
[INFO] Finished at: 2017-11-16T14:13:33+01:00
[INFO] Final Memory: 6M/77M
[INFO] ------------------------------------------------------------------------
[ERROR] Unknown lifecycle phase "build-service". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/LifecyclePhaseNotFoundException

`

I don't know how i can resolve the problem.

Thanks in advance.


问:
jni-wrapper-to-openssl-AES_encrypt-not-working
I am trying to encrypt and decrypt the file by using android open ssl.
Below sharing the JNI wrapper for the same.

```<code>JNIEXPORT jbyteArray JNICALL
Java_com_example_MainActivity_AESencrypt( JNIEnv* env, jobject thiz, jint
length, jbyteArray jarrByte)
{
unsigned char plaintext[AES_BLOCK_SIZE * 4];
unsigned char ciphertext[AES_BLOCK_SIZE * 4];
unsigned char checktext[AES_BLOCK_SIZE * 4];
const unsigned char userKey[AES_BLOCK_SIZE * 4] = "123456";
const int bits = 128;
AES_KEY keyin = { { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0,
                    0,
                    0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, }, 12 };
AES_KEY *key = &keyin;
jbyte* pJbyte = env->GetByteArrayElements(jarrByte, NULL);
if(pJbyte!=NULL){
   memcpy(plaintext, pJbyte, length);
   env->ReleaseByteArrayElements(jarrByte, pJbyte, JNI_ABORT);
}
unsigned char* beforeEncrypt = &plaintext[0];
unsigned char* afterEncrypt = &ciphertext[0];
AES_set_encrypt_key(userKey, bits, key);
AES_encrypt(beforeEncrypt, afterEncrypt, key);
jbyteArray jarrRet = env->NewByteArray(strlen((char*) ciphertext));
env->SetByteArrayRegion(jarrRet, 0, strlen((char*) ciphertext), (jbyte *) ciphertext);
return jarrRet;
}

JNIEXPORT jbyteArray JNICALL
Java_com_example_MainActivity_AESdecrypt( JNIEnv* env, jobject thiz, jint
length, jbyteArray jarrByte)
{
 unsigned char encryptText[AES_BLOCK_SIZE * 4];
 unsigned char ciphertext[AES_BLOCK_SIZE * 4];
 unsigned char checktext[AES_BLOCK_SIZE * 4];
 const unsigned char userKey[AES_BLOCK_SIZE * 4] = "123456";
 const int bits = 128;
AES_KEY keyin = { { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0,
                    0,
                    0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, }, 12 };
AES_KEY *key = &keyin;
jbyte* pJbyte = env->GetByteArrayElements(jarrByte, NULL);
if(pJbyte!=NULL){
    memcpy(encryptText, pJbyte, length);
    env->ReleaseByteArrayElements(jarrByte, pJbyte, JNI_ABORT);
}

unsigned char* beforeDecrypt = &encryptText[0];
unsigned char* afterDecrypt = &ciphertext[0];
AES_set_decrypt_key(userKey, bits, key);
AES_decrypt(beforeDecrypt, afterDecrypt, key);

jbyteArray jarrRet = env->NewByteArray(strlen((char*) ciphertext));
env->SetByteArrayRegion(jarrRet, 0, strlen((char*) ciphertext), (jbyte *) ciphertext);
return jarrRet;
}
</code>```

I am calling JNI methods as below.

```<code>Mainactivity.java :
   public void jni_encryption_and_decryption {

                    // reads the file and converts into bytes
                    plainTextBytes = getBytesFromInputFile();
                    len = plainTextBytes.length;

                    // encrypts the plain text and returns the encrypted bytes
                    byte[] encryptedByte = AESencrypt(len, plainTextBytes);
                    String encryptString = new String(encryptedByte);
                    encrypt.setText(encryptString);

                    len = encryptedByte.length;
                    // decrypts encrypted bytes and returns the decrypted bytes
                    decryptedByte = AESdecrypt(len, encryptedByte);
                    String decryptString = new String(decryptedByte);
                    decrypt.setText(decryptString);
      }
</code>```

Encryption is working fine but while decryption, junk is coming and also If the file contains more plain text, it is not decryting complete plain text.

Input from File: This is an android openssl encryption and decryption demo

Encryption Text: �UZ�L\n�c�������a��[���ܰ�h�ܰ�ܰ0_��

Decryption Text: This is an andro�ܰ���0_�!

I also shared bytes before and after encryption. Till 15th index bytes are same. after that bytes are found not same.

What is wrong in Jni Wrapper? Am I missing anything? Please help.

```<code>JNIEXPORT jbyteArray JNICALL
Java_com_example_MainActivity_doEncryption(jbyteArray data_plaintext, int
plaintext_len, jbyteArray data_key,
        jbyteArray data_iv, jbyteArray data_ciphertext)
{
unsigned char* key = (unsigned char*) data_key;
unsigned char* iv = (unsigned char*) data_iv;
unsigned char* plaintext =  (unsigned char*) data_plaintext;
unsigned char* ciphertext =  (unsigned char*) data_ciphertext;
EVP_CIPHER_CTX *ctx;

int len;

int ciphertext_len;

/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new())){
    ERR_print_errors_fp(stderr);
    abort();
}

/* Initialise the encryption operation. IMPORTANT - ensure you use a key
 * and IV size appropriate for your cipher
 * In this example we are using 256 bit AES (i.e. a 256 bit key). The
 * IV size for *most* modes is the same as the block size. For AES this
 * is 128 bits */
if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv)){
    ERR_print_errors_fp(stderr);
    abort();
}

/* Provide the message to be encrypted, and obtain the encrypted output.
 * EVP_EncryptUpdate can be called multiple times if necessary
 */
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)){
    ERR_print_errors_fp(stderr);
    abort();
}
ciphertext_len = len;

/* Finalise the encryption. Further ciphertext bytes may be written at
 * this stage.
 */
if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)){
    ERR_print_errors_fp(stderr);
    abort();
}
ciphertext_len += len;

/* Clean up */
EVP_CIPHER_CTX_free(ctx);
jbyteArray  ciphertext_copy = (jbyteArray ) ciphertext;

return ciphertext_copy;
}
</code>```

Below sharing the error details:

Error Details :
     * What went wrong:
Execution failed for task ':app:externalNativeBuildDebug'.

Build command failed.
  Error while executing process C:\android\sdk\cmake\3.6.4111459\bin\cmake.exe with arguments {--build C:\Users\SampleJni\app.externalNativeBuild\cmake\debug\armeabi-v7a --target native-lib}
  [1/1] Linking CXX shared library ........\build\intermediates\cmake\debug\obj\armeabi-v7a\libnative-lib.so
  FAILED: cmd.exe /C "cd . && C:\android\sdk\ndk-bundle\toolchains\llvm\prebuilt\windows-x86_64\bin\clang++.exe  --target=armv7-none-linux-androideabi --gcc-toolchain=C:/android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/prebuilt/windows-x86_64 --sysroot=C:/android/sdk/ndk-bundle/sysroot -fPIC -isystem C:/android/sdk/ndk-bundle/sysroot/usr/include/arm-linux-androideabi -D__ANDROID_API__=14 -g -DANDROID -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16 -fno-integrated-as -mthumb -Wa,--noexecstack -Wformat -Werror=format-security   -O0 -fno-limit-debug-info  -Wl,--exclude-libs,libgcc.a --sysroot C:/android/sdk/ndk-bundle/platforms/android-14/arch-arm -Wl,--build-id -Wl,--warn-shared-textrel -Wl,--fatal-warnings -Wl,--fix-cortex-a8 -Wl,--no-undefined -Wl,-z,noexecstack -Qunused-arguments -Wl,-z,relro -Wl,-z,now -shared -Wl,-soname,libnative-lib.so -o ........\build\intermediates\cmake\debug\obj\armeabi-v7a\libnative-lib.so CMakeFiles/native-lib.dir/src/main/cpp/native-lib.cpp.o  ../../../../openssl-armeabi-v7a/lib/libcrypto.a ../../../../openssl-armeabi-v7a/lib/libssl.a -llog -lm "C:/android/sdk/ndk-bundle/sources/cxx-stl/gnu-libstdc++/4.9/libs/armeabi-v7a/libgnustl_static.a" && cd ."
  ../../../../openssl-armeabi-v7a/lib/libcrypto.a(ui_openssl.o):ui_openssl.c:function read_string_inner: error: undefined reference to 'signal'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(ui_openssl.o):ui_openssl.c:function read_string_inner: error: undefined reference to 'tcsetattr'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(ui_openssl.o):ui_openssl.c:function read_string_inner: error: undefined reference to 'tcsetattr'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(ui_openssl.o):ui_openssl.c:function open_console: error: undefined reference to 'tcgetattr'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function zlib_stateful_expand_block: error: undefined reference to 'inflate'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function zlib_stateful_compress_block: error: undefined reference to 'deflate'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function bio_zlib_free: error: undefined reference to 'inflateEnd'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function bio_zlib_free: error: undefined reference to 'deflateEnd'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function zlib_stateful_finish: error: undefined reference to 'inflateEnd'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function zlib_stateful_finish: error: undefined reference to 'deflateEnd'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function zlib_stateful_init: error: undefined reference to 'inflateInit_'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function zlib_stateful_init: error: undefined reference to 'deflateInit_'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function bio_zlib_ctrl: error: undefined reference to 'deflate'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function bio_zlib_ctrl: error: undefined reference to 'zError'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function bio_zlib_write: error: undefined reference to 'deflate'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function bio_zlib_write: error: undefined reference to 'zError'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function bio_zlib_write: error: undefined reference to 'deflateInit_'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function bio_zlib_read: error: undefined reference to 'inflate'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function bio_zlib_read: error: undefined reference to 'zError'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function bio_zlib_read: error: undefined reference to 'inflateInit_'
    clang++.exe: error: linker command failed with exit code 1 (use -v to see invocation)
    ninja: build stopped: subcommand failed.

答:
AES is a block cipher, the block length is 16 bytes. The issue here is that aes_encrypt() and aes_decrypt() are lowlevel-functions, which only operate on a single block (didn't you wonder, why there was no length-parameter?). So, you only encrypted and decrypted 16 bytes of your demo string, the rest of the decryption buffer remained unintialized!

So you should either iterate for operating on more blocks, or use a higher-level interface like the EVP-functionfamily. A good primer is the OpenSSL Wiki

In both cases you should furthermore implement proper padding according to PKCS#7.

Body:
I am trying to encrypt and decrypt the file by using android open ssl.
Below sharing the JNI wrapper for the same.

JNIEXPORT jbyteArray JNICALL
Java_com_example_MainActivity_AESencrypt( JNIEnv* env, jobject thiz, jint
length, jbyteArray jarrByte)
{
unsigned char plaintext[AES_BLOCK_SIZE * 4];
unsigned char ciphertext[AES_BLOCK_SIZE * 4];
unsigned char checktext[AES_BLOCK_SIZE * 4];
const unsigned char userKey[AES_BLOCK_SIZE * 4] = "123456";
const int bits = 128;
AES_KEY keyin = { { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0,
                    0,
                    0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, }, 12 };
AES_KEY *key = &keyin;
jbyte* pJbyte = env->GetByteArrayElements(jarrByte, NULL);
if(pJbyte!=NULL){
   memcpy(plaintext, pJbyte, length);
   env->ReleaseByteArrayElements(jarrByte, pJbyte, JNI_ABORT);
}
unsigned char* beforeEncrypt = &plaintext[0];
unsigned char* afterEncrypt = &ciphertext[0];
AES_set_encrypt_key(userKey, bits, key);
AES_encrypt(beforeEncrypt, afterEncrypt, key);
jbyteArray jarrRet = env->NewByteArray(strlen((char*) ciphertext));
env->SetByteArrayRegion(jarrRet, 0, strlen((char*) ciphertext), (jbyte *) ciphertext);
return jarrRet;
}

JNIEXPORT jbyteArray JNICALL
Java_com_example_MainActivity_AESdecrypt( JNIEnv* env, jobject thiz, jint
length, jbyteArray jarrByte)
{
 unsigned char encryptText[AES_BLOCK_SIZE * 4];
 unsigned char ciphertext[AES_BLOCK_SIZE * 4];
 unsigned char checktext[AES_BLOCK_SIZE * 4];
 const unsigned char userKey[AES_BLOCK_SIZE * 4] = "123456";
 const int bits = 128;
AES_KEY keyin = { { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0,
                    0,
                    0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, }, 12 };
AES_KEY *key = &keyin;
jbyte* pJbyte = env->GetByteArrayElements(jarrByte, NULL);
if(pJbyte!=NULL){
    memcpy(encryptText, pJbyte, length);
    env->ReleaseByteArrayElements(jarrByte, pJbyte, JNI_ABORT);
}

unsigned char* beforeDecrypt = &encryptText[0];
unsigned char* afterDecrypt = &ciphertext[0];
AES_set_decrypt_key(userKey, bits, key);
AES_decrypt(beforeDecrypt, afterDecrypt, key);

jbyteArray jarrRet = env->NewByteArray(strlen((char*) ciphertext));
env->SetByteArrayRegion(jarrRet, 0, strlen((char*) ciphertext), (jbyte *) ciphertext);
return jarrRet;
}

I am calling JNI methods as below.

Mainactivity.java :
   public void jni_encryption_and_decryption {

                    // reads the file and converts into bytes
                    plainTextBytes = getBytesFromInputFile();
                    len = plainTextBytes.length;

                    // encrypts the plain text and returns the encrypted bytes
                    byte[] encryptedByte = AESencrypt(len, plainTextBytes);
                    String encryptString = new String(encryptedByte);
                    encrypt.setText(encryptString);

                    len = encryptedByte.length;
                    // decrypts encrypted bytes and returns the decrypted bytes
                    decryptedByte = AESdecrypt(len, encryptedByte);
                    String decryptString = new String(decryptedByte);
                    decrypt.setText(decryptString);
      }

Encryption is working fine but while decryption, junk is coming and also If the file contains more plain text, it is not decryting complete plain text.

Input from File: This is an android openssl encryption and decryption demo

Encryption Text: �UZ�L\n�c�������a��[���ܰ�h�ܰ�ܰ0_��

Decryption Text: This is an andro�ܰ���0_�!

I also shared bytes before and after encryption. Till 15th index bytes are same. after that bytes are found not same.

What is wrong in Jni Wrapper? Am I missing anything? Please help.

JNIEXPORT jbyteArray JNICALL
Java_com_example_MainActivity_doEncryption(jbyteArray data_plaintext, int
plaintext_len, jbyteArray data_key,
        jbyteArray data_iv, jbyteArray data_ciphertext)
{
unsigned char* key = (unsigned char*) data_key;
unsigned char* iv = (unsigned char*) data_iv;
unsigned char* plaintext =  (unsigned char*) data_plaintext;
unsigned char* ciphertext =  (unsigned char*) data_ciphertext;
EVP_CIPHER_CTX *ctx;

int len;

int ciphertext_len;

/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new())){
    ERR_print_errors_fp(stderr);
    abort();
}

/* Initialise the encryption operation. IMPORTANT - ensure you use a key
 * and IV size appropriate for your cipher
 * In this example we are using 256 bit AES (i.e. a 256 bit key). The
 * IV size for *most* modes is the same as the block size. For AES this
 * is 128 bits */
if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv)){
    ERR_print_errors_fp(stderr);
    abort();
}

/* Provide the message to be encrypted, and obtain the encrypted output.
 * EVP_EncryptUpdate can be called multiple times if necessary
 */
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len)){
    ERR_print_errors_fp(stderr);
    abort();
}
ciphertext_len = len;

/* Finalise the encryption. Further ciphertext bytes may be written at
 * this stage.
 */
if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)){
    ERR_print_errors_fp(stderr);
    abort();
}
ciphertext_len += len;

/* Clean up */
EVP_CIPHER_CTX_free(ctx);
jbyteArray  ciphertext_copy = (jbyteArray ) ciphertext;

return ciphertext_copy;
}

Below sharing the error details:

Error Details :
     * What went wrong:
Execution failed for task ':app:externalNativeBuildDebug'.

Build command failed.
  Error while executing process C:\android\sdk\cmake\3.6.4111459\bin\cmake.exe with arguments {--build C:\Users\SampleJni\app.externalNativeBuild\cmake\debug\armeabi-v7a --target native-lib}
  [1/1] Linking CXX shared library ........\build\intermediates\cmake\debug\obj\armeabi-v7a\libnative-lib.so
  FAILED: cmd.exe /C "cd . && C:\android\sdk\ndk-bundle\toolchains\llvm\prebuilt\windows-x86_64\bin\clang++.exe  --target=armv7-none-linux-androideabi --gcc-toolchain=C:/android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/prebuilt/windows-x86_64 --sysroot=C:/android/sdk/ndk-bundle/sysroot -fPIC -isystem C:/android/sdk/ndk-bundle/sysroot/usr/include/arm-linux-androideabi -D__ANDROID_API__=14 -g -DANDROID -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16 -fno-integrated-as -mthumb -Wa,--noexecstack -Wformat -Werror=format-security   -O0 -fno-limit-debug-info  -Wl,--exclude-libs,libgcc.a --sysroot C:/android/sdk/ndk-bundle/platforms/android-14/arch-arm -Wl,--build-id -Wl,--warn-shared-textrel -Wl,--fatal-warnings -Wl,--fix-cortex-a8 -Wl,--no-undefined -Wl,-z,noexecstack -Qunused-arguments -Wl,-z,relro -Wl,-z,now -shared -Wl,-soname,libnative-lib.so -o ........\build\intermediates\cmake\debug\obj\armeabi-v7a\libnative-lib.so CMakeFiles/native-lib.dir/src/main/cpp/native-lib.cpp.o  ../../../../openssl-armeabi-v7a/lib/libcrypto.a ../../../../openssl-armeabi-v7a/lib/libssl.a -llog -lm "C:/android/sdk/ndk-bundle/sources/cxx-stl/gnu-libstdc++/4.9/libs/armeabi-v7a/libgnustl_static.a" && cd ."
  ../../../../openssl-armeabi-v7a/lib/libcrypto.a(ui_openssl.o):ui_openssl.c:function read_string_inner: error: undefined reference to 'signal'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(ui_openssl.o):ui_openssl.c:function read_string_inner: error: undefined reference to 'tcsetattr'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(ui_openssl.o):ui_openssl.c:function read_string_inner: error: undefined reference to 'tcsetattr'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(ui_openssl.o):ui_openssl.c:function open_console: error: undefined reference to 'tcgetattr'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function zlib_stateful_expand_block: error: undefined reference to 'inflate'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function zlib_stateful_compress_block: error: undefined reference to 'deflate'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function bio_zlib_free: error: undefined reference to 'inflateEnd'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function bio_zlib_free: error: undefined reference to 'deflateEnd'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function zlib_stateful_finish: error: undefined reference to 'inflateEnd'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function zlib_stateful_finish: error: undefined reference to 'deflateEnd'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function zlib_stateful_init: error: undefined reference to 'inflateInit_'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function zlib_stateful_init: error: undefined reference to 'deflateInit_'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function bio_zlib_ctrl: error: undefined reference to 'deflate'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function bio_zlib_ctrl: error: undefined reference to 'zError'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function bio_zlib_write: error: undefined reference to 'deflate'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function bio_zlib_write: error: undefined reference to 'zError'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function bio_zlib_write: error: undefined reference to 'deflateInit_'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function bio_zlib_read: error: undefined reference to 'inflate'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function bio_zlib_read: error: undefined reference to 'zError'
    ../../../../openssl-armeabi-v7a/lib/libcrypto.a(c_zlib.o):c_zlib.c:function bio_zlib_read: error: undefined reference to 'inflateInit_'
    clang++.exe: error: linker command failed with exit code 1 (use -v to see invocation)
    ninja: build stopped: subcommand failed.


问:
How to GROUP BY eloquent in <select>
I want to have unique mounths in SELECT. I find out i have to use GROUP BY. But it doesnt work this way:

```<code> @foreach($months as $month)
       <option value="{{ $month->id }}">{{ Carbon\Carbon::parse($month
->date)
->format(' F ')
->groupBy('date') }}</option>
 @endforeach
</code>```

How to use groupBy in this way? Because it looks like this right now without GROUP BY:

My Laravel Controller:

```<code>public function index()
{
    $users = User::all(['name', 'id']);
    $months = RouteInfo::all(['date', 'id']);

    return view('admin.index', compact('users', $users, 'months', $months));
}
</code>```

Thank you for your help

答:
You need just filter items before show</p>

```<code>@php
$uniqueMonth = [];
  foreach($months as $key=>$month){
     $month = Carbon\Carbon::parse($month->date);
     $uniqueMonth[$month->format('m')] = $month->format(' F ');
  }
  ksort($uniqueMonth); // sorting months
@endphp

@foreach($uniqueMonth as $key=>$month)
   <option value="{{ $key }}">{{ $month }}</option>
@endforeach
</code>```

Title: How to GROUP BY eloquent in <select>

Body:
I want to have unique mounths in SELECT. I find out i have to use GROUP BY. But it doesnt work this way:

 @foreach($months as $month)
       <option value="{{ $month->id }}">{{ Carbon\Carbon::parse($month
->date)
->format(' F ')
->groupBy('date') }}</option>
 @endforeach

How to use groupBy in this way? Because it looks like this right now without GROUP BY:

My Laravel Controller:

public function index()
{
    $users = User::all(['name', 'id']);
    $months = RouteInfo::all(['date', 'id']);

    return view('admin.index', compact('users', $users, 'months', $months));
}

Thank you for your help

Body:
You need just filter items before show

@php
$uniqueMonth = [];
  foreach($months as $key=>$month){
     $month = Carbon\Carbon::parse($month->date);
     $uniqueMonth[$month->format('m')] = $month->format(' F ');
  }
  ksort($uniqueMonth); // sorting months
@endphp

@foreach($uniqueMonth as $key=>$month)
   <option value="{{ $key }}">{{ $month }}</option>
@endforeach


问:
CSS background image only as nav bg
I want to set a background only for the listing items in a nav-bar. It should be continuous over all li's. The div container of the navigation is full width over the site. Is there any possibility to do this? I cannot work with margin in px, because the site has to be responsive.</p>

答:
For ex : If nav looks like this

```<code>   <div class="container">
    <nav class="navbar navbar-default navbar-custom" role="navigation">
        <div class="container-fluid">
          <!-- Brand and toggle get grouped for better mobile display -->
          <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
              <span class="sr-only">Toggle navigation</span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">Brand</a>
          </div>

          <!-- Collect the nav links, forms, and other content for toggling -->
          <div class="collapse navbar-collapse navbar-ex1-collapse">
            <ul class="nav navbar-nav">
              <li class="active"><a href="#">Link 1</a></li>
              <li><a href="#">Link 2</a></li>
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
                <ul class="dropdown-menu">
                  <li><a href="#">Action</a></li>
                  <li><a href="#">Another action</a></li>
                  <li><a href="#">Something else here</a></li>
                  <li><a href="#">Separated link</a></li>
                  <li><a href="#">One more separated link</a></li>
                </ul>
              </li>
            </ul>

            </div><!-- /.navbar-collapse -->
        </div>
    </nav>
</div>
</code>```

Use code :

```<code>.navbar{
  background: url('http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-169280.jpg');

}
</code>```

check this one
https://codepen.io/anon/pen/jaaaWm

Title: CSS background image only as nav bg

Body:
For ex : If nav looks like this

   <div class="container">
    <nav class="navbar navbar-default navbar-custom" role="navigation">
        <div class="container-fluid">
          <!-- Brand and toggle get grouped for better mobile display -->
          <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
              <span class="sr-only">Toggle navigation</span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
              <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">Brand</a>
          </div>

          <!-- Collect the nav links, forms, and other content for toggling -->
          <div class="collapse navbar-collapse navbar-ex1-collapse">
            <ul class="nav navbar-nav">
              <li class="active"><a href="#">Link 1</a></li>
              <li><a href="#">Link 2</a></li>
              <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
                <ul class="dropdown-menu">
                  <li><a href="#">Action</a></li>
                  <li><a href="#">Another action</a></li>
                  <li><a href="#">Something else here</a></li>
                  <li><a href="#">Separated link</a></li>
                  <li><a href="#">One more separated link</a></li>
                </ul>
              </li>
            </ul>

            </div><!-- /.navbar-collapse -->
        </div>
    </nav>
</div>

Use code :

.navbar{
  background: url('http://wallpapers.wallhaven.cc/wallpapers/full/wallhaven-169280.jpg');

}

check this one
https://codepen.io/anon/pen/jaaaWm


问:
Firebase quick start throws NoClassDefFoundError
I added the app to Firebase console and added google json file to app folder.
Then when I try to launch the app it crashes with the following message.

Thanks in Advance.

Error:

07-27 13:18:21.000 26362-26362/? E/AndroidRuntime: FATAL EXCEPTION:
  main
                                                     Process: com.google.samples.quickstart.config, PID: 26362
                                                     java.lang.NoClassDefFoundError: Failed resolution of:
  Lcom/google/android/gms/R$string;
                                                         at com.google.android.gms.common.internal.zzby.(Unknown Source)
                                                         at com.google.firebase.FirebaseOptions.fromResource(Unknown Source)
                                                         at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                         at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown
  Source)
                                                         at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
                                                         at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
                                                         at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown
  Source)
                                                         at android.app.ActivityThread.installProvider(ActivityThread.java:5855)
                                                         at android.app.ActivityThread.installContentProviders(ActivityThread.java:5447)
                                                         at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5386)
                                                         at android.app.ActivityThread.-wrap2(ActivityThread.java)
                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1546)
                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                         at android.os.Looper.loop(Looper.java:154)
                                                         at android.app.ActivityThread.main(ActivityThread.java:6121)
                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
                                                      Caused by: java.lang.ClassNotFoundException: Didn't find class
  "com.google.android.gms.R$string" on path: DexPathList[[zip file
  "/data/app/com.google.samples.quickstart.config-1/base.apk", zip file
  "/data/app/com.google.samples.quickstart.config-1/split_lib_dependencies_apk.apk"],nativeLibraryDirectories=[/data/app/com.google.samples.quickstart.config-1/lib/arm64,
  /system/lib64, /vendor/lib64]]
                                                         at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                         at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
                                                         at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
                                                         at com.google.android.gms.common.internal.zzby.(Unknown Source)
                                                         at com.google.firebase.FirebaseOptions.fromResource(Unknown Source)
                                                         at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                         at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown
  Source)
                                                         at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
                                                         at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
                                                         at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown
  Source)
                                                         at android.app.ActivityThread.installProvider(ActivityThread.java:5855)
                                                         at android.app.ActivityThread.installContentProviders(ActivityThread.java:5447)
                                                         at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5386)
                                                         at android.app.ActivityThread.-wrap2(ActivityThread.java)
                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1546)
                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                         at android.os.Looper.loop(Looper.java:154)
                                                         at android.app.ActivityThread.main(ActivityThread.java:6121)
                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

Gradle

```<code>apply plugin: 'com.android.application'
check.dependsOn 'assembleDebugAndroidTest'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"

    defaultConfig {
        applicationId "com.google.samples.quickstart.config"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

configurations.all {
    resolutionStrategy.force 'com.android.support:support-annotations:25.4.0'
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:25.4.0'

    compile 'com.google.firebase:firebase-config:11.0.1'

    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
    androidTestCompile 'com.android.support.test:runner:1.0.0'
    compile 'com.android.support:multidex:1.0.1'
}

apply plugin: 'com.google.gms.google-services'
</code>```

Manifest

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google.samples.quickstart.config" >

    <application
        android:allowBackup="true"
        android:name="android.support.multidex.MultiDexApplication"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

答: I solved this issue by first adding multidex and then clean the project and rebuilding it.</p>

Body:
I added the app to Firebase console and added google json file to app folder.
Then when I try to launch the app it crashes with the following message.

Thanks in Advance.

Error:

07-27 13:18:21.000 26362-26362/? E/AndroidRuntime: FATAL EXCEPTION:
  main
                                                     Process: com.google.samples.quickstart.config, PID: 26362
                                                     java.lang.NoClassDefFoundError: Failed resolution of:
  Lcom/google/android/gms/R$string;
                                                         at com.google.android.gms.common.internal.zzby.(Unknown Source)
                                                         at com.google.firebase.FirebaseOptions.fromResource(Unknown Source)
                                                         at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                         at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown
  Source)
                                                         at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
                                                         at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
                                                         at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown
  Source)
                                                         at android.app.ActivityThread.installProvider(ActivityThread.java:5855)
                                                         at android.app.ActivityThread.installContentProviders(ActivityThread.java:5447)
                                                         at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5386)
                                                         at android.app.ActivityThread.-wrap2(ActivityThread.java)
                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1546)
                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                         at android.os.Looper.loop(Looper.java:154)
                                                         at android.app.ActivityThread.main(ActivityThread.java:6121)
                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
                                                      Caused by: java.lang.ClassNotFoundException: Didn't find class
  "com.google.android.gms.R$string" on path: DexPathList[[zip file
  "/data/app/com.google.samples.quickstart.config-1/base.apk", zip file
  "/data/app/com.google.samples.quickstart.config-1/split_lib_dependencies_apk.apk"],nativeLibraryDirectories=[/data/app/com.google.samples.quickstart.config-1/lib/arm64,
  /system/lib64, /vendor/lib64]]
                                                         at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                         at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
                                                         at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
                                                         at com.google.android.gms.common.internal.zzby.(Unknown Source)
                                                         at com.google.firebase.FirebaseOptions.fromResource(Unknown Source)
                                                         at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                                                         at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown
  Source)
                                                         at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
                                                         at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
                                                         at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown
  Source)
                                                         at android.app.ActivityThread.installProvider(ActivityThread.java:5855)
                                                         at android.app.ActivityThread.installContentProviders(ActivityThread.java:5447)
                                                         at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5386)
                                                         at android.app.ActivityThread.-wrap2(ActivityThread.java)
                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1546)
                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                         at android.os.Looper.loop(Looper.java:154)
                                                         at android.app.ActivityThread.main(ActivityThread.java:6121)
                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)

Gradle

apply plugin: 'com.android.application'
check.dependsOn 'assembleDebugAndroidTest'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"

    defaultConfig {
        applicationId "com.google.samples.quickstart.config"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        multiDexEnabled true

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

configurations.all {
    resolutionStrategy.force 'com.android.support:support-annotations:25.4.0'
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:25.4.0'

    compile 'com.google.firebase:firebase-config:11.0.1'

    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
    androidTestCompile 'com.android.support.test:runner:1.0.0'
    compile 'com.android.support:multidex:1.0.1'
}

apply plugin: 'com.google.gms.google-services'

Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google.samples.quickstart.config" >

    <application
        android:allowBackup="true"
        android:name="android.support.multidex.MultiDexApplication"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>