问:
Extjs 6.2 treelist change selection dynamically
I am using treelist and I want to change dynamically my selection of navigation list on afterrender function.

```<code>Ext.create({
    xtype: 'treelist',
    reference: 'navigationTreeList',
    itemId: 'navigationTreeList',
    ui: 'nav',
    store: Ext.create('Ext.data.Store', {
        fields: [{
            name: 'text'
        }],
        root: {
            expanded: true,
            children: [{
                    text: 'Dashboard',
                    iconCls: 'x-fa fa-home',
                    rowCls: 'nav-tree-badge',
                    viewType: 'dashboardcei',
                    routeId: 'cei/dashboardcei',
                    leaf: true
                },
                {
                    text: 'Create Application',
                    iconCls: 'x-fa fa-send',
                    rowCls: 'nav-tree-badge',
                    routeId: 'cei/create-application',
                    viewType: 'create-application',
                    leaf: true
                },
                {
                    text: 'Application Status',
                    iconCls: 'x-fa fa-user',
                    routeId: 'cei/application-status',
                    viewType: 'application-status',
                    leaf: true
                }
            ]
        }
    }),
    width: 250,
    expanderFirst: false,
    expanderOnly: false,
    listeners: {
        afterrender: function(tree) {

            var selection = tree.getStore().getData().items[1]; // bydefault "create application page should be open instead of dashboard"
            tree.fireEvent('selectionchange', tree, selection);
        }
    }
});
</code>```

above is my experiment in render function to open "create application page" default on page load from treelist. its opening the page but the actual selection on treelist not happening like selection remains old that's the issue I was facing from last two day's can anyone please help me to solve the problem

答:
You need to use treelist.setSelection(record)) method for dynamic selection change of treelist.

As per your requirement, I have created a small SENCHA FIDDLE  demo. Hope this will help you or guide you to achieve your requirement.

```<code>Ext.create('Ext.panel.Panel', {
    layout: 'hbox',
    title: 'Navigation tree list example',
    renderTo: Ext.getBody(),
    border: 1,
    height: window.innerHeight,
    viewModel: {
        selection: null
    },
    style: {
        borderColor: '#ccc',
        borderStyle: 'solid',
        borderWidth: '1px'
    },
    items: [{
        xtype: 'treelist',
        flex: 0.30,
        store: {
            root: {
                expanded: true,
                children: [{
                    text: 'Dashboard',
                    id: 'dashboard',
                    iconCls: 'x-fa fa-home',
                    rowCls: 'nav-tree-badge',
                    viewType: 'dashboardcei',
                    routeId: 'cei/dashboardcei',
                    leaf: true
                }, {
                    text: 'Create Application',
                    id: 'createapp',
                    iconCls: 'x-fa fa-send',
                    rowCls: 'nav-tree-badge',
                    routeId: 'cei/create-application',
                    viewType: 'create-application',
                    leaf: true
                }, {
                    text: 'Application Status',
                    id: 'appstatus',
                    iconCls: 'x-fa fa-user',
                    routeId: 'cei/application-status',
                    viewType: 'application-status',
                    leaf: true
                }]
            }
        },
        listeners: {
            selectionchange: function (tree, node) {
                this.up('panel').getViewModel().set('selection', node);
            }
        }
    }, {
        margin: '10 0 0 0',
        flex: 0.70,
        height: '100%',
        bind: {
            title: '{selection.text}'
        },
        style: {
            borderColor: '#ccc',
            borderStyle: 'solid',
            borderWidth: '1px'
        },
        itemId: 'rightPanel'
    }],
    buttons: [{
        text: 'Dashboard',
        name: 'dashboard',
        handler: function () {
            this.up('panel').doSetNode(this);
        }
    }, {
        text: 'Create Application',
        name: 'createapp',
        handler: function () {
            this.up('panel').doSetNode(this);
        }
    }, {
        text: 'Application Status',
        name: 'appstatus',
        handler: function () {
            this.up('panel').doSetNode(this);
        }
    }],
    //function will fire on bottom button click
    doSetNode: function (button) {
        var tree = this.down('treelist'),
            newSelection = tree.getStore().findRecord('id', button.name);
        tree.setSelection(newSelection);
    }
});
</code>```

Body:
I am using treelist and I want to change dynamically my selection of navigation list on afterrender function.

Ext.create({
    xtype: 'treelist',
    reference: 'navigationTreeList',
    itemId: 'navigationTreeList',
    ui: 'nav',
    store: Ext.create('Ext.data.Store', {
        fields: [{
            name: 'text'
        }],
        root: {
            expanded: true,
            children: [{
                    text: 'Dashboard',
                    iconCls: 'x-fa fa-home',
                    rowCls: 'nav-tree-badge',
                    viewType: 'dashboardcei',
                    routeId: 'cei/dashboardcei',
                    leaf: true
                },
                {
                    text: 'Create Application',
                    iconCls: 'x-fa fa-send',
                    rowCls: 'nav-tree-badge',
                    routeId: 'cei/create-application',
                    viewType: 'create-application',
                    leaf: true
                },
                {
                    text: 'Application Status',
                    iconCls: 'x-fa fa-user',
                    routeId: 'cei/application-status',
                    viewType: 'application-status',
                    leaf: true
                }
            ]
        }
    }),
    width: 250,
    expanderFirst: false,
    expanderOnly: false,
    listeners: {
        afterrender: function(tree) {

            var selection = tree.getStore().getData().items[1]; // bydefault "create application page should be open instead of dashboard"
            tree.fireEvent('selectionchange', tree, selection);
        }
    }
});

above is my experiment in render function to open "create application page" default on page load from treelist. its opening the page but the actual selection on treelist not happening like selection remains old that's the issue I was facing from last two day's can anyone please help me to solve the problem

Body:
You need to use treelist.setSelection(record)) method for dynamic selection change of treelist.

As per your requirement, I have created a small SENCHA FIDDLE  demo. Hope this will help you or guide you to achieve your requirement.

Ext.create('Ext.panel.Panel', {
    layout: 'hbox',
    title: 'Navigation tree list example',
    renderTo: Ext.getBody(),
    border: 1,
    height: window.innerHeight,
    viewModel: {
        selection: null
    },
    style: {
        borderColor: '#ccc',
        borderStyle: 'solid',
        borderWidth: '1px'
    },
    items: [{
        xtype: 'treelist',
        flex: 0.30,
        store: {
            root: {
                expanded: true,
                children: [{
                    text: 'Dashboard',
                    id: 'dashboard',
                    iconCls: 'x-fa fa-home',
                    rowCls: 'nav-tree-badge',
                    viewType: 'dashboardcei',
                    routeId: 'cei/dashboardcei',
                    leaf: true
                }, {
                    text: 'Create Application',
                    id: 'createapp',
                    iconCls: 'x-fa fa-send',
                    rowCls: 'nav-tree-badge',
                    routeId: 'cei/create-application',
                    viewType: 'create-application',
                    leaf: true
                }, {
                    text: 'Application Status',
                    id: 'appstatus',
                    iconCls: 'x-fa fa-user',
                    routeId: 'cei/application-status',
                    viewType: 'application-status',
                    leaf: true
                }]
            }
        },
        listeners: {
            selectionchange: function (tree, node) {
                this.up('panel').getViewModel().set('selection', node);
            }
        }
    }, {
        margin: '10 0 0 0',
        flex: 0.70,
        height: '100%',
        bind: {
            title: '{selection.text}'
        },
        style: {
            borderColor: '#ccc',
            borderStyle: 'solid',
            borderWidth: '1px'
        },
        itemId: 'rightPanel'
    }],
    buttons: [{
        text: 'Dashboard',
        name: 'dashboard',
        handler: function () {
            this.up('panel').doSetNode(this);
        }
    }, {
        text: 'Create Application',
        name: 'createapp',
        handler: function () {
            this.up('panel').doSetNode(this);
        }
    }, {
        text: 'Application Status',
        name: 'appstatus',
        handler: function () {
            this.up('panel').doSetNode(this);
        }
    }],
    //function will fire on bottom button click
    doSetNode: function (button) {
        var tree = this.down('treelist'),
            newSelection = tree.getStore().findRecord('id', button.name);
        tree.setSelection(newSelection);
    }
});


来源: stackexchange

问:
Generate er diagram from Hibernate entity
I would like to generate ER diagram from Hibernate entities or Hibernate mapping. I have selected visual paradigm tool which provides this feature. I would like to know your feedback about visual paradigm or some other tools if you know which supports the above feature.</p>

答:
Single version of truth

Please do not use the entitys to modify the structure of the database:

if you add a non-null non-default column to a entity the database can not be changed if there are rows in that table because the initial value of that column can not be calculated.

If you add a fk to a table some values might have illegal references.
You do not like to have this problems in deployment.

Use the tools of db managers instead please and calculate the entitys from the db.

ContentLicense: CC BY-SA 3.0


问:
Need Help with Simple JavaScript
I need help with javascript. I need to create a hidden input with the name "keywords", and write a JS function that populates it with the values of the checked checkboxes when the form is submitted.

First, I had to change the "," to a "|" because that is the correct syntax for ExpressionEngine. But for some reason the search will not work if there is a "|" at the end.

So for example if I select three checkboxes the output to the hidden keyword box is Aberdeen|Harrisburg|Avon| and this will not work with the search, but if I manually enter Aberdeen|Harrisburg|Avon with no "|" at the end, the search will work.

So How can I change this line to not have a "|" at the end of the keywords
templateValues += checkBox.value + "|";

答:
```<code>function removeTrailingPipe(mytext){
  mytextarray=mytext.split('|');
  while(mytextarray[mytextarray.length-1]==''){
    mytextarray.slice(0,mytextarray.length-1);
  }
  return mytextarray.join('|');
}

mytext='red|green|blue|yellow|';
mytext=removeTrailingPipe(mytext);
</code>```

Title: Need Help with Simple JavaScript

ContentLicense: CC BY-SA 2.5


问:
PHP set value to php variable if variable store in database table
This is my Code

```<code>table_query
id query
1  SELECT * FROM TABLE WHERE date = "$loc_date"

 <?php
$q1 = 'SELECT query FROM table_query WHERE 1 LIMIT 1';
$result = execute q1;
$query = $result['query'];
    $loc_date = '2017-12-06';
    $loc_query = $query; //This query fetch from table. Not directly write on file
    execute query here
    ?>
</code>```

But I don't get any result after executing query.

答:
You have to write variable in double quotation single quote. </p>

```<code>$loc_date = '2017-12-06';
$loc_query = "SELECT * FROM TABLE WHERE date = '".$loc_date."'";
</code>```

Body:
This is my Code

table_query
id query
1  SELECT * FROM TABLE WHERE date = "$loc_date"

 <?php
$q1 = 'SELECT query FROM table_query WHERE 1 LIMIT 1';
$result = execute q1;
$query = $result['query'];
    $loc_date = '2017-12-06';
    $loc_query = $query; //This query fetch from table. Not directly write on file
    execute query here
    ?>

But I don't get any result after executing query.

Body:
You have to write variable in double quotation single quote.

$loc_date = '2017-12-06';
$loc_query = "SELECT * FROM TABLE WHERE date = '".$loc_date."'";


问:
Output the highest average using functions
I am supposed to create a function which receives the arrays as parameters and which searches for the student with the highest average of the 3 grades and return to main the location of the student in the array.

The 4 arrays are:
Student number(9 digits)
Math grade
Science grade
English grade

And finally, it's supposed to read the data from the file into the array.

File data is:

```<code>123456789
60
70
80
987654321
70
80
90
999888777
75
85
65
111222333
55
65
75
444555666
63
73
83
</code>```

I need help with how to read the file data using the arrays and functions.

This is what I have so far:

```<code>#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;

int findHighest(int Mgrade[5], int Sgrade1[5], int Egrade[5], long Snumber[5]);

main()
{
    int Mgrade[5], Sgrade[5], Egrade[5];
    long Snumber[5];

    char num_from_file;
    ifstream infile;
    char mystring[20];
    int grade;
    infile.open("testdata.txt", ios::in);

    if (infile)
    {

        cout<<"File opened successfully\n";
        {
            do
            {

                infile.get(mystring,21); //(example from other program)
                infile.ignore(80,'\n');// (what should go here instead)

                infile>> grade;//(example from other program)
                infile.ignore(80,'\n');// (what should go here instead)

                if (infile.eof())
                {
                    break;
                }

                cout<<mystring<<'\t'<<grade<<endl<<endl;
                //cout<<'\t'<<num_from_file<<endl;
            }
            while(1);
        }
    }
    else
    {
        cout<<"error opening file";
    }

    infile.close();

    return 0;
}
</code>```

答:
Simply use getline(), like this:

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

int main(void) {
    int Mgrade[5], Sgrade[5], Egrade[5];
    long Snumber[5];
    std::ifstream input("testdata.txt");
    int index = 0, counter = 0;
    for( std::string line; getline( input, line ); ) {
        if(counter == 4) {
            counter = 0;
            index++;
        }
        if(counter == 0) {
            Snumber[index] = std::stol(line);
        } else if(counter == 1) {
            Mgrade[index] = std::stoi(line);
        } else if(counter == 2) {
            Sgrade[index] = std::stoi(line);
        } else if(counter == 3) {
            Egrade[index] = std::stoi(line);
        }
        counter++;
    }
    return 0;
}
</code>```

The code reads the file (variable input in the code) line by line and uses a for loop to achieve that.

In every iteration of the loop, the variable line will contain the current line of the file that are we are reading. For example, in the first iteration, line will be equal to "123456789".

Now I use two integers, index and counter. The first is used to index the arrays, since we are reading the first student, we want to populate the first cell of every array (that would be an index equal to 0).

counter is used in order to keep track of how many lines are been read for the idnex-th student. We expect to read 4 lines for every student, so counter will be 0 when we read his number, 1 when we read his math grade, 2 when we read his science grade and 3 when we read his English grade. The counter gets increased by one, in the end of every iteration.

Now, when counter is equal to 4, that means that we should start reading data for the next student, thus we have to increment index by one, so that for example if we were reading data for the first student(index equal to 0), now we would need (index equal to 1).

Moreover, counter should be re-initialized to 0, so that we read his number and grades correctly, with the if-else statements.

Body:
I am supposed to create a function which receives the arrays as parameters and which searches for the student with the highest average of the 3 grades and return to main the location of the student in the array.

The 4 arrays are:
Student number(9 digits)
Math grade
Science grade
English grade

And finally, it's supposed to read the data from the file into the array.

File data is:

123456789
60
70
80
987654321
70
80
90
999888777
75
85
65
111222333
55
65
75
444555666
63
73
83

I need help with how to read the file data using the arrays and functions.

This is what I have so far:

#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;

int findHighest(int Mgrade[5], int Sgrade1[5], int Egrade[5], long Snumber[5]);

main()
{
    int Mgrade[5], Sgrade[5], Egrade[5];
    long Snumber[5];

    char num_from_file;
    ifstream infile;
    char mystring[20];
    int grade;
    infile.open("testdata.txt", ios::in);

    if (infile)
    {

        cout<<"File opened successfully\n";
        {
            do
            {

                infile.get(mystring,21); //(example from other program)
                infile.ignore(80,'\n');// (what should go here instead)

                infile>> grade;//(example from other program)
                infile.ignore(80,'\n');// (what should go here instead)

                if (infile.eof())
                {
                    break;
                }

                cout<<mystring<<'\t'<<grade<<endl<<endl;
                //cout<<'\t'<<num_from_file<<endl;
            }
            while(1);
        }
    }
    else
    {
        cout<<"error opening file";
    }

    infile.close();

    return 0;
}

Body:
Simply use getline(), like this:

#include <fstream>
#include <iostream>
#include <string>

int main(void) {
    int Mgrade[5], Sgrade[5], Egrade[5];
    long Snumber[5];
    std::ifstream input("testdata.txt");
    int index = 0, counter = 0;
    for( std::string line; getline( input, line ); ) {
        if(counter == 4) {
            counter = 0;
            index++;
        }
        if(counter == 0) {
            Snumber[index] = std::stol(line);
        } else if(counter == 1) {
            Mgrade[index] = std::stoi(line);
        } else if(counter == 2) {
            Sgrade[index] = std::stoi(line);
        } else if(counter == 3) {
            Egrade[index] = std::stoi(line);
        }
        counter++;
    }
    return 0;
}

The code reads the file (variable input in the code) line by line and uses a for loop to achieve that.

In every iteration of the loop, the variable line will contain the current line of the file that are we are reading. For example, in the first iteration, line will be equal to "123456789".

Now I use two integers, index and counter. The first is used to index the arrays, since we are reading the first student, we want to populate the first cell of every array (that would be an index equal to 0).

counter is used in order to keep track of how many lines are been read for the idnex-th student. We expect to read 4 lines for every student, so counter will be 0 when we read his number, 1 when we read his math grade, 2 when we read his science grade and 3 when we read his English grade. The counter gets increased by one, in the end of every iteration.

Now, when counter is equal to 4, that means that we should start reading data for the next student, thus we have to increment index by one, so that for example if we were reading data for the first student(index equal to 0), now we would need (index equal to 1).

Moreover, counter should be re-initialized to 0, so that we read his number and grades correctly, with the if-else statements.


问:
GlusterFS extremely slow (creating 100 empty files takes ~2 minutes)
I am trying glusterfs for the first time,
I used this tutorial to get started:

https://www.digitalocean.com/community/tutorials/how-to-create-a-redundant-storage-pool-using-glusterfs-on-ubuntu-servers

And I did not create a separate partition like suggested in the official docs.

Everything is up and running on EC2 (ubuntu instances), but it is extremely slow creating 100 empty files takes around 2 minutes

```<code>time sudo touch file{1..100}

real    1m43.220s
user    0m0.008s
sys 0m0.004s
</code>```

Am I missing something or doing something wrong ?

Current setup: I am using 2 servers and a client, all in the same region, the replication level is 2.
This is the command I used to create the pool:

```<code>sudo gluster volume create myvolume replica 2 transport tcp host1:/gluster-storage host2:/gluster-storage force
</code>```

CORRECTION:
The client was in a different region, this is the speed when I create 100 files from a client inside the same region:

```<code>time sudo touch file{1..100}

real    0m1.237s
user    0m0.004s
sys 0m0.000s
</code>```

I will leave the question open because I think 2 minutes to create empty files is too long even if the client is in a different region (Oregon -> N. Virginia)

答:
As such stretched cluster (means across regions in your case) is NOT supported.

Note, there are various communications happens back and forth between the
nodes and then the client getting success reply.

maybe you can try the same within same region(LAN) and check out the latency.

Body:
I am trying glusterfs for the first time,
I used this tutorial to get started:

https://www.digitalocean.com/community/tutorials/how-to-create-a-redundant-storage-pool-using-glusterfs-on-ubuntu-servers

And I did not create a separate partition like suggested in the official docs.

Everything is up and running on EC2 (ubuntu instances), but it is extremely slow creating 100 empty files takes around 2 minutes

time sudo touch file{1..100}

real    1m43.220s
user    0m0.008s
sys 0m0.004s

Am I missing something or doing something wrong ?

Current setup: I am using 2 servers and a client, all in the same region, the replication level is 2.
This is the command I used to create the pool:

sudo gluster volume create myvolume replica 2 transport tcp host1:/gluster-storage host2:/gluster-storage force

CORRECTION:
The client was in a different region, this is the speed when I create 100 files from a client inside the same region:

time sudo touch file{1..100}

real    0m1.237s
user    0m0.004s
sys 0m0.000s

I will leave the question open because I think 2 minutes to create empty files is too long even if the client is in a different region (Oregon -> N. Virginia)


问:
Cutting a UIImageView according to UIBezier?
I have a UIImageView, with a certain image.
I also have a UIBezierPath in some strange shape.
I would like to cut the image to that shape and return a new image in that shape.

In the form of :

```<code>func getCut(bezier:UIBezierPath, image:UIImageView)->UIImageView
</code>```

答:
You can use mask to do so. Here's a quick example.

```<code>class ViewController: UIViewController {

    var path: UIBezierPath!
    var touchPoint: CGPoint!
    var startPoint: CGPoint!

    var imageView =  UIImageView(image: #imageLiteral(resourceName: "IMG_0715"))

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(imageView)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            startPoint = touch.location(in: view)
            path = UIBezierPath()
            path.move(to: startPoint)
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            touchPoint = touch.location(in: view)
        }

        path.addLine(to: touchPoint)
        startPoint = touchPoint

    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        cut()
    }

    private func cut() {
        guard let path = path else { return }
        imageView = imageView.getCut(with: path)
    }

}

extension UIImageView {
    func getCut(with bezier: UIBezierPath) -> UIImageView {

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = bezier.cgPath

        self.layer.mask = shapeLayer

        return self
    }
}
</code>```

Body:
I have a UIImageView, with a certain image.
I also have a UIBezierPath in some strange shape.
I would like to cut the image to that shape and return a new image in that shape.

In the form of :

func getCut(bezier:UIBezierPath, image:UIImageView)->UIImageView

Body:
You can use mask to do so. Here's a quick example.

class ViewController: UIViewController {

    var path: UIBezierPath!
    var touchPoint: CGPoint!
    var startPoint: CGPoint!

    var imageView =  UIImageView(image: #imageLiteral(resourceName: "IMG_0715"))

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(imageView)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            startPoint = touch.location(in: view)
            path = UIBezierPath()
            path.move(to: startPoint)
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch = touches.first {
            touchPoint = touch.location(in: view)
        }

        path.addLine(to: touchPoint)
        startPoint = touchPoint

    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        cut()
    }

    private func cut() {
        guard let path = path else { return }
        imageView = imageView.getCut(with: path)
    }

}

extension UIImageView {
    func getCut(with bezier: UIBezierPath) -> UIImageView {

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = bezier.cgPath

        self.layer.mask = shapeLayer

        return self
    }
}


问:
iPhone - Waiting beetween 2 code line for asynchronous task to be done
I have two lines of code that are executed just before the pop of a view.
Those two lines are making some scrolling.
Because of those 3 animations, there are many things that the user don't see, or let's say don't see well.

I don't want to use callbacks to deal with this.
I just need the app to wait some 0,5 secs for the view to pop, and 0,5 secs more beetween the two scroll calls to let him see what is happening.

How may I do this easily without stopping the animations ?

I tried (quickly) [NSThread sleepForTimeInterval:0.5]; but it stops everything. Of course.

答:
You can't wait for an animation to finish from the main UI thread without exiting from the current method after the first line and using a callback for the second line.

If you don't like callbacks, your alternative is to queue your two lines for execution in a background thread.


问:
Testing methods that eventually throw an exception in RSpec
I've got a method as follows:

```<code> if response.fetch('ok')
    response.fetch(response_key) { [] }
  elsif response.fetch('error') == 'token_revoked'
    ErrorReporter.increment('access_revoked', source: { account_id: account_id }, sporadic: true)
    fail(RemoteService::AccessRevoked, 'Our access to your account was revoked, please re-authorize.')
  else
    ErrorReporter.increment(
      'bad_request',
      source: {
        account_id: account_id
        error: response.fetch('error')
      },
      sporadic: true
    )
    fail(RemoteService::InvalidRequest, 'Something went wrong communicating with the remote service, please try again')
  end
</code>```

And I'm trying to test the scenario when the request returns with the token_revoked error.  I'd like to ensure the test specifies that in this scenario, that we report the error to our ErrorReporting service.

So, my spec looks like this:

```<code>it 'records the failure with our error reporting service' do
  expect(ErrorReporter).to receive(:increment).with(
    'bad_request',
     source: {
       account_id:  1
     },
     sporadic: true
   )

   available_channels.fetch
end
</code>```

However, this spec always fails, because after the call is made to the ErrorReporter, the code immediately calls fail which makes my spec fail.  Does anyone have any idea how I can verify that the call to my error reporter is made while handling the inevitable exception that I know the code is now going to throw?

答:
The exception causes your example to fail because it is not rescued. To prevent the error, you can wrap the method call in a begin ... rescue block:

```<code>it 'records the failure with our error reporting service' do
  expect(ErrorReporter).to receive(:increment).with(
    'bad_request',
     source: {
       account_id:  1
     },
     sporadic: true
   )

   begin
     available_channels.fetch
   rescue => RemoteService::InvalidRequest
     # would cause the example to fail
   end
end
</code>```

In another example, you should also expect the error to be raised.

Body:
I've got a method as follows:

 if response.fetch('ok')
    response.fetch(response_key) { [] }
  elsif response.fetch('error') == 'token_revoked'
    ErrorReporter.increment('access_revoked', source: { account_id: account_id }, sporadic: true)
    fail(RemoteService::AccessRevoked, 'Our access to your account was revoked, please re-authorize.')
  else
    ErrorReporter.increment(
      'bad_request',
      source: {
        account_id: account_id
        error: response.fetch('error')
      },
      sporadic: true
    )
    fail(RemoteService::InvalidRequest, 'Something went wrong communicating with the remote service, please try again')
  end

And I'm trying to test the scenario when the request returns with the token_revoked error.  I'd like to ensure the test specifies that in this scenario, that we report the error to our ErrorReporting service.

So, my spec looks like this:

it 'records the failure with our error reporting service' do
  expect(ErrorReporter).to receive(:increment).with(
    'bad_request',
     source: {
       account_id:  1
     },
     sporadic: true
   )

   available_channels.fetch
end

However, this spec always fails, because after the call is made to the ErrorReporter, the code immediately calls fail which makes my spec fail.  Does anyone have any idea how I can verify that the call to my error reporter is made while handling the inevitable exception that I know the code is now going to throw?

Body:
The exception causes your example to fail because it is not rescued. To prevent the error, you can wrap the method call in a begin ... rescue block:

it 'records the failure with our error reporting service' do
  expect(ErrorReporter).to receive(:increment).with(
    'bad_request',
     source: {
       account_id:  1
     },
     sporadic: true
   )

   begin
     available_channels.fetch
   rescue => RemoteService::InvalidRequest
     # would cause the example to fail
   end
end

In another example, you should also expect the error to be raised.

ContentLicense: CC BY-SA 4.0


问:
Compare current time with specific time when some event occures
In the code below, only the else part is ever getting executed. What should I do to execute the if part?

```<code>private void Form_Load(object sender, EventArgs e)
{
    // Current Time is 11:47:00 AM
    DateTime CurrentTime = System.DateTime.Now;
    DateTime StartTime = Convert.ToDateTime("10:15:00 AM");
    DateTime Stoptime = Convert.ToDateTime("02:29:57 PM");
    DateTime CloseTime = Convert.ToDateTime("02:59:57 PM");

    if (StartTime > CurrentTime && CurrentTime < Stoptime)
    {
        // CODE
    }
    else
    {
        // CODE
    }
}
</code>```

答:
The problem is that you're checking if StartTime is greater than CurrentTime, which it clearly isn't. You just need to swap out that first operator with a less than operator:

```<code>if (StartTime < CurrentTime && CurrentTime < Stoptime)
{
    //CODE
}
else
{
    //CODE
}
</code>```

Body:
In the code below, only the else part is ever getting executed. What should I do to execute the if part?

private void Form_Load(object sender, EventArgs e)
{
    // Current Time is 11:47:00 AM
    DateTime CurrentTime = System.DateTime.Now;
    DateTime StartTime = Convert.ToDateTime("10:15:00 AM");
    DateTime Stoptime = Convert.ToDateTime("02:29:57 PM");
    DateTime CloseTime = Convert.ToDateTime("02:59:57 PM");

    if (StartTime > CurrentTime && CurrentTime < Stoptime)
    {
        // CODE
    }
    else
    {
        // CODE
    }
}

Body:
The problem is that you're checking if StartTime is greater than CurrentTime, which it clearly isn't. You just need to swap out that first operator with a less than operator:

if (StartTime < CurrentTime && CurrentTime < Stoptime)
{
    //CODE
}
else
{
    //CODE
}


问:
Android Studio: I accidentally deleted my app.iml file from my project, how do I add it
Now, my project will not run...it is telling me that my app module is missing.  Has anyone had this problem before?  I have no idea what information was in that file, so I dont know what to do.  Any recommendations would be appreciated :-)</p>

答:
For me, I tried just before on my new system with fresh Android Studio install. So I have tried in some different way and worked.

I have copied app.imp file from some other project and added in app folder of the Project. After this I have followed like File -> Invalidate Caches / Restart. It refreshed the file automatically as per the gradle file details and project Run perfectly.


问:
Django ImportError: No module named 'culqipy'
I made a module for Python https://github.com/culqi/culqi-python
but I don't know the reason why I cannot import it into my Django project.

```<code>  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/willyaguirre/PycharmProjects/e-s/tienda/urls.py", line 4, in <module>
    from . import views
  File "/Users/willyaguirre/PycharmProjects/e-s/tienda/views.py", line 13, in <module>
    import culqipy as culqi
ImportError: No module named culqipy
</code>```

Maybe my module is not correct.

答: Make sure you have installed it in the virtual environment of your current project. Or make sure you have activated the correct virtual environment for your project.</p>

Body:
I made a module for Python https://github.com/culqi/culqi-python
but I don't know the reason why I cannot import it into my Django project.

  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/willyaguirre/PycharmProjects/e-s/tienda/urls.py", line 4, in <module>
    from . import views
  File "/Users/willyaguirre/PycharmProjects/e-s/tienda/views.py", line 13, in <module>
    import culqipy as culqi
ImportError: No module named culqipy

Maybe my module is not correct.


问:
How to read a PDF file from a url of external site in C#
I want to be able to download a pdf that is accessed by a routed url (external site) in my asp.net application.
is there a way to do it?

The Current Situation:
The routed url is in the company's internal site (joomla site) http://example/sites/index.php/2011-10-30-12-29-04/finish/11/1234
This link is redirecting users to a pdf file
I need to get this pdf in my application (PdfReader) using the routed url.

Update#1:

I did some changes to my code as you suggested (I added it in the original question), just I needed to pass the content stream to my pdfReader. However it still shows me that download failed..

Update#2:
The problem is solved now, I had to pass the contentstream as follows
  Dim pdfReader As New PdfReader(isp:=contentStream)

Many Thanks..

```<code>   Public Async Function GetPDFFromCompanyWebsite() As Task(Of HttpResponseMessage)

    Using client As HttpClient = New HttpClient()
        Dim msg As HttpResponseMessage = Await client.GetAsync("http://example/sites/index.php/2011-10-30-12-29-04/finish/4/4088")
        If msg.IsSuccessStatusCode Then

            Dim contentStream = Await msg.Content.ReadAsStreamAsync()

            Dim pdfReader As New PdfReader(isp:=contentStream)
            Dim MST As MemoryStream = New MemoryStream()
            Dim pdfStamper As New PdfStamper(pdfReader, MST)
            For pageIndex As Integer = 1 To pdfReader.NumberOfPages
                Dim pageRectangle As Rectangle = pdfReader.GetPageSizeWithRotation(pageIndex)
                Dim pdfData As PdfContentByte = pdfStamper.GetOverContent(pageIndex)

                pdfData.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 40)
                Dim graphicsState As New PdfGState()

                graphicsState.FillOpacity = 0.1F
                pdfData.SetGState(graphicsState)

                pdfData.SetColorFill(BaseColor.BLUE)

                Dim bf As BaseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED)

                pdfData.SetFontAndSize(bf, pageRectangle.Width / 25)
                pdfData.BeginText()
                pdfData.SetFlatness(1000)

                Dim windowsuser As String = User.Identity.Name.Substring(4)
                windowsuser = windowsuser + "        " + windowsuser + "        " + windowsuser + "        " + windowsuser + "        " + windowsuser + "        " + windowsuser + "        " + windowsuser
                '    pdfData.ShowTextAligned(Element.ALIGN_BOTTOM, User.Identity.Name, 100, 100, 45)
                Response.Write("width:height: " + pageRectangle.Width.ToString + " / " + pageRectangle.Height.ToString)
                pdfData.ShowTextAligned(Element.ALIGN_CENTER, windowsuser, pageRectangle.Width / 2, pageRectangle.Height / 2, 45)
                pdfData.ShowTextAligned(Element.ALIGN_CENTER, windowsuser, pageRectangle.Width / 4, pageRectangle.Height - (pageRectangle.Height / 4), 45)
                pdfData.ShowTextAligned(Element.ALIGN_CENTER, windowsuser, pageRectangle.Width - (pageRectangle.Width / 4), pageRectangle.Height / 4, 45)
                pdfData.ShowTextAligned(Element.ALIGN_CENTER, windowsuser, (3 * pageRectangle.Width) / 8, pageRectangle.Height - ((3 * pageRectangle.Height) / 8), 45)
                pdfData.ShowTextAligned(Element.ALIGN_CENTER, windowsuser, pageRectangle.Width - ((3 * pageRectangle.Width) / 8), (3 * pageRectangle.Height) / 8, 45)

                pdfData.EndText()

            Next
            pdfStamper.Close()
            Dim bytesInStream As Byte() = MST.ToArray()

            MST.Close()

            Response.Clear()
            Response.ClearContent()
            Response.ClearHeaders()
            Response.ContentType = "application/pdf"
            Response.AddHeader("content-disposition", "attachment;filename=File.pdf")
            Response.BufferOutput = True
            Response.Cache.SetCacheability(HttpCacheability.NoCache)
            Response.BinaryWrite(bytesInStream)
            Response.End()
            Response.Close()

            '        End Using
        End If

        Return msg
    End Using
End Function
</code>```

答:
Try making a GET request to your company's website using the HttpClient class in C#. You can do something along the lines.</p>

```<code>using System.Net.Http;
using System.IO;

public async Task<HttpResponseMessage> GetPDFFromCompanyWebsite()
{
string currentDirectory = System.Web.Hosting.HostingEnvironment.MapPath("~");
string filePath = Path.Combine(currentDirectory, "App_Data", "someDocument.pdf");

using(HttpClient client = new HttpClient())
{
    HttpResponseMessage msg = await client.GetAsync($"http://example/sites/index.php/2011-10-30-12-29-04/finish/11/1234");

    if(msg.IsSuccessStatusCode)
    {
     using(var file = File.Create(filePath))
     {
       // create a new file to write to
       var contentStream = await msg.Content.ReadAsStreamAsync(); // get the actual content stream
       await contentStream.CopyToAsync(file); // copy that stream to the file stream
       await file.FlushAsync(); // flush back to disk before disposing
     }
   }
  return msg;
} }
</code>```

Body:
I want to be able to download a pdf that is accessed by a routed url (external site) in my asp.net application.
is there a way to do it?

The Current Situation:
The routed url is in the company's internal site (joomla site) http://example/sites/index.php/2011-10-30-12-29-04/finish/11/1234
This link is redirecting users to a pdf file
I need to get this pdf in my application (PdfReader) using the routed url.

Update#1:

I did some changes to my code as you suggested (I added it in the original question), just I needed to pass the content stream to my pdfReader. However it still shows me that download failed..

Update#2:
The problem is solved now, I had to pass the contentstream as follows
  Dim pdfReader As New PdfReader(isp:=contentStream)

Many Thanks..

   Public Async Function GetPDFFromCompanyWebsite() As Task(Of HttpResponseMessage)

    Using client As HttpClient = New HttpClient()
        Dim msg As HttpResponseMessage = Await client.GetAsync("http://example/sites/index.php/2011-10-30-12-29-04/finish/4/4088")
        If msg.IsSuccessStatusCode Then

            Dim contentStream = Await msg.Content.ReadAsStreamAsync()

            Dim pdfReader As New PdfReader(isp:=contentStream)
            Dim MST As MemoryStream = New MemoryStream()
            Dim pdfStamper As New PdfStamper(pdfReader, MST)
            For pageIndex As Integer = 1 To pdfReader.NumberOfPages
                Dim pageRectangle As Rectangle = pdfReader.GetPageSizeWithRotation(pageIndex)
                Dim pdfData As PdfContentByte = pdfStamper.GetOverContent(pageIndex)

                pdfData.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 40)
                Dim graphicsState As New PdfGState()

                graphicsState.FillOpacity = 0.1F
                pdfData.SetGState(graphicsState)

                pdfData.SetColorFill(BaseColor.BLUE)

                Dim bf As BaseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED)

                pdfData.SetFontAndSize(bf, pageRectangle.Width / 25)
                pdfData.BeginText()
                pdfData.SetFlatness(1000)

                Dim windowsuser As String = User.Identity.Name.Substring(4)
                windowsuser = windowsuser + "        " + windowsuser + "        " + windowsuser + "        " + windowsuser + "        " + windowsuser + "        " + windowsuser + "        " + windowsuser
                '    pdfData.ShowTextAligned(Element.ALIGN_BOTTOM, User.Identity.Name, 100, 100, 45)
                Response.Write("width:height: " + pageRectangle.Width.ToString + " / " + pageRectangle.Height.ToString)
                pdfData.ShowTextAligned(Element.ALIGN_CENTER, windowsuser, pageRectangle.Width / 2, pageRectangle.Height / 2, 45)
                pdfData.ShowTextAligned(Element.ALIGN_CENTER, windowsuser, pageRectangle.Width / 4, pageRectangle.Height - (pageRectangle.Height / 4), 45)
                pdfData.ShowTextAligned(Element.ALIGN_CENTER, windowsuser, pageRectangle.Width - (pageRectangle.Width / 4), pageRectangle.Height / 4, 45)
                pdfData.ShowTextAligned(Element.ALIGN_CENTER, windowsuser, (3 * pageRectangle.Width) / 8, pageRectangle.Height - ((3 * pageRectangle.Height) / 8), 45)
                pdfData.ShowTextAligned(Element.ALIGN_CENTER, windowsuser, pageRectangle.Width - ((3 * pageRectangle.Width) / 8), (3 * pageRectangle.Height) / 8, 45)

                pdfData.EndText()

            Next
            pdfStamper.Close()
            Dim bytesInStream As Byte() = MST.ToArray()

            MST.Close()

            Response.Clear()
            Response.ClearContent()
            Response.ClearHeaders()
            Response.ContentType = "application/pdf"
            Response.AddHeader("content-disposition", "attachment;filename=File.pdf")
            Response.BufferOutput = True
            Response.Cache.SetCacheability(HttpCacheability.NoCache)
            Response.BinaryWrite(bytesInStream)
            Response.End()
            Response.Close()

            '        End Using
        End If

        Return msg
    End Using
End Function

Body:
Try making a GET request to your company's website using the HttpClient class in C#. You can do something along the lines.

using System.Net.Http;
using System.IO;

public async Task<HttpResponseMessage> GetPDFFromCompanyWebsite()
{
string currentDirectory = System.Web.Hosting.HostingEnvironment.MapPath("~");
string filePath = Path.Combine(currentDirectory, "App_Data", "someDocument.pdf");

using(HttpClient client = new HttpClient())
{
    HttpResponseMessage msg = await client.GetAsync($"http://example/sites/index.php/2011-10-30-12-29-04/finish/11/1234");

    if(msg.IsSuccessStatusCode)
    {
     using(var file = File.Create(filePath))
     {
       // create a new file to write to
       var contentStream = await msg.Content.ReadAsStreamAsync(); // get the actual content stream
       await contentStream.CopyToAsync(file); // copy that stream to the file stream
       await file.FlushAsync(); // flush back to disk before disposing
     }
   }
  return msg;
} }


问:
Why are Branch Target Buffers needed for non register jump instructions?
For a MIPS 5 stage pipeline, the branch target is known by the decode stage because it can be easily extracted if the branch offset it is in the instruction and also you read the registers in the decode stage.

So then for an out of order pipeline, you obviously run into a problem with with instructions like 'jr', which might use a register that hasn't been calculated yet. For uses like this, there is clear use for a branch target buffer.

But for an instruction like 'beq', I see the necessity for a branch predictor, but not for the branch target because you already know the branch offset and of course you know the current program counter so you can easily come up with the branch destination.

Are register jumps the only instructions that use the branch target buffer or am I missing something?

答:
The fetch stage needs prediction to know what block to fetch next.  Instruction cache has some latency but can be pipelined.  DRAM has even more latency, but can still have multiple outstanding requests (depending on the memory controller or outer levels of cache).  So the fetch stage needs block addresses multiple cycles ahead of the blocks that are currently arriving from memory/cache.

Decode doesn't happen until after fetch, so that's an extra stall cycle if you waited until decode to detect the existence of unconditional direct branches.

See What branch misprediction does the Branch Target Buffer detect? for more about this from an x86 perspective (where decode is expensive and takes multiple stages, so this is even more critical).

Also note that high-performance CPUs decode multiple instructions in parallel, and often have a queue between fetch and decode to absorb fetch bubbles.  If the fetch stage predicts there's a taken branch (conditional or unconditional, doesn't matter), it can queue up instructions from the branch target instead of instructions after the branch.

See also Slow jmp-instruction for an x86 benchmark of a giant sequence of jump to next-instruction.  (i.e. relative offset = 0).  It slows down when the sequence is long enough not to fit in the BTB.


问:
Vba save newly workbook with name in any user's system location
I want a new workbook creation that automatically saves at user's system but the path is not fixed so is there any way to do the same. I don't want that  User manually gives name ins ave as dialogue box. I want a macro that handles at runtime and saves the workbook in user's specific location.(Users are different)
Kindly suggest the code and approach for the same.
I have tried some variants:

```<code>Sub sb_Copy_Save_ActiveSheet_As_Workbook()
Set wb = Workbooks.Add
ThisWorkbook.Activate
ActiveSheet.Copy Before:=wb.Sheets(1)
wb.Activate
wb.SaveAs "C:\temp\test3.xlsx"
End Sub
</code>```

This gives me an error and I want the path that allows any user to save the file in their location without user's input(Save As Dialogue). Macro is able to save the file in any user's system.

答:
If you copy a worksheet to no destination, you end up with a new workbook with one worksheet (a copy of the original). Also lookup environ function to get user info.

```<code>activesheet.copy
activeworkbook.saveas filename:=environ("TEMP") & "\test", fileformat:=xlOpenXMLWorkbook
activeworkbook.close savechanges:=false
</code>```

Body:
I want a new workbook creation that automatically saves at user's system but the path is not fixed so is there any way to do the same. I don't want that  User manually gives name ins ave as dialogue box. I want a macro that handles at runtime and saves the workbook in user's specific location.(Users are different)
Kindly suggest the code and approach for the same.
I have tried some variants:

Sub sb_Copy_Save_ActiveSheet_As_Workbook()
Set wb = Workbooks.Add
ThisWorkbook.Activate
ActiveSheet.Copy Before:=wb.Sheets(1)
wb.Activate
wb.SaveAs "C:\temp\test3.xlsx"
End Sub

This gives me an error and I want the path that allows any user to save the file in their location without user's input(Save As Dialogue). Macro is able to save the file in any user's system.

Body:
If you copy a worksheet to no destination, you end up with a new workbook with one worksheet (a copy of the original). Also lookup environ function to get user info.

activesheet.copy
activeworkbook.saveas filename:=environ("TEMP") & "\test", fileformat:=xlOpenXMLWorkbook
activeworkbook.close savechanges:=false


问:
Extracting DateTime from Date to get DateTime
What I have is;

A list of weekendDates in a format of 11/4/2017 12:00:00 AM

A list of late comings lateDateTimeList in a format of 11/4/2017 02:40:03 PM

and I am trying to exclude all the weekends from the late comings, So I have a list that has all the date and time both (without weekendDates) since I need the time later.

for weekendDates:

```<code>// Build list of weekdates and weekend dates
            List<DateTime> weekDates = new List<DateTime>();
            List<DateTime> weekendDates = new List<DateTime>();
            int days = (EndDate - StartDate).Days;
            for (int i = 0; i < days; i++)
            {
                DateTime date = StartDate.AddDays(i);
                if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday)
                {
                    weekendDates.Add(date);
                    continue;
                }
                weekDates.Add(date);
            }
</code>```

late coming list:

```<code>var fetchAllrec = (from m in db.D2L
                            where m.RId == ENum && m.Date >= StartDate && m.Date <= EndDate
                            select m).Distinct();

            var onerecord = fetchAllrec
                    .GroupBy(dt => dt.Date)
                    .Select(z => z.OrderBy(y => y.Date).FirstOrDefault())
                    .ToList();

//All the dates he was late compared to his AT
            var late = (from d in onerecord
                        where d.DateTime.Value.Hour >= ArT
                        select d).ToList();
</code>```

WithoutWeekends:

```<code>//All the late dates without weekends
            IEnumerable<DateTime> lateDateTimeList = late.Select(m => m.DateTime.Value).ToList();
            //^^^Change this to m.Date to get the 'latDateTimeList' dates without weekends but then it wont calculate
            //the minutes since it will have all the Dates in the 'lateDateTimeList' ONLY!
            IEnumerable<DateTime> lateDateTimeWithoutWeekendsList =  lateDateTimeList.Except(weekendDates).ToList();

            //get latecoming DateTimes list here
            var lateComings = new List<DateTime>();

            foreach (var g in lateDateTimeWithoutWeekendsList)
            {
                lateComings.Add(g);    // IT MUST HAVE DATE TIME HERE NOT JUST DATE
            }

            countLates = lateComings.Count();

           //list of time differences
            var timeDiff = new List<TimeSpan>();

            foreach (DateTime ts in lateComings)
            {

                if (ts.TimeOfDay > TimeSpan.FromHours(AT))
                {
                    timeDiff.Add(ts.TimeOfDay - TimeSpan.FromHours(AT));
                }
            }
 //fetching the minutes from the above list

            var minutesList = timeDiff.Select(t => Convert.ToInt32(t.TotalMinutes)).ToList();
</code>```

What the above code does is that it does not exclude the weekendDates, i.e. this part gives complete list including weekendDates i.e. the list that was in lateDateTimeList

```<code>IEnumerable<DateTime> lateDateTimeWithoutWeekendsList = lateDateTimeList.Except(weekendDates).ToList();
</code>```

OUTPUT:

```<code>11/2/2017 10:53:00 AM
11/3/2017 11:10:03 AM
11/4/2017 01:12:13 PM
11/5/2017 12:11:10 PM
</code>```

but if I change this;

```<code>IEnumerable<DateTime> lateDateTimeList = late.Select(m => m.DateTime.Value).ToList();
</code>```

to

```<code>IEnumerable<DateTime> lateDateTimeList = late.Select(m => m.Date.Value).ToList();
</code>```

it gives me all the dates WITHOUT time.

OUTPUT:

```<code>11/2/2017 12:00:00 AM
11/3/2017 12:00:00 AM
</code>```

答:
```<code>  using System;
  using System.Collections.Generic;
  using System.Linq;

  static class DateTimeExtension
  {
    public static bool IsWeekend (this DateTime dt)
        => dt.DayOfWeek == DayOfWeek.Saturday || dt.DayOfWeek == DayOfWeek.Sunday;

    public static Func<DateTime, bool> IsWeekend_2 =
        dt => dt.DayOfWeek == DayOfWeek.Saturday || dt.DayOfWeek == DayOfWeek.Sunday;
  }

  class Program
  {
    Func<DateTime, bool> IsWeekend = dt => dt.DayOfWeek == DayOfWeek.Saturday || dt.DayOfWeek == DayOfWeek.Sunday;

    static void PrintDates (IList<DateTime> dts) => Console.WriteLine (string.Join ("", dts.Select (item => item.ToString () + "      Weekend: " + (item.IsWeekend () ? "Yes" : "No") + "\n"))) ;
    static Random r = new Random ();
    static void Main (string[] args)
    {
      // Data
      var dates = new List<DateTime> ();
      Enumerable.Range (0, 50)
          .ToList ()
          .ForEach (n => dates.Add (DateTime.Now.AddDays (n).AddHours(r.NextDouble() * 12)));

      // no weekends
      var datesWithoutWeekends = dates.Where (myDate => !myDate.IsWeekend ()).ToList ();

      // also no weekends
      var datesWithoutWeekends_2 = dates.Where (myDate => !DateTimeExtension.IsWeekend_2 (myDate)).ToList ();

      // still no weekends
      var datesWithoutWeekends_3 = dates.Where (myDate =>myDate.DayOfWeek != DayOfWeek.Sunday && myDate.DayOfWeek == DayOfWeek.Saturday).ToList ();

      PrintDates (dates);
      Console.WriteLine ();
      PrintDates (datesWithoutWeekends);
      Console.ReadLine ();
    }
  }
</code>```

Just filter the weekends on the fly - f.e. with an Extension - or a Predicate (do not use Predicase, use Func - they are the same but Func is func'ier) or do it inline.

Format the output however you want using DateTime Customn Format

Output (German default locale dd.mm.YYYY):

```<code>06.12.2017 16:40:13      Weekend: No
07.12.2017 15:06:42      Weekend: No
08.12.2017 12:09:55      Weekend: No
09.12.2017 10:19:20      Weekend: Yes
10.12.2017 19:51:28      Weekend: Yes
11.12.2017 12:18:26      Weekend: No
15.12.2017 17:11:18      Weekend: No
16.12.2017 15:45:32      Weekend: Yes
17.12.2017 11:39:25      Weekend: Yes
18.12.2017 17:34:05      Weekend: No
19.12.2017 16:25:51      Weekend: No
20.12.2017 12:11:49      Weekend: No
21.12.2017 16:37:07      Weekend: No
22.12.2017 17:56:36      Weekend: No
23.12.2017 08:37:13      Weekend: Yes
24.12.2017 09:22:52      Weekend: Yes
25.12.2017 20:01:19      Weekend: No
26.12.2017 13:24:30      Weekend: No

06.12.2017 16:40:13      Weekend: No
07.12.2017 15:06:42      Weekend: No
08.12.2017 12:09:55      Weekend: No
11.12.2017 12:18:26      Weekend: No
12.12.2017 20:00:09      Weekend: No
13.12.2017 20:12:48      Weekend: No
14.12.2017 17:03:31      Weekend: No
15.12.2017 17:11:18      Weekend: No
18.12.2017 17:34:05      Weekend: No
19.12.2017 16:25:51      Weekend: No
20.12.2017 12:11:49      Weekend: No
21.12.2017 16:37:07      Weekend: No
22.12.2017 17:56:36      Weekend: No
25.12.2017 20:01:19      Weekend: No
26.12.2017 13:24:30      Weekend: No
</code>```

Body:
What I have is;

A list of weekendDates in a format of 11/4/2017 12:00:00 AM

A list of late comings lateDateTimeList in a format of 11/4/2017 02:40:03 PM

and I am trying to exclude all the weekends from the late comings, So I have a list that has all the date and time both (without weekendDates) since I need the time later.

for weekendDates:

// Build list of weekdates and weekend dates
            List<DateTime> weekDates = new List<DateTime>();
            List<DateTime> weekendDates = new List<DateTime>();
            int days = (EndDate - StartDate).Days;
            for (int i = 0; i < days; i++)
            {
                DateTime date = StartDate.AddDays(i);
                if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday)
                {
                    weekendDates.Add(date);
                    continue;
                }
                weekDates.Add(date);
            }

late coming list:

var fetchAllrec = (from m in db.D2L
                            where m.RId == ENum && m.Date >= StartDate && m.Date <= EndDate
                            select m).Distinct();

            var onerecord = fetchAllrec
                    .GroupBy(dt => dt.Date)
                    .Select(z => z.OrderBy(y => y.Date).FirstOrDefault())
                    .ToList();

//All the dates he was late compared to his AT
            var late = (from d in onerecord
                        where d.DateTime.Value.Hour >= ArT
                        select d).ToList();

WithoutWeekends:

//All the late dates without weekends
            IEnumerable<DateTime> lateDateTimeList = late.Select(m => m.DateTime.Value).ToList();
            //^^^Change this to m.Date to get the 'latDateTimeList' dates without weekends but then it wont calculate
            //the minutes since it will have all the Dates in the 'lateDateTimeList' ONLY!
            IEnumerable<DateTime> lateDateTimeWithoutWeekendsList =  lateDateTimeList.Except(weekendDates).ToList();

            //get latecoming DateTimes list here
            var lateComings = new List<DateTime>();

            foreach (var g in lateDateTimeWithoutWeekendsList)
            {
                lateComings.Add(g);    // IT MUST HAVE DATE TIME HERE NOT JUST DATE
            }

            countLates = lateComings.Count();

           //list of time differences
            var timeDiff = new List<TimeSpan>();

            foreach (DateTime ts in lateComings)
            {

                if (ts.TimeOfDay > TimeSpan.FromHours(AT))
                {
                    timeDiff.Add(ts.TimeOfDay - TimeSpan.FromHours(AT));
                }
            }
 //fetching the minutes from the above list

            var minutesList = timeDiff.Select(t => Convert.ToInt32(t.TotalMinutes)).ToList();

What the above code does is that it does not exclude the weekendDates, i.e. this part gives complete list including weekendDates i.e. the list that was in lateDateTimeList

IEnumerable<DateTime> lateDateTimeWithoutWeekendsList = lateDateTimeList.Except(weekendDates).ToList();

OUTPUT:

11/2/2017 10:53:00 AM
11/3/2017 11:10:03 AM
11/4/2017 01:12:13 PM
11/5/2017 12:11:10 PM

but if I change this;

IEnumerable<DateTime> lateDateTimeList = late.Select(m => m.DateTime.Value).ToList();

to

IEnumerable<DateTime> lateDateTimeList = late.Select(m => m.Date.Value).ToList();

it gives me all the dates WITHOUT time.

OUTPUT:

11/2/2017 12:00:00 AM
11/3/2017 12:00:00 AM

Body:
  using System;
  using System.Collections.Generic;
  using System.Linq;

  static class DateTimeExtension
  {
    public static bool IsWeekend (this DateTime dt)
        => dt.DayOfWeek == DayOfWeek.Saturday || dt.DayOfWeek == DayOfWeek.Sunday;

    public static Func<DateTime, bool> IsWeekend_2 =
        dt => dt.DayOfWeek == DayOfWeek.Saturday || dt.DayOfWeek == DayOfWeek.Sunday;
  }

  class Program
  {
    Func<DateTime, bool> IsWeekend = dt => dt.DayOfWeek == DayOfWeek.Saturday || dt.DayOfWeek == DayOfWeek.Sunday;

    static void PrintDates (IList<DateTime> dts) => Console.WriteLine (string.Join ("", dts.Select (item => item.ToString () + "      Weekend: " + (item.IsWeekend () ? "Yes" : "No") + "\n"))) ;
    static Random r = new Random ();
    static void Main (string[] args)
    {
      // Data
      var dates = new List<DateTime> ();
      Enumerable.Range (0, 50)
          .ToList ()
          .ForEach (n => dates.Add (DateTime.Now.AddDays (n).AddHours(r.NextDouble() * 12)));

      // no weekends
      var datesWithoutWeekends = dates.Where (myDate => !myDate.IsWeekend ()).ToList ();

      // also no weekends
      var datesWithoutWeekends_2 = dates.Where (myDate => !DateTimeExtension.IsWeekend_2 (myDate)).ToList ();

      // still no weekends
      var datesWithoutWeekends_3 = dates.Where (myDate =>myDate.DayOfWeek != DayOfWeek.Sunday && myDate.DayOfWeek == DayOfWeek.Saturday).ToList ();

      PrintDates (dates);
      Console.WriteLine ();
      PrintDates (datesWithoutWeekends);
      Console.ReadLine ();
    }
  }

Just filter the weekends on the fly - f.e. with an Extension - or a Predicate (do not use Predicase, use Func - they are the same but Func is func'ier) or do it inline.

Format the output however you want using DateTime Customn Format

Output (German default locale dd.mm.YYYY):

06.12.2017 16:40:13      Weekend: No
07.12.2017 15:06:42      Weekend: No
08.12.2017 12:09:55      Weekend: No
09.12.2017 10:19:20      Weekend: Yes
10.12.2017 19:51:28      Weekend: Yes
11.12.2017 12:18:26      Weekend: No
15.12.2017 17:11:18      Weekend: No
16.12.2017 15:45:32      Weekend: Yes
17.12.2017 11:39:25      Weekend: Yes
18.12.2017 17:34:05      Weekend: No
19.12.2017 16:25:51      Weekend: No
20.12.2017 12:11:49      Weekend: No
21.12.2017 16:37:07      Weekend: No
22.12.2017 17:56:36      Weekend: No
23.12.2017 08:37:13      Weekend: Yes
24.12.2017 09:22:52      Weekend: Yes
25.12.2017 20:01:19      Weekend: No
26.12.2017 13:24:30      Weekend: No

06.12.2017 16:40:13      Weekend: No
07.12.2017 15:06:42      Weekend: No
08.12.2017 12:09:55      Weekend: No
11.12.2017 12:18:26      Weekend: No
12.12.2017 20:00:09      Weekend: No
13.12.2017 20:12:48      Weekend: No
14.12.2017 17:03:31      Weekend: No
15.12.2017 17:11:18      Weekend: No
18.12.2017 17:34:05      Weekend: No
19.12.2017 16:25:51      Weekend: No
20.12.2017 12:11:49      Weekend: No
21.12.2017 16:37:07      Weekend: No
22.12.2017 17:56:36      Weekend: No
25.12.2017 20:01:19      Weekend: No
26.12.2017 13:24:30      Weekend: No


Title: Extracting DateTime from Date to get DateTime

Body:
How about that:

static void Main(string[] args)
{

    Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

    List<DateTime> dates = new List<DateTime>();

    for(int i = 1; i <= 50; i++)
    {
        DateTime date = DateTime.Now.AddDays(i);
        dates.Add(date);
        Trace.WriteLine(date.ToString("dd.MM.yyyy HH:mm:ss dddd"));
    }

    List<DateTime> filteredDates = dates.Where(date =>
                                               !(date.DayOfWeek == DayOfWeek.Saturday ||
                                                 date.DayOfWeek == DayOfWeek.Sunday))
                                        .ToList();

    Trace.WriteLine("------NO-WEEKENDS----------");

    filteredDates.ForEach(date => Trace.WriteLine(date.ToString("dd.MM.yyyy HH:mm:ss dddd")));

    Console.ReadKey();
}

Using Linq Enumerable.Where

Output:

07.12.2017 08:40:32 Thursday
08.12.2017 08:40:32 Friday
09.12.2017 08:40:32 Saturday
10.12.2017 08:40:32 Sunday
11.12.2017 08:40:32 Monday
12.12.2017 08:40:32 Tuesday
13.12.2017 08:40:32 Wednesday
14.12.2017 08:40:32 Thursday
15.12.2017 08:40:32 Friday
16.12.2017 08:40:32 Saturday
17.12.2017 08:40:32 Sunday
18.12.2017 08:40:32 Monday
19.12.2017 08:40:32 Tuesday
20.12.2017 08:40:32 Wednesday
21.12.2017 08:40:32 Thursday
22.12.2017 08:40:32 Friday
23.12.2017 08:40:32 Saturday
24.12.2017 08:40:32 Sunday
25.12.2017 08:40:32 Monday
26.12.2017 08:40:32 Tuesday
27.12.2017 08:40:32 Wednesday
28.12.2017 08:40:32 Thursday
29.12.2017 08:40:32 Friday
30.12.2017 08:40:32 Saturday
31.12.2017 08:40:32 Sunday
01.01.2018 08:40:32 Monday
02.01.2018 08:40:32 Tuesday
03.01.2018 08:40:32 Wednesday
04.01.2018 08:40:32 Thursday
05.01.2018 08:40:32 Friday
06.01.2018 08:40:32 Saturday
07.01.2018 08:40:32 Sunday
08.01.2018 08:40:32 Monday
09.01.2018 08:40:32 Tuesday
10.01.2018 08:40:32 Wednesday
11.01.2018 08:40:32 Thursday
12.01.2018 08:40:32 Friday
13.01.2018 08:40:32 Saturday
14.01.2018 08:40:32 Sunday
15.01.2018 08:40:32 Monday
16.01.2018 08:40:32 Tuesday
17.01.2018 08:40:32 Wednesday
18.01.2018 08:40:32 Thursday
19.01.2018 08:40:32 Friday
20.01.2018 08:40:32 Saturday
21.01.2018 08:40:32 Sunday
22.01.2018 08:40:32 Monday
23.01.2018 08:40:32 Tuesday
24.01.2018 08:40:32 Wednesday
25.01.2018 08:40:32 Thursday

------NO-WEEKENDS----------

07.12.2017 08:40:32 Thursday
08.12.2017 08:40:32 Friday
11.12.2017 08:40:32 Monday
12.12.2017 08:40:32 Tuesday
13.12.2017 08:40:32 Wednesday
14.12.2017 08:40:32 Thursday
15.12.2017 08:40:32 Friday
18.12.2017 08:40:32 Monday
19.12.2017 08:40:32 Tuesday
20.12.2017 08:40:32 Wednesday
21.12.2017 08:40:32 Thursday
22.12.2017 08:40:32 Friday
25.12.2017 08:40:32 Monday
26.12.2017 08:40:32 Tuesday
27.12.2017 08:40:32 Wednesday
28.12.2017 08:40:32 Thursday
29.12.2017 08:40:32 Friday
01.01.2018 08:40:32 Monday
02.01.2018 08:40:32 Tuesday
03.01.2018 08:40:32 Wednesday
04.01.2018 08:40:32 Thursday
05.01.2018 08:40:32 Friday
08.01.2018 08:40:32 Monday
09.01.2018 08:40:32 Tuesday
10.01.2018 08:40:32 Wednesday
11.01.2018 08:40:32 Thursday
12.01.2018 08:40:32 Friday
15.01.2018 08:40:32 Monday
16.01.2018 08:40:32 Tuesday
17.01.2018 08:40:32 Wednesday
18.01.2018 08:40:32 Thursday
19.01.2018 08:40:32 Friday
22.01.2018 08:40:32 Monday
23.01.2018 08:40:32 Tuesday
24.01.2018 08:40:32 Wednesday
25.01.2018 08:40:32 Thursday


问:
Eclipse opens and then immediately closes after graphic appears
When windows installed updates, it closed my eclipse and corrupted the workspace or something.   When I try to start eclipse I get the error:

I have already tried most of the google solutions.  I tried deleting the plugins folder, and it still does the same thing.  I tried adding the --clean option to the eclipse launcher, and it still crashes.  If I delete the org.eclipse.e4.workbench folder, it still does the same behavior.  When I try to start eclipse it shows the launcher logo for about a quarter second, and none of the above solutions fixed my problem.

Any other ideas?

Thanks,

```<code> The workspace exited with unsaved changes in the previous session; refreshing workspace to recover changes.

!ENTRY org.eclipse.mylyn.tasks.core 2 0 2015-08-24 08:54:58.371
!MESSAGE Failed to load tasks.xml.zip, restoring from snapshot
!STACK 1
org.eclipse.core.runtime.CoreException: Failed to load Task List
</code>```

答:
SOLUTION IS SIMPLE

Firstly you wil come across this issue if you have uninstalled Java versions from system uninstall window. eg., I uninstalled Java 8 u151 from my machine and downloaded and installed Java 8 u152. Then it was opening with splash screens for few seconds.
Quick Fix is:

```<code>Undo all your java version changes.
Uninstall 152 for exammple and install the original 151 version. This fixed my issue.
</code>```

DONT FOGET TO COPY ECLIPSE folder TO c:\program files folder.

Body:
When windows installed updates, it closed my eclipse and corrupted the workspace or something.   When I try to start eclipse I get the error:

I have already tried most of the google solutions.  I tried deleting the plugins folder, and it still does the same thing.  I tried adding the --clean option to the eclipse launcher, and it still crashes.  If I delete the org.eclipse.e4.workbench folder, it still does the same behavior.  When I try to start eclipse it shows the launcher logo for about a quarter second, and none of the above solutions fixed my problem.

Any other ideas?

Thanks,

 The workspace exited with unsaved changes in the previous session; refreshing workspace to recover changes.

!ENTRY org.eclipse.mylyn.tasks.core 2 0 2015-08-24 08:54:58.371
!MESSAGE Failed to load tasks.xml.zip, restoring from snapshot
!STACK 1
org.eclipse.core.runtime.CoreException: Failed to load Task List

Body:
SOLUTION IS SIMPLE

Firstly you wil come across this issue if you have uninstalled Java versions from system uninstall window. eg., I uninstalled Java 8 u151 from my machine and downloaded and installed Java 8 u152. Then it was opening with splash screens for few seconds.
Quick Fix is:

Undo all your java version changes.
Uninstall 152 for exammple and install the original 151 version. This fixed my issue.

DONT FOGET TO COPY ECLIPSE folder TO c:\program files folder.


问:
Boxplot for each individual level in two factor columns?
This is my code. I have two factor variables (cyl and am)that I want to plot in my box plot.

boxplot(mpg~cyl+am,data=mtcars)

I want to make a boxplot for each individual factor levels - 4,6,8,0,1 but not the interaction of them (e.g. 4.0).

My box plot should only have (4,6,8,0,1) on the axis. How do I do that?

答:
You may reshape the data and then you can do the plotting, However this may not be the elegant

```<code>library(reshape2)
mtcars_subset <- mtcars[,c("am", "cyl", "mpg")]
dat <- melt(mtcars_subset, id.vars="mpg")
#or dat <- melt(mtcars, id.vars = "mpg", measure.vars = c("cyl", "am"))
boxplot(data=dat, mpg ~ value)
</code>```

Body:
You may reshape the data and then you can do the plotting, However this may not be the elegant

library(reshape2)
mtcars_subset <- mtcars[,c("am", "cyl", "mpg")]
dat <- melt(mtcars_subset, id.vars="mpg")
#or dat <- melt(mtcars, id.vars = "mpg", measure.vars = c("cyl", "am"))
boxplot(data=dat, mpg ~ value)


问:
Div on click expands but does not contract on clicking again
When I click on my div it expands, but when i click again it does not contact. Clicking on the Div again should close/contract it back.

Below is my HTML code:

```<code><div style="height:35px;" onclick="style='height:auto'">
  <p style="color: #9DA4AB;font-size: 15px;">{{list.TASKDESC}}</p>
</div>
</code>```

Please note i am using IONIC and i am looking at a simplest way to achieve this.

答:
Here is a simple solution with Pure css and HTML

HTML

```<code><input type="checkbox" id="post" />
<label for="post">
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit.Libero fuga facilis vel consectetur quos sapiente deleniti eveniet dolores tempore eos deserunt officia quis ab? Excepturi vero tempore minus beatae voluptatem!</div>
</label>

<p>The text above expends when you click on it. (checkbox and label used to achieve)</p>
</code>```

CSS

```<code>input {
  display: none;
}
div {
  max-height: 1em;
  overflow: hidden;
}
input:checked ~ label div {
  font-size: inherit;
  max-height: 999em;
}
</code>```

Demo on Codepen

Body:
When I click on my div it expands, but when i click again it does not contact. Clicking on the Div again should close/contract it back.

Below is my HTML code:

{{list.TASKDESC}}

Please note i am using IONIC and i am looking at a simplest way to achieve this.

Body:
Here is a simple solution with Pure css and HTML

HTML

<input type="checkbox" id="post" />
<label for="post">
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit.Libero fuga facilis vel consectetur quos sapiente deleniti eveniet dolores tempore eos deserunt officia quis ab? Excepturi vero tempore minus beatae voluptatem!</div>
</label>

<p>The text above expends when you click on it. (checkbox and label used to achieve)</p>

CSS

input {
  display: none;
}
div {
  max-height: 1em;
  overflow: hidden;
}
input:checked ~ label div {
  font-size: inherit;
  max-height: 999em;
}

Demo on Codepen


问:
YYYYMMDD Date Format regular Expression to validate a date in C# .net
I need to validate the date format using regular expression in C#.

Here is the format: "YYYYMMDD"

答:
Consider using DateTime.TryParseExact to validate the date.
You can use the method to silmultaneously validate and read the DateTime value.

For example:

```<code>DateTime dateValue;
if (DateTime.TryParseExact(dateString, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue))
{
 //Parsed Successfully
}
</code>```

Body:
Consider using DateTime.TryParseExact to validate the date.
You can use the method to silmultaneously validate and read the DateTime value.

For example:

DateTime dateValue;
if (DateTime.TryParseExact(dateString, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateValue))
{
 //Parsed Successfully
}


问:
Error code 500 while uploading the file on Box Drive
I'm trying to upload file on Box using rest API and getting 500 Internal Server Error.

```<code>URL: https://upload.box.com/api/2.0/files/content
Header :- "Authorization: Bearer XYZ"
Body(form-data) : attributes='{"name":"test.png", "parent":{"id":""498765432099}}'
file=file will be here
</code>```

Postman screenshot are following:-

答:
Thank you guys problem is resolved,

I was using the postman from google chrome extension to check the API
and getting 500 in response.

But now I had tested it on postman official application (https://www.getpostman.com/apps) Now it's working fine.

As postman extension is deprecated it still gives me error but on official application its working fine.

Body:
I'm trying to upload file on Box using rest API and getting 500 Internal Server Error.

URL: https://upload.box.com/api/2.0/files/content
Header :- "Authorization: Bearer XYZ"
Body(form-data) : attributes='{"name":"test.png", "parent":{"id":""498765432099}}'
file=file will be here

Postman screenshot are following:-


问:
Node Red MongoDB
I have sensor data from MongoLab to Node-RED and I want visualize this data using Node-Red dashboard in form of a gauge or chart.
Data from the mongoLab collection looks like this:

```<code>[{"_id":"5947e34de8fef902920defd8","sensorId":"5947340048225508","value":34,"date":"2017-06-19T14:44:29.000Z"},{"_id":"5947e34e6737e202b54f0a62","sensorId":"13359295204302776","value":25,"date":"2017-06-19T14:44:30.000Z"},{"_id":"5947e352e8fef902920defdc","sensorId":"5947340048225508","value":37,"date":"2017-06-19T14:44:34.000Z"},{"_id":"5947e3536737e202b54f0a66","sensorId":"13359295204302776","value":24,"date":"2017-06-19T14:44:35.000Z"}]
</code>```

I want to visualize the values based on the sensorId...or is there any way I can be able to visualize this data using Node Red.

The function node is using the following javascript

```<code>msg.headers = {"Content-Type":"application/json"};
return msg;
</code>```

My intention is to visualize the sensor value on the ui_gauge or chart.

答:
Make a gauge/graph for each of the unique data steams you want to reflect in the UI/dashboard,

Then you'll need to double the output lines to another function that passes this information to the msg.payload, and then from that function, tie it to the corresponding dashboard gauges.

A gauge will obviously show the last value sent, while a graph will show you a history. May need to tweak the visual layout of the dashboard gauges/charts to show more data, to your liking.

Flow Chart Example

Your code might look something like this in the new forked function that is then tied to your gauges:

```<code>  msg.payload = msg.value;
  return msg;
</code>```

or you can use a switch, that then breaks the values to multiple outputs, that then each output goes to a corresponding gauge to reflect the data.

Flow Chart Example Using Switch

I really hope this helps.

Title: Node Red MongoDB

Body:
I have sensor data from MongoLab to Node-RED and I want visualize this data using Node-Red dashboard in form of a gauge or chart.
Data from the mongoLab collection looks like this:

[{"_id":"5947e34de8fef902920defd8","sensorId":"5947340048225508","value":34,"date":"2017-06-19T14:44:29.000Z"},{"_id":"5947e34e6737e202b54f0a62","sensorId":"13359295204302776","value":25,"date":"2017-06-19T14:44:30.000Z"},{"_id":"5947e352e8fef902920defdc","sensorId":"5947340048225508","value":37,"date":"2017-06-19T14:44:34.000Z"},{"_id":"5947e3536737e202b54f0a66","sensorId":"13359295204302776","value":24,"date":"2017-06-19T14:44:35.000Z"}]

I want to visualize the values based on the sensorId...or is there any way I can be able to visualize this data using Node Red.

The function node is using the following javascript

msg.headers = {"Content-Type":"application/json"};
return msg;

My intention is to visualize the sensor value on the ui_gauge or chart.

Body:
Make a gauge/graph for each of the unique data steams you want to reflect in the UI/dashboard,

Then you'll need to double the output lines to another function that passes this information to the msg.payload, and then from that function, tie it to the corresponding dashboard gauges.

A gauge will obviously show the last value sent, while a graph will show you a history. May need to tweak the visual layout of the dashboard gauges/charts to show more data, to your liking.

Flow Chart Example

Your code might look something like this in the new forked function that is then tied to your gauges:

  msg.payload = msg.value;
  return msg;

or you can use a switch, that then breaks the values to multiple outputs, that then each output goes to a corresponding gauge to reflect the data.

Flow Chart Example Using Switch

I really hope this helps.


问:
How coordinates points works in LinearGradient?
Can anyone please explain or describe how the coordinates points in the LinearGradient?

For example: I have my code in this way.

```<code>   var gradient = new LinearGradient(0, 0, 500, 500, colors, null, Shader.TileMode.Clamp);
   paint.SetShader(gradient);
   paint.Dither = true;
</code>```

how it display in the rectangle while applying in the rectangle ?

答:
In Android, the coordinate system always is like what you can see above picture.

1) (0,0) is top left corner.

2) (maxX,0) is top right corner

3) (0,maxY) is bottom left corner

4) (maxX,maxY) is bottom right corner

The maxX or maxY is the screen's(or view's) max width or max height.

This new LinearGradient(0, 0, 500, 500, colors, null, Shader.TileMode.Clamp) method will be sure a Gradient line which you can see in above picture. And when you use Canvas to draw the rectangle with the paint, the colors will be rendered along this line.

Body:
Can anyone please explain or describe how the coordinates points in the LinearGradient?

For example: I have my code in this way.

   var gradient = new LinearGradient(0, 0, 500, 500, colors, null, Shader.TileMode.Clamp);
   paint.SetShader(gradient);
   paint.Dither = true;

how it display in the rectangle while applying in the rectangle ?


问:
handle transaction in Linq to sql
I am implementing the asp.net MVC web application, where i am using the Linq to Sql to manipulate the data in database. but in my one of action, i want to insert multiple table entries which are depends upon each other by referring previous insertion Id's. So i just wnat to know how to handle the transaction, like begin transaction, commit,rollback and all like in ADO.net. how to manage this. what if one of insertion get crashed in the middle of manipulation?

Note:- I am not using the Stored procedures here. I am using Lambda expressions and methods. Also these are use in different manager classes.
Example:
For Create Subject - used method in SubjectManager class to insert subject infor, that returns subject Id. within this subjectid i am inserting the let say its chapters with another method in manager class  as ChapterManager. which again returns the ChapterId, on base of this chapeter Id , inserting the Topics of chapter. that again uses Topic manager same like above.in each manger class i am creating dataContext object for the same. and I am controlling all this within a single action in my controller. but worrying about the transaction management. how I can use here ?

答:
The DataContext already includes an embedded transaction object.  For example, let's say you are placing a new order for a customer. You can set up your model so that the following code updates both the Customer AND Order table with a single SubmitChanges.  As long as a foreign key relationship exists between the two tables, the embedded transaction object handles both the Customer update and the Order insert in the same transaction.  Using a TransactionScope object to encase a single DataContext is redundant:</p>

```<code>using (DataContext dc = new DataContext())
{
    Order order = new Order();

    order.ProductID = 283564;
    order.Quantity = 7;
    order.OrderDate = DateTime.Now;

    Customer customer = dc.Customers.Single(c => c.CustomerID == 6);

    customer.LastUpdate = order.OrderDate;
    customer.Orders.Add(order);

    dc.SubmitChanges();
}
</code>```

Title: handle transaction in Linq to sql

Body:
The DataContext already includes an embedded transaction object.  For example, let's say you are placing a new order for a customer. You can set up your model so that the following code updates both the Customer AND Order table with a single SubmitChanges.  As long as a foreign key relationship exists between the two tables, the embedded transaction object handles both the Customer update and the Order insert in the same transaction.  Using a TransactionScope object to encase a single DataContext is redundant:

using (DataContext dc = new DataContext())
{
    Order order = new Order();

    order.ProductID = 283564;
    order.Quantity = 7;
    order.OrderDate = DateTime.Now;

    Customer customer = dc.Customers.Single(c => c.CustomerID == 6);

    customer.LastUpdate = order.OrderDate;
    customer.Orders.Add(order);

    dc.SubmitChanges();
}


问:
ggplot x-axis labels with all x-axis values
I'm plotting ggplot with geom_point. The x-axis will be individuals' ID, and y-axis is variable A. How can I ggplot all and individual ID values on the x-axis without overlapping labels? ID may not be continuous.

df sample (actual rows are much longer)

```<code>> df
ID     A
1      4
2      12
3      45
5      1
</code>```

Code for the plot:

```<code>ggplot(df, aes(x = ID, y = A)) + geom_point()
</code>```

Above code has x-axis in intervals, but not presenting individual ID.

Thanks!

答:
Is this what you're looking for?

```<code>ID <- 1:50
A <- runif(50,1,100)

df <- data.frame(ID,A)

ggplot(df, aes(x = ID, y = A)) +
  geom_point() +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
  scale_x_continuous("ID", labels = as.character(ID), breaks = ID)
</code>```

This will produce this image:

So you'll get a label for every ID-value. If you'd like to remove the gridlines (There are too much for my taste) you can remove them by adding theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())

EDIT: The easier way would be to just use ID as a factor for the plot. like this:

```<code>ggplot(df, aes(x = factor(ID), y = A)) +
  geom_point() +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
  xlab("ID")
</code>```

The advantage of this method is that you don't get empty spaces from missing IDs

EDIT2: Concerning your Problem with overlapping labels: I'm guessing it comes from a large number of IDs to be plotted. There are several ways we can deal with this. So lets say your plot looks like this:

One idea would be to hide every 3rd label from the x-axis by modifying the break argument of the axis:

```<code>ggplot(df, aes(x = factor(ID), y = A)) +
  geom_point() +
  scale_x_discrete(breaks = ID[c(T,F,F)]) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
  xlab("ID")
</code>```

which leads to this:

If hiding labels is not an option, you could split your plot into subplots.

```<code>df$group <- as.numeric(cut(df$ID, 4))

ggplot(df, aes(x = factor(ID), y = A)) +
  geom_point() +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
  xlab("ID") +
  facet_wrap(~group, ncol = 1, scales = "free_x")
</code>```

which leads to this:

Body:
I'm plotting ggplot with geom_point. The x-axis will be individuals' ID, and y-axis is variable A. How can I ggplot all and individual ID values on the x-axis without overlapping labels? ID may not be continuous.

df sample (actual rows are much longer)

> df
ID     A
1      4
2      12
3      45
5      1

Code for the plot:

ggplot(df, aes(x = ID, y = A)) + geom_point()

Above code has x-axis in intervals, but not presenting individual ID.

Thanks!

Body:
Is this what you're looking for?

ID <- 1:50
A <- runif(50,1,100)

df <- data.frame(ID,A)

ggplot(df, aes(x = ID, y = A)) +
  geom_point() +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
  scale_x_continuous("ID", labels = as.character(ID), breaks = ID)

This will produce this image:

So you'll get a label for every ID-value. If you'd like to remove the gridlines (There are too much for my taste) you can remove them by adding theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())

EDIT: The easier way would be to just use ID as a factor for the plot. like this:

ggplot(df, aes(x = factor(ID), y = A)) +
  geom_point() +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
  xlab("ID")

The advantage of this method is that you don't get empty spaces from missing IDs

EDIT2: Concerning your Problem with overlapping labels: I'm guessing it comes from a large number of IDs to be plotted. There are several ways we can deal with this. So lets say your plot looks like this:

One idea would be to hide every 3rd label from the x-axis by modifying the break argument of the axis:

ggplot(df, aes(x = factor(ID), y = A)) +
  geom_point() +
  scale_x_discrete(breaks = ID[c(T,F,F)]) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
  xlab("ID")

which leads to this:

If hiding labels is not an option, you could split your plot into subplots.

df$group <- as.numeric(cut(df$ID, 4))

ggplot(df, aes(x = factor(ID), y = A)) +
  geom_point() +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5)) +
  xlab("ID") +
  facet_wrap(~group, ncol = 1, scales = "free_x")

which leads to this:


问:
Compile shared library linux gcc/g++ cpp

I have successfully compiled and created a shared object, but I'm not sure if it is truly shared and linked/analog to DLL.Could you tell me if it is right?
    I have shared.h, main.cpp, nameOfLib.cpp.

```<code>shared.h

#ifndef SHARED_H
   #define SHARED_H
   int helpingLib();
#endif

main.cpp

#include "shared.h"
#pragma once

int main(){
 helpingLib();
 return 0;
}

nameOfLib.cpp

#pragma once
int helpingLib(){ return 20;}

Console:
g++ -shared -fPIC nameOfLib.cpp -o renameTo.so
//create local var
export $MY_LD_PATH = /home/student/Documents/Total/LinuxXlib/renameTo.so
g++ main.cpp -Wl,$MY_LD_PATH -o executable
</code>```

First of all is it is a truly shareable library?

It works correctly, even with sophisticated cpp code in nameOfLib.cpp

答:
I'm not sure if it is truly shared

Yes, it is.

Your command line to link against this shared library is wrong though. Do this instead:

```<code>g++ main.cpp -o executable /home/student/Documents/Total/LinuxXlib/renameTo.so
</code>```

Body:
I have successfully compiled and created a shared object, but I'm not sure if it is truly shared and linked/analog to DLL.Could you tell me if it is right?
    I have shared.h, main.cpp, nameOfLib.cpp.

shared.h

#ifndef SHARED_H
   #define SHARED_H
   int helpingLib();
#endif

main.cpp

#include "shared.h"
#pragma once

int main(){
 helpingLib();
 return 0;
}

nameOfLib.cpp

#pragma once
int helpingLib(){ return 20;}

Console:
g++ -shared -fPIC nameOfLib.cpp -o renameTo.so
//create local var
export $MY_LD_PATH = /home/student/Documents/Total/LinuxXlib/renameTo.so
g++ main.cpp -Wl,$MY_LD_PATH -o executable

First of all is it is a truly shareable library?

It works correctly, even with sophisticated cpp code in nameOfLib.cpp

Body:
I'm not sure if it is truly shared

Yes, it is.

Your command line to link against this shared library is wrong though. Do this instead:

g++ main.cpp -o executable /home/student/Documents/Total/LinuxXlib/renameTo.so


问:
Problems with newline in Graphics2D.drawString
g2 is an instance of the class Graphics2D. I'd like to be able to draw multi-line text, but that requires a newline character. The following code renders in one line.

```<code>String newline = System.getProperty("line.separator");
g2.drawString("part1\r\n" + newline + "part2", x, y);
</code>```

答:
Here's a snippet I used to draw text in a JPanel with tab expansion and multiple lines:

```<code>import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;

public class Scratch {
    public static void main(String argv[]) {
        JFrame frame = new JFrame("FrameDemo");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel() {
            @Override
            public void paint(Graphics graphics) {
                graphics.drawRect(100, 100, 1, 1);
                String message =
                        "abc\tdef\n" +
                        "abcx\tdef\tghi\n" +
                        "xxxxxxxxdef\n" +
                        "xxxxxxxxxxxxxxxxghi\n";
                int x = 100;
                int y = 100;
                FontMetrics fontMetrics = graphics.getFontMetrics();
                Rectangle2D tabBounds = fontMetrics.getStringBounds(
                        "xxxxxxxx",
                        graphics);
                int tabWidth = (int)tabBounds.getWidth();
                String[] lines = message.split("\n");
                for (String line : lines) {
                    int xColumn = x;
                    String[] columns = line.split("\t");
                    for (String column : columns) {
                        if (xColumn != x) {
                            // Align to tab stop.
                            xColumn += tabWidth - (xColumn-x) % tabWidth;
                        }
                        Rectangle2D columnBounds = fontMetrics.getStringBounds(
                                column,
                                graphics);
                        graphics.drawString(
                                column,
                                xColumn,
                                y + fontMetrics.getAscent());
                        xColumn += columnBounds.getWidth();
                    }
                    y += fontMetrics.getHeight();
                }
            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(400, 200);
            }
        };
        frame.getContentPane().add(panel, BorderLayout.CENTER);

        frame.pack();

        frame.setVisible(true);    }
}
</code>```

It really seemed like Utilities.drawTabbedText() was promising, but I couldn't figure out what it needed as input.

Body:
g2 is an instance of the class Graphics2D. I'd like to be able to draw multi-line text, but that requires a newline character. The following code renders in one line.

String newline = System.getProperty("line.separator");
g2.drawString("part1\r\n" + newline + "part2", x, y);

Body:
Here's a snippet I used to draw text in a JPanel with tab expansion and multiple lines:

import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;

public class Scratch {
    public static void main(String argv[]) {
        JFrame frame = new JFrame("FrameDemo");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel() {
            @Override
            public void paint(Graphics graphics) {
                graphics.drawRect(100, 100, 1, 1);
                String message =
                        "abc\tdef\n" +
                        "abcx\tdef\tghi\n" +
                        "xxxxxxxxdef\n" +
                        "xxxxxxxxxxxxxxxxghi\n";
                int x = 100;
                int y = 100;
                FontMetrics fontMetrics = graphics.getFontMetrics();
                Rectangle2D tabBounds = fontMetrics.getStringBounds(
                        "xxxxxxxx",
                        graphics);
                int tabWidth = (int)tabBounds.getWidth();
                String[] lines = message.split("\n");
                for (String line : lines) {
                    int xColumn = x;
                    String[] columns = line.split("\t");
                    for (String column : columns) {
                        if (xColumn != x) {
                            // Align to tab stop.
                            xColumn += tabWidth - (xColumn-x) % tabWidth;
                        }
                        Rectangle2D columnBounds = fontMetrics.getStringBounds(
                                column,
                                graphics);
                        graphics.drawString(
                                column,
                                xColumn,
                                y + fontMetrics.getAscent());
                        xColumn += columnBounds.getWidth();
                    }
                    y += fontMetrics.getHeight();
                }
            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(400, 200);
            }
        };
        frame.getContentPane().add(panel, BorderLayout.CENTER);

        frame.pack();

        frame.setVisible(true);    }
}

It really seemed like Utilities.drawTabbedText() was promising, but I couldn't figure out what it needed as input.