问:
Creating a scraper that isolates a part of a page, and then scrapes the title and first paragraph from every link
```<code>def custom_scrape(e1, master):
session = requests.Session()
# selectWikiPage = input("Please enter the Wikipedia page you wish to scrape from")
selectWikiPage = e1.get()
if "wikipedia" in selectWikiPage: #turn this into a regular expression
    html = session.post(selectWikiPage)
    bsObj = BeautifulSoup(html.text, "html.parser")
    findReferences = bsObj.find('ol', {'class': 'references'})  # isolate refereces section of page
    href = BeautifulSoup(str(findReferences), "html.parser")
    links = [a["href"] for a in href.find_all("a", href=True)]
    for link in links:
        print("Link: " + link)
else:
    print("Error: Please enter a valid Wikipedia URL")
</code>```

As you can see, I am able to isolate the references section of the Wikipedia page, but I am unsure as how to make it enter the isolated links, and then carry out the actions aforementioned in the title.

答:
You can use selenium driver to simulate click on those links.

```<code><body>
<a href="hello.html"   target="_self">Hello</a>
</body>
</code>```

To click on link hello.html do like this

```<code>link = driver.find_element_by_link_text('Details')
link.click()
</code>```

Body:
def custom_scrape(e1, master):
session = requests.Session()
# selectWikiPage = input("Please enter the Wikipedia page you wish to scrape from")
selectWikiPage = e1.get()
if "wikipedia" in selectWikiPage: #turn this into a regular expression
    html = session.post(selectWikiPage)
    bsObj = BeautifulSoup(html.text, "html.parser")
    findReferences = bsObj.find('ol', {'class': 'references'})  # isolate refereces section of page
    href = BeautifulSoup(str(findReferences), "html.parser")
    links = [a["href"] for a in href.find_all("a", href=True)]
    for link in links:
        print("Link: " + link)
else:
    print("Error: Please enter a valid Wikipedia URL")

As you can see, I am able to isolate the references section of the Wikipedia page, but I am unsure as how to make it enter the isolated links, and then carry out the actions aforementioned in the title.

Body:
You can use selenium driver to simulate click on those links.

<body>
<a href="hello.html"   target="_self">Hello</a>
</body>

To click on link hello.html do like this

link = driver.find_element_by_link_text('Details')
link.click()


来源: stackexchange

问:
how do I detect a "long Tap" gesture on a UITableViewCell
In my app I'm displaying a table with different elements if a user taps on a tableviewcell a detailview gets pushed onto the navigationstack.
I now want to provide the user with abilty to "long tap" on a tableviewcell in order to pop up an alertview showing the user different options that can be applied on said tableviewcell (email information to a friend, print it out, add to bookmarks etc)

how do i implement a "long tap" gesture recognizer on a UITableViewCell??

thanks for your help

答:
on a touch down you would use a timer to fire off a method call in X number of seconds (how ever long you want the long touch to be). Then if they let go before that time you cancel the timer:</p>

```<code>-(void) startSingleTouch:(UITouch*)touch
{
 tapTouch = touch;
 tapTimer = [[NSTimer scheduledTimerWithTimeInterval:tapDelay target:self selector:@selector(singleTapGestureSucceeded) userInfo:nil repeats:NO] retain];
}

-(void) cancelSingleTouch
{
 if(tapTimer)
 {
  [tapTimer invalidate];
  [tapTimer release];
 }

 tapTouch = nil;
 tapTimer = nil;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
on a touch down you would use a timer to fire off a method call in X number of seconds (how ever long you want the long touch to be). Then if they let go before that time you cancel the timer:

-(void) startSingleTouch:(UITouch*)touch
{
 tapTouch = touch;
 tapTimer = [[NSTimer scheduledTimerWithTimeInterval:tapDelay target:self selector:@selector(singleTapGestureSucceeded) userInfo:nil repeats:NO] retain];
}

-(void) cancelSingleTouch
{
 if(tapTimer)
 {
  [tapTimer invalidate];
  [tapTimer release];
 }

 tapTouch = nil;
 tapTimer = nil;
}


问:
Histogram Binning of Gradient Vectors
I am working on a project that has a small component requiring the comparison of distributions over image gradients. Assume I have computed the image gradients in the x and y directions using a Sobel filter and have for each pixel a 2-vector. Obviously getting the magnitude and direction is reasonably trivial and is as follows:

However, what is not clear to me is how to bin these two components in to a two dimensional histogram for an arbitrary number of bins.

I had considered something along these lines(written in browser):

```<code>//Assuming normalised magnitudes.
//Histogram dimensions are bins * bins.
int getHistIdx(float mag, float dir, int bins) {
    const int magInt = reinterpret_cast<int>(mag);
    const int dirInt = reinterpret_cast<int>(dir);
    const int magMod = reinterpret_cast<int>(static_cast<float>(1.0));
    const int dirMod = reinterpret_cast<int>(static_cast<float>(TWO_PI));

    const int idxMag = (magInt % magMod) & bins
    const int idxDir = (dirInt % dirMod) & bins;
    return idxMag * bins + idxDir;
}
</code>```

However, I suspect that the mod operation will introduce a lot of incorrect overlap, i.e. completely different gradients getting placed in to the same bin.

Any insight in to this problem would be very much appreciated.

I would like to avoid using any off the shelf libraries as I want to keep this project as dependency light as possible. Also I intend to implement this in CUDA.

答:
This is more of a what is an histogram question? rather than one of your tags. Two things:

In a 2D plain two directions equal by modulation of 2pi are in fact the same - so it makes sense to modulate.

I see no practical or logical reason of modulating the norms.

Next, you say you want a "two dimensional histogram", but return a single number. A 2D histogram, and what would make sense in your context, is a 3D plot - the plane is theta/R, 2 indexed, while the 3D axis is the "count".

So first suggestion, return

```<code>return Pair<int,int>(idxMag,idxDir);
</code>```

Then you can make a 2D histogram, or 2 2D histograms.

Regarding the "number of bins"

this is use case dependent. You need to define the number of bins you want (maybe different for theta and R). Maybe just some constant 10 bins? Maybe it should depend on the amount of vectors? In any case, you need a function that receives either the number of vectors, or the total set of vectors, and returns the number of bins for each axis. This could be a constant (10 bins) initially, and you can play with it. Once you decide on the number of bins:

Determine the bins

For a bounded case such as 0<theta<2 pi, this is easy. Divide the interval equally into the number of bins, assuming a flat distribution. Your modulation actually handles this well - if you would have actually modulated by 2*pi, which you didn't. You would still need to determine the bin bounds though.

For R this gets trickier, as this is unbounded. Two options here, but both rely on the same tactic - choose a maximal bin. Either arbitrarily (Say R=10), so any vector longer than that is placed in the "longer than max" bin. The rest is divided equally (for example, though you could choose other distributions). Another option is for the longest vector to determine the edge of the maximal bin.

Getting the index

Once you have the bins, you need to search the magnitude/direction of the current vector in your bins. If bins are pairs representing min/max of bin (and maybe an index), say in a linked list, then it would be something like (for mag for example):

```<code>bin = histogram.first;
while ( mag > bin.min ) bin = bin.next;
magIdx = bin.index;
</code>```

If the bin does not hold the index you can just use a counter and increase it in the while. Also, for the magnitude the final bin should hold "infinity" or some large number as a limit.  Note this has nothing to do with modulation, though that would work for your direction - as you have coded. I don't see how this makes sense for the norm.

Bottom line though, you have to think a bit about what you want. In any case all the "objects" here are trivial enough to write yourself, or  even use small arrays.

ContentLicense: CC BY-SA 3.0

Title: Histogram Binning of Gradient Vectors

Body:
I am working on a project that has a small component requiring the comparison of distributions over image gradients. Assume I have computed the image gradients in the x and y directions using a Sobel filter and have for each pixel a 2-vector. Obviously getting the magnitude and direction is reasonably trivial and is as follows:

However, what is not clear to me is how to bin these two components in to a two dimensional histogram for an arbitrary number of bins.

I had considered something along these lines(written in browser):

//Assuming normalised magnitudes.
//Histogram dimensions are bins * bins.
int getHistIdx(float mag, float dir, int bins) {
    const int magInt = reinterpret_cast<int>(mag);
    const int dirInt = reinterpret_cast<int>(dir);
    const int magMod = reinterpret_cast<int>(static_cast<float>(1.0));
    const int dirMod = reinterpret_cast<int>(static_cast<float>(TWO_PI));

    const int idxMag = (magInt % magMod) & bins
    const int idxDir = (dirInt % dirMod) & bins;
    return idxMag * bins + idxDir;
}

However, I suspect that the mod operation will introduce a lot of incorrect overlap, i.e. completely different gradients getting placed in to the same bin.

Any insight in to this problem would be very much appreciated.

I would like to avoid using any off the shelf libraries as I want to keep this project as dependency light as possible. Also I intend to implement this in CUDA.

Body:
This is more of a what is an histogram question? rather than one of your tags. Two things:

In a 2D plain two directions equal by modulation of 2pi are in fact the same - so it makes sense to modulate.

I see no practical or logical reason of modulating the norms.

Next, you say you want a "two dimensional histogram", but return a single number. A 2D histogram, and what would make sense in your context, is a 3D plot - the plane is theta/R, 2 indexed, while the 3D axis is the "count".

So first suggestion, return

return Pair<int,int>(idxMag,idxDir);

Then you can make a 2D histogram, or 2 2D histograms.

Regarding the "number of bins"

this is use case dependent. You need to define the number of bins you want (maybe different for theta and R). Maybe just some constant 10 bins? Maybe it should depend on the amount of vectors? In any case, you need a function that receives either the number of vectors, or the total set of vectors, and returns the number of bins for each axis. This could be a constant (10 bins) initially, and you can play with it. Once you decide on the number of bins:

Determine the bins

For a bounded case such as 0<theta<2 pi, this is easy. Divide the interval equally into the number of bins, assuming a flat distribution. Your modulation actually handles this well - if you would have actually modulated by 2*pi, which you didn't. You would still need to determine the bin bounds though.

For R this gets trickier, as this is unbounded. Two options here, but both rely on the same tactic - choose a maximal bin. Either arbitrarily (Say R=10), so any vector longer than that is placed in the "longer than max" bin. The rest is divided equally (for example, though you could choose other distributions). Another option is for the longest vector to determine the edge of the maximal bin.

Getting the index

Once you have the bins, you need to search the magnitude/direction of the current vector in your bins. If bins are pairs representing min/max of bin (and maybe an index), say in a linked list, then it would be something like (for mag for example):

bin = histogram.first;
while ( mag > bin.min ) bin = bin.next;
magIdx = bin.index;

If the bin does not hold the index you can just use a counter and increase it in the while. Also, for the magnitude the final bin should hold "infinity" or some large number as a limit.  Note this has nothing to do with modulation, though that would work for your direction - as you have coded. I don't see how this makes sense for the norm.

Bottom line though, you have to think a bit about what you want. In any case all the "objects" here are trivial enough to write yourself, or  even use small arrays.


问:
Retrieve the right clicked QPushButton object name in qt
I already have this function to retrieve the clicked QPushButton object name:

```<code>void MainWindow::clickedBtnInfo()
{
    QPushButton *btnSender = qobject_cast<QPushButton*>(sender()); // retrieve the button you have clicked
    QString *clickedBtnName = btnSender->objectName(); // retrive the object name from the clicked button
    qDebug() << clickedBtnName;
}
</code>```

And I checked this website to implement the rightClicked signal.

But I want to know what I can do to retrieve the QPushButton object name which is right clicked.
 Thanks.

An edit of how I implement the rightClicked signal:

```<code>void MainWindow::onRightClicked()
{
    qDebug() << "User right clicked me";
}

void MainWindow::mousePressEvent(QMouseEvent *e)
{
    if(e->button() == Qt::RightButton) {
        emit rightClicked();
    }
}
</code>```

And connect like this:

```<code>connect(this, SIGNAL(rightClicked()), this, SLOT(onRightClicked()));
</code>```

Sorry for not explaining my question completely before. BTW, I am just very new to Qt, So hope to get some specifically explained answers.
 Thanks a lot.

答:
The link you provided in the question does the right thing. You need to extend QPushButton and not QMainWindow! Simply copy the sources from https://stackoverflow.com/a/15658863/3767076 into your project (if you need both clicks, check the comment below).

After that, you can use the QRightClickButton instead of a QPushButton. If you created your UI with the designer, you can right-click the button in the ui and set it as placeholder for QRightClickButton.

Body:
I already have this function to retrieve the clicked QPushButton object name:

void MainWindow::clickedBtnInfo()
{
    QPushButton *btnSender = qobject_cast<QPushButton*>(sender()); // retrieve the button you have clicked
    QString *clickedBtnName = btnSender->objectName(); // retrive the object name from the clicked button
    qDebug() << clickedBtnName;
}

And I checked this website to implement the rightClicked signal.

But I want to know what I can do to retrieve the QPushButton object name which is right clicked.
 Thanks.

An edit of how I implement the rightClicked signal:

void MainWindow::onRightClicked()
{
    qDebug() << "User right clicked me";
}

void MainWindow::mousePressEvent(QMouseEvent *e)
{
    if(e->button() == Qt::RightButton) {
        emit rightClicked();
    }
}

And connect like this:

connect(this, SIGNAL(rightClicked()), this, SLOT(onRightClicked()));

Sorry for not explaining my question completely before. BTW, I am just very new to Qt, So hope to get some specifically explained answers.
 Thanks a lot.


问:
Is there a way to enable post process actions in a Jenkins multibranch pipeline job?
I have a projects that uses a multibranch pipeline to fetch all branches of a git server and then builds it. I need to do some post build actions there, but for some reason there is not post action configuration available in the builds. Neither in the multibranch pipeline nor the fetched sub projects. But the post build configuration is available in normal Jenkins jobs.

So far the only way I know of is to adjust the Jenkinsfile. But it would be great to do some work in the Jenkins frontend instead.
Edit: Another way I found is to create a Freestyle project that will be triggered when the target branch inside the multibranch project has been successfully build. The downside here is that the project has to be run a second time because I cannot access the jar files of the other branch.

Is there a way to add post build steps to such a job? If so, how?

答:
The main idea behind the Jenkinsfile is to have your "infrastructure as code". So going by this, your job configuration including the post-build steps, should be version controlled in SCM.

To add post build steps to a Multibranch Pipeline:

```<code>node {

    try {
        stage("Checkout") {
            // checkout scm
        }

        stage("Build & test") {
            // build & Unit test
        }
    } catch (e) {
        // fail the build if an exception is thrown
        currentBuild.result = "FAILED"
        throw e
    } finally {
        // Post build steps here
        /* Success or failure, always run post build steps */
        // send email
        // publish test results etc etc
    }
}
</code>```

For most of the post-build steps you would want there are online examples of them on how to write in pipeline format.  If you have any specific one please list it

Body:
The main idea behind the Jenkinsfile is to have your "infrastructure as code". So going by this, your job configuration including the post-build steps, should be version controlled in SCM.

To add post build steps to a Multibranch Pipeline:

node {

    try {
        stage("Checkout") {
            // checkout scm
        }

        stage("Build & test") {
            // build & Unit test
        }
    } catch (e) {
        // fail the build if an exception is thrown
        currentBuild.result = "FAILED"
        throw e
    } finally {
        // Post build steps here
        /* Success or failure, always run post build steps */
        // send email
        // publish test results etc etc
    }
}

For most of the post-build steps you would want there are online examples of them on how to write in pipeline format.  If you have any specific one please list it


问:
Powershell: resolve path that might not exist?
I'm trying to process a list of files that may or may not be up to date and may or may not yet exist.  In doing so, I need to resolve the full path of an item, even though the item may be specified with relative paths.  However, Resolve-Path prints an error when used with a non-existant file.

For example, What's the simplest, cleanest way to resolve ".\newdir\newfile.txt" to "C:\Current\Working\Directory\newdir\newfile.txt" in Powershell?

Note that System.IO.Path's static method use with the process's working directory - which isn't the powershell current location.

答:
There is an accepted answer here, but it is quite lengthy and there is a simpler alternative available.

In any recent version of Powershell, you can use Test-Path -IsValid -Path 'C:\Probably Fake\Path.txt'

This simply verifies that there are no illegal characters in the path and that the path could be used to store a file. If the target doesn't exist, Test-Path won't care in this instance -- it's only being asked to test if the provided path is potentially valid.

ContentLicense: CC BY-SA 4.0


问:
Yii2: Error 404 after using Gii for a new database schema
I used Gii code generator to create a model and its CRUD for a table located in the non public schema but then the URL is not working: Error 404 not found.

I have a PostgreSQL database called travels with two schemas: public and laboratory. Everything works perfect using the public schema.

Now I need to use the laboratory schema that I created recently. So I created the model (a minor problem: autocomplete doesn't work for laboratory schema but the model is created anyway):

Then I created the CRUD:

Then I try to see the results:

It's my common/config/main-local.php file:

```<code><?php
return [
    'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'pgsql:host=localhost;dbname=travel',
            'username' => 'aaaa',
            'password' => 'bbbb',
            'charset' => 'utf8',
        ],
    ],
];
</code>```

答:
The problem was that I modified this file before and something was not right:

/vendor/yiisoft/yii2-gii/generators/crud/default/views

The problem about model autocomplete is still there.

Body:
I used Gii code generator to create a model and its CRUD for a table located in the non public schema but then the URL is not working: Error 404 not found.

I have a PostgreSQL database called travels with two schemas: public and laboratory. Everything works perfect using the public schema.

Now I need to use the laboratory schema that I created recently. So I created the model (a minor problem: autocomplete doesn't work for laboratory schema but the model is created anyway):

Then I created the CRUD:

Then I try to see the results:

It's my common/config/main-local.php file:

<?php
return [
    'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'pgsql:host=localhost;dbname=travel',
            'username' => 'aaaa',
            'password' => 'bbbb',
            'charset' => 'utf8',
        ],
    ],
];


问:
JSON Cookie problem
I'm using CookieJar to read and write an Array of Objects to a cookie.

In my ClickButton function I do read the existing cookie and add to the Array of objects before I over write it again.

Here are the JSON string being saved:

```<code>[{"id":"3","value":"33333","text":"Bbbbb"},
 [{"id":"3","value":"33333","text":"Bbbbb"},
  [{"id":"5","value":"55555","text":"xxxxxx"}]]]
</code>```

I want it really to be:

```<code>[{"id":"3","value":"33333","text":"Bbbbb"},
 {"id":"3","value":"33333","text":"Bbbbb"},
 {"id":"5","value":"55555","text":"xxxxxx"}]
</code>```

Any ideas what I'm doing wrong here? I struggled with this for over a day now :)

Code:

```<code><script type="text/javascript">
    function Display() {
        jar = new CookieJar({
            expires: 3600,   // seconds
            path: '/'
        });

        var itemArray = jar.get("Items");
        if (itemArray) {
            tmpDiv.innerHTML += itemArray.toJSONString() + '<br/>';

            for (var i = 0; i < itemArray.length; i++) {
                tmpDiv.innerHTML += itemArray[i].item[0].value + '<br/>';
            }
        }
    }

    function ClickButton(id, value, text) {
        jar = new CookieJar({
            expires: 3600,   // seconds
            path: '/'
        });

        var tmpA = jar.get("Items");
        var items = new Array;

        items.push({ "id": id, "value": value, "text": text });

        // If any existing values in the cookie, load and add to Array
        if (tmpA != null)
            items.push(tmpA);

        tmpDiv.innerHTML += items.toJSONString() + "<br/>";
        jar.put("Items", items);
    }
</script>
</code>```

答:
Each time your button is clicked, you're creating a new array called items, then adding the old array called tmpA to it.  Then, you stash items, which now has a new child array inside it (representing the previous value, which itself was an array).

Instead of:

```<code>    if (tmpA != null)
        items.push(tmpA);
</code>```

You should have:

```<code>    if (tmpA != null)
        items = items.concat(tmpA); // this will merge the two arrays
</code>```

Title: JSON Cookie problem

Body:
I'm using CookieJar to read and write an Array of Objects to a cookie.

In my ClickButton function I do read the existing cookie and add to the Array of objects before I over write it again.

Here are the JSON string being saved:

[{"id":"3","value":"33333","text":"Bbbbb"},
 [{"id":"3","value":"33333","text":"Bbbbb"},
  [{"id":"5","value":"55555","text":"xxxxxx"}]]]

I want it really to be:

[{"id":"3","value":"33333","text":"Bbbbb"},
 {"id":"3","value":"33333","text":"Bbbbb"},
 {"id":"5","value":"55555","text":"xxxxxx"}]

Any ideas what I'm doing wrong here? I struggled with this for over a day now :)

Code:

Body:
Each time your button is clicked, you're creating a new array called items, then adding the old array called tmpA to it.  Then, you stash items, which now has a new child array inside it (representing the previous value, which itself was an array).

Instead of:

    if (tmpA != null)
        items.push(tmpA);

You should have:

    if (tmpA != null)
        items = items.concat(tmpA); // this will merge the two arrays


问:
Nested attributes saving with empty values rails 5
I have two models. order and order has many order_products.
i am using angularjs post request to create an order.
angular controller:

```<code>return $scope.submitForm = function() {
    var order_products_attributes;
    if ($scope.buyer.selected_item) {
        $scope.order.company_id = $scope.buyer.selected_item.id;
    }
    order_products_attributes = [];
    var qtt = 0
    $scope.op.forEach(function(obj) {
        var newObj;
        var total = parseInt(obj.quantity) * parseInt(obj.batch.selected_item[0].pack_size);
        qtt= qtt+total;
        newObj = {
            product_id: parseInt(obj.product.selected_item[0].id),
            product_batch_id: parseInt(obj.batch.selected_item[0].id),
            price: parseInt(obj.price),
            quantity: parseInt(obj.quantity),
            free_quantity: parseInt(obj.free_quantity),
            total_quantity:total ,
            total_amount: parseInt(obj.total_amount)
        };
        return order_products_attributes.push(newObj);
    });
    $scope.order.order_products_attributes = order_products_attributes;
    $scope.order.price = $scope.amount;
    $scope.order.discount = $scope.discount;
    $scope.order.quantity = qtt;
    $scope.order.status = 'Booked'
    // $scope.order.dc_date = $("#orderDate").find("input").val()
    $scope.order.order_date = $("#orderDate").find("input").val()
    // $scope.order.delivery_date = $("#orderDate").find("input").val()
    $scope.order.delivery_date = $("#deliveryDate").find("input").val()

    var st = $("#orderDate").find("input").val().split("/");
    var dd = new Date(st[2],st[1]-1,st[0]);
    dd.setDate(dd.getDate()+30);
    $scope.order.due_date = dd;

    $scope.order.authenticity_token = $scope.authenticity_token;
    $scope.order.type = type;
    // if($scope.p_type.selected_item)
    //     $scope.order.payment_type = $scope.p_type.selected_item.value;
    console.log($scope.order)

    return $http.post('/orders', $scope.order).then(function(response) {
        response.data;

        $window.location.href = '/orders/invoice_print/'+response.data.id;
    });
};
</code>```

following is the request.

```<code>Parameters: {"company_id"=>13, "order_products_attributes"=>[{"product_id"=>6, "product_batch_id"=>26, "price"=>1100, "quantity"=>1, "free_quantity"=>nil, "total_quantity"=>10, "total_amount"=>11000}], "price"=>11000, "discount"=>0, "quantity"=>10, "status"=>"Booked", "order_date"=>"13/11/2017", "delivery_date"=>"13/11/2017", "due_date"=>"2017-12-12T19:00:00.000Z", "authenticity_token"=>"OJx5FtSx6+e0FEhlRdUIqzfW7OhA18/Y3B3ETAqye8en3WC49QhR0smmz3MGoqRfsqmckMFLhVsz2ldRnmDXXA==", "type"=>"RegisteredOrder", "order"=>{"company_id"=>13, "price"=>11000, "quantity"=>10, "order_date"=>"13/11/2017", "delivery_date"=>"13/11/2017", "discount"=>0, "type"=>"RegisteredOrder", "due_date"=>"2017-12-12T19:00:00.000Z"}}
</code>```

My models are

```<code>class Order < ApplicationRecord
    has_many :order_products, inverse_of: :order, :dependent => :destroy
    accepts_nested_attributes_for :order_products
end
class OrderProduct < ApplicationRecord
    belongs_to :product
    belongs_to :order
end
</code>```

Controller:

```<code>@order = Order.new(order_params)
status_value_id = StatusValue.where(:status_val=> 'Booked').where(:status_type => 'sale-order').first.id
@order.order_products_attributes = params["order_products_attributes"]
@order.save

params.require(:order).permit(:status,:company_id, :type, :price,:quantity,:discount, :order_date, :delivery_date ,:due_date, :dc_date, :dc_number, :order_number, :invoice_number,  :special_instruction,order_products_attributes: [:id,:product_id, :description, :product_batch_id, :quantity,:pack_size,:total_quantity, :price, :discount, :discount_percentage, :total_amount])
</code>```

It creates order products but all attributes are set to null. following is the output. it works perfectly fine in rails 4 but not working in rails 5.

```<code>INSERT INTO "orders" ("company_id", "price", "quantity", "order_date", "delivery_date", "created_at", "updated_at", "discount", "order_number", "invoice_number", "type", "dc_number", "user_id", "due_date", "status_value_id") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15) RETURNING "id"  [["company_id", 13], ["price", 11000.0], ["quantity", 10], ["order_date", 2017-11-12 19:00:00 UTC], ["delivery_date", 2017-11-12 19:00:00 UTC], ["created_at", 2017-11-13 06:06:52 UTC], ["updated_at", 2017-11-13 06:06:52 UTC], ["discount", 0.0], ["order_number", 26], ["invoice_number", 26], ["type", "RegisteredOrder"], ["dc_number", "10"], ["user_id", 1], ["due_date", 2017-12-12 19:00:00 UTC], ["status_value_id", 9]]
SQL (16.0ms)  INSERT INTO "order_products" ("order_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["order_id", 90], ["created_at", 2017-11-13 06:06:52 UTC], ["updated_at", 2017-11-13 06:06:52 UTC]]
</code>```

答:
it finally worked with addition of

```<code>@order.order_products_attributes = order_products_attributes_params[:order_products_attributes]
</code>```

to wasif's answer.

order_products_attributes_params was returning a hash { [ {} , {} ] } so I extracted array of order_products_attributes from that

Body:
I have two models. order and order has many order_products.
i am using angularjs post request to create an order.
angular controller:

return $scope.submitForm = function() {
    var order_products_attributes;
    if ($scope.buyer.selected_item) {
        $scope.order.company_id = $scope.buyer.selected_item.id;
    }
    order_products_attributes = [];
    var qtt = 0
    $scope.op.forEach(function(obj) {
        var newObj;
        var total = parseInt(obj.quantity) * parseInt(obj.batch.selected_item[0].pack_size);
        qtt= qtt+total;
        newObj = {
            product_id: parseInt(obj.product.selected_item[0].id),
            product_batch_id: parseInt(obj.batch.selected_item[0].id),
            price: parseInt(obj.price),
            quantity: parseInt(obj.quantity),
            free_quantity: parseInt(obj.free_quantity),
            total_quantity:total ,
            total_amount: parseInt(obj.total_amount)
        };
        return order_products_attributes.push(newObj);
    });
    $scope.order.order_products_attributes = order_products_attributes;
    $scope.order.price = $scope.amount;
    $scope.order.discount = $scope.discount;
    $scope.order.quantity = qtt;
    $scope.order.status = 'Booked'
    // $scope.order.dc_date = $("#orderDate").find("input").val()
    $scope.order.order_date = $("#orderDate").find("input").val()
    // $scope.order.delivery_date = $("#orderDate").find("input").val()
    $scope.order.delivery_date = $("#deliveryDate").find("input").val()

    var st = $("#orderDate").find("input").val().split("/");
    var dd = new Date(st[2],st[1]-1,st[0]);
    dd.setDate(dd.getDate()+30);
    $scope.order.due_date = dd;

    $scope.order.authenticity_token = $scope.authenticity_token;
    $scope.order.type = type;
    // if($scope.p_type.selected_item)
    //     $scope.order.payment_type = $scope.p_type.selected_item.value;
    console.log($scope.order)

    return $http.post('/orders', $scope.order).then(function(response) {
        response.data;

        $window.location.href = '/orders/invoice_print/'+response.data.id;
    });
};

following is the request.

Parameters: {"company_id"=>13, "order_products_attributes"=>[{"product_id"=>6, "product_batch_id"=>26, "price"=>1100, "quantity"=>1, "free_quantity"=>nil, "total_quantity"=>10, "total_amount"=>11000}], "price"=>11000, "discount"=>0, "quantity"=>10, "status"=>"Booked", "order_date"=>"13/11/2017", "delivery_date"=>"13/11/2017", "due_date"=>"2017-12-12T19:00:00.000Z", "authenticity_token"=>"OJx5FtSx6+e0FEhlRdUIqzfW7OhA18/Y3B3ETAqye8en3WC49QhR0smmz3MGoqRfsqmckMFLhVsz2ldRnmDXXA==", "type"=>"RegisteredOrder", "order"=>{"company_id"=>13, "price"=>11000, "quantity"=>10, "order_date"=>"13/11/2017", "delivery_date"=>"13/11/2017", "discount"=>0, "type"=>"RegisteredOrder", "due_date"=>"2017-12-12T19:00:00.000Z"}}

My models are

class Order < ApplicationRecord
    has_many :order_products, inverse_of: :order, :dependent => :destroy
    accepts_nested_attributes_for :order_products
end
class OrderProduct < ApplicationRecord
    belongs_to :product
    belongs_to :order
end

Controller:

@order = Order.new(order_params)
status_value_id = StatusValue.where(:status_val=> 'Booked').where(:status_type => 'sale-order').first.id
@order.order_products_attributes = params["order_products_attributes"]
@order.save

params.require(:order).permit(:status,:company_id, :type, :price,:quantity,:discount, :order_date, :delivery_date ,:due_date, :dc_date, :dc_number, :order_number, :invoice_number,  :special_instruction,order_products_attributes: [:id,:product_id, :description, :product_batch_id, :quantity,:pack_size,:total_quantity, :price, :discount, :discount_percentage, :total_amount])

It creates order products but all attributes are set to null. following is the output. it works perfectly fine in rails 4 but not working in rails 5.

INSERT INTO "orders" ("company_id", "price", "quantity", "order_date", "delivery_date", "created_at", "updated_at", "discount", "order_number", "invoice_number", "type", "dc_number", "user_id", "due_date", "status_value_id") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15) RETURNING "id"  [["company_id", 13], ["price", 11000.0], ["quantity", 10], ["order_date", 2017-11-12 19:00:00 UTC], ["delivery_date", 2017-11-12 19:00:00 UTC], ["created_at", 2017-11-13 06:06:52 UTC], ["updated_at", 2017-11-13 06:06:52 UTC], ["discount", 0.0], ["order_number", 26], ["invoice_number", 26], ["type", "RegisteredOrder"], ["dc_number", "10"], ["user_id", 1], ["due_date", 2017-12-12 19:00:00 UTC], ["status_value_id", 9]]
SQL (16.0ms)  INSERT INTO "order_products" ("order_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["order_id", 90], ["created_at", 2017-11-13 06:06:52 UTC], ["updated_at", 2017-11-13 06:06:52 UTC]]

Body:
it finally worked with addition of

@order.order_products_attributes = order_products_attributes_params[:order_products_attributes]

to wasif's answer.

order_products_attributes_params was returning a hash { [ {} , {} ] } so I extracted array of order_products_attributes from that


问:
Vim / vi Survival Guide
What are the essential vim commands?  What does a new-user need to know to keep themselves from getting into trouble?  One command per comment, please.</p>

答: I made my first steps using The tutorial here, and have used the reference cheatsheet for a few weeks. And, of course, there's vimtutor in vim/gvim/Macvim.</p>

OwnerDisplayName: tsellon

Title: Vim / vi Survival Guide

LastEditorDisplayName: scraimer


问:
Elasticsearch: how to apply multiple filters to the same value?
Shortly: when a field has multiple values, how can I get only those items where both my filter applies to the SAME value in a multiple-values field?

Details

I have stored in Elasticsearch some items which have a nested field with multiple values, e.g.

```<code>"hits": [
    {
        "name": "John",
        "tickets": [
            {
                "color": "green",
                "code": "001"
            },
            {
                "color": "red",
                "code": "002"
            }
        ]
    },
    {
        "name": "Frank",
        "tickets": [
            {
                "color": "red",
                "code": "001"
            },
            {
                "color": "green",
                "code": "002"
            }
        ]
    }
]
</code>```

Now consider these filters:

```<code>...
filter: [
    { terms: { 'tickets.code': '001' } },
    { terms: { 'tickets.color': 'green' } },
]
...
</code>```

Both items match, because each one of them has at least a ticket with code "001" and each one of them has ticket with color "green".

How do I write my filters so that only the first match, because it has a ticket which has code "001" AND color "green"?

Thank you in advance for any suggestion.

答:
Your problem is caused by the fact that Elasticsearch flattens objects. So internally, your data is represented something like this:

```<code>{
    "name": "John",
    "tickets.color": ["green", "red"],
    "tickets.code": ["001", "002"]
},
{
    "name": "Frank",
    "tickets.color": ["red", "green"],
    "tickets.code": ["001", "002"]
}
</code>```

It's impossible to know which color and code are on the same object. (The original source is also stored, in order to be returned when you make a request, but that's not the data that's queried when you search.)

There are two potential solutions here: denormalization, or nested data type. If you can at all get away with it, denormalization is the better choice here, because it's more efficient. If you denormalize your data, you might end up with a representation like this:

```<code>{
    "name": "John",
    "ticket": {
        "color": "green",
        "code": "001"
    }
},
{
    "name": "John",
    "ticket": {
        "color": "red",
        "code": "002"
    }

},
{
    "name": "Frank",
    "ticket": {
        "color": "red",
        "code": "001"
    }
},
{
    "name": , "Frank",
    "ticket": {
        "color": "green",
        "code": "002"
    }
}
</code>```

If you use a nested data type, you'll have to use a mapping something like this:

```<code>{
     "ticket": {
         "type": "nested",
         "properties": {
             "color": {"type": "keyword"},
             "code": {"type": "keyword"}
         }
     }
}
</code>```

Body:
Shortly: when a field has multiple values, how can I get only those items where both my filter applies to the SAME value in a multiple-values field?

Details

I have stored in Elasticsearch some items which have a nested field with multiple values, e.g.

"hits": [
    {
        "name": "John",
        "tickets": [
            {
                "color": "green",
                "code": "001"
            },
            {
                "color": "red",
                "code": "002"
            }
        ]
    },
    {
        "name": "Frank",
        "tickets": [
            {
                "color": "red",
                "code": "001"
            },
            {
                "color": "green",
                "code": "002"
            }
        ]
    }
]

Now consider these filters:

...
filter: [
    { terms: { 'tickets.code': '001' } },
    { terms: { 'tickets.color': 'green' } },
]
...

Both items match, because each one of them has at least a ticket with code "001" and each one of them has ticket with color "green".

How do I write my filters so that only the first match, because it has a ticket which has code "001" AND color "green"?

Thank you in advance for any suggestion.

Body:
Your problem is caused by the fact that Elasticsearch flattens objects. So internally, your data is represented something like this:

{
    "name": "John",
    "tickets.color": ["green", "red"],
    "tickets.code": ["001", "002"]
},
{
    "name": "Frank",
    "tickets.color": ["red", "green"],
    "tickets.code": ["001", "002"]
}

It's impossible to know which color and code are on the same object. (The original source is also stored, in order to be returned when you make a request, but that's not the data that's queried when you search.)

There are two potential solutions here: denormalization, or nested data type. If you can at all get away with it, denormalization is the better choice here, because it's more efficient. If you denormalize your data, you might end up with a representation like this:

{
    "name": "John",
    "ticket": {
        "color": "green",
        "code": "001"
    }
},
{
    "name": "John",
    "ticket": {
        "color": "red",
        "code": "002"
    }

},
{
    "name": "Frank",
    "ticket": {
        "color": "red",
        "code": "001"
    }
},
{
    "name": , "Frank",
    "ticket": {
        "color": "green",
        "code": "002"
    }
}

If you use a nested data type, you'll have to use a mapping something like this:

{
     "ticket": {
         "type": "nested",
         "properties": {
             "color": {"type": "keyword"},
             "code": {"type": "keyword"}
         }
     }
}


问:
PHP Regex - Get text after some text in brackets
I'm new to regular expressions and try to extract text in a string which starts with a value in brackets on the beginning of a new line until the next string in brackets.

My string:

```<code>   (1x) cat
   dog
   (2) ele(4)phant
   tiger
   (x) fish
   bird
</code>```

I need to get:

```<code>- "1x" and "cat\r\ndog"
- "2" and  "ele(4)phant\r\ntiger"
- "x" and "fish\r\nbird"
</code>```

My regex:

```<code>(\r\n)*(\((.*?)\))(.*)
</code>```

This gets me:

```<code>Match 1
Full match  0-8 `(1x) cat`
Group 2.    0-4 `(1x)`
Group 3.    1-3 `1x`
Group 4.    4-8 ` cat`

Match 2
Full match  13-28   `(2) ele(4)phant`
Group 2.    13-16   `(2)`
Group 3.    14-15   `2`
Group 4.    16-28   ` ele(4)phant`

Match 3
Full match  35-44   `(x) fish `
Group 2.    35-38   `(x)`
Group 3.    36-37   `x`
Group 4.    38-44   ` fish `
</code>```

The problem is that my regex seems to stop at the end of the line so the strings on the new line (dog, tiger, bird) are missing.

Do you have an idea how to also get the content of the next lines until the next match?

答:
You may use

```<code>'~^\(([^()]*)\)(.*(?:\R(?!\([^()]*\)).*)*)~m'
</code>```

See the regex demo

Details

^ - start of a line (due to m modifier, ^ matches the start of a line rather than the start of the whole string)

\( - a (

([^()]*)  - Group 1:

[^()]* - 0+ chars other than ( and ) (you might use your .*? here, if you do not want to overflow across lines, and want to match ( inside (...))

\) - a ) char

(.*(?:\R(?!\([^()]*\)).*)*) - Group 2:

.* - the rest of the line

(?:\R(?!\([^()]*\)).*)* - 0+ sequences of

\R(?!\([^()]*\)) - line break not followed with (...) substring

.* - rest of the line

Body:
I'm new to regular expressions and try to extract text in a string which starts with a value in brackets on the beginning of a new line until the next string in brackets.

My string:

   (1x) cat
   dog
   (2) ele(4)phant
   tiger
   (x) fish
   bird

I need to get:

- "1x" and "cat\r\ndog"
- "2" and  "ele(4)phant\r\ntiger"
- "x" and "fish\r\nbird"

My regex:

(\r\n)*(\((.*?)\))(.*)

This gets me:

Match 1
Full match  0-8 `(1x) cat`
Group 2.    0-4 `(1x)`
Group 3.    1-3 `1x`
Group 4.    4-8 ` cat`

Match 2
Full match  13-28   `(2) ele(4)phant`
Group 2.    13-16   `(2)`
Group 3.    14-15   `2`
Group 4.    16-28   ` ele(4)phant`

Match 3
Full match  35-44   `(x) fish `
Group 2.    35-38   `(x)`
Group 3.    36-37   `x`
Group 4.    38-44   ` fish `

The problem is that my regex seems to stop at the end of the line so the strings on the new line (dog, tiger, bird) are missing.

Do you have an idea how to also get the content of the next lines until the next match?

Body:
You may use

'~^\(([^()]*)\)(.*(?:\R(?!\([^()]*\)).*)*)~m'

See the regex demo

Details

^ - start of a line (due to m modifier, ^ matches the start of a line rather than the start of the whole string)

\( - a (

([^()]*)  - Group 1:

[^()]* - 0+ chars other than ( and ) (you might use your .*? here, if you do not want to overflow across lines, and want to match ( inside (...))

\) - a ) char

(.*(?:\R(?!\([^()]*\)).*)*) - Group 2:

.* - the rest of the line

(?:\R(?!\([^()]*\)).*)* - 0+ sequences of

\R(?!\([^()]*\)) - line break not followed with (...) substring

.* - rest of the line


问:
How to make horizontal navigation bar using Bootstrap?
I have this simple code in HTML using Bootstrap classes to create a navigation bar. I want my navigation bar to be horizontal so I added the navbar-inverse class. However, my navigation bar keeps showing vertical and I can't figure out why it does that even thought I tried different things to fix it.

Home

New features

{{ Auth::user()->name }}

```

答:
I hope navbar-inverse is nothing to do with menu view style I hope it's used to change the color of the menu text and for the view style you should use nav-link in a tag and nav-toggleable in nav tag I hope it's the answer.

I'm sorry if I misunderstood your question

```<code>               <ul class="nav navbar-nav ">
                 <li class="nav-item">
                   <a class="nav-link  active" href="#">Home</a>
                 </li>
                 <li class="nav-item">
                   <a class="nav-link " href="#">New features</a>
                 </li>

               </ul>

               <ul class="nav navbar-nav navbar-right">
                 <li class="nav-item"><a class="nav-item" href="#">{{ Auth::user()->name }}</a></li>
               </ul>

         </nav>
     </div>
</code>```

Body:
I hope navbar-inverse is nothing to do with menu view style I hope it's used to change the color of the menu text and for the view style you should use nav-link in a tag and nav-toggleable in nav tag I hope it's the answer.

I'm sorry if I misunderstood your question

               <ul class="nav navbar-nav ">
                 <li class="nav-item">
                   <a class="nav-link  active" href="#">Home</a>
                 </li>
                 <li class="nav-item">
                   <a class="nav-link " href="#">New features</a>
                 </li>

               </ul>

               <ul class="nav navbar-nav navbar-right">
                 <li class="nav-item"><a class="nav-item" href="#">{{ Auth::user()->name }}</a></li>
               </ul>

         </nav>
     </div>


问:
How to show or hide Primefaces chart Legend independently when you have two charts in the same view?
I have 2 charts in the same page. I'd like to show legends just in one chart, not both, but I have just a global solution. Thats my javascript code:

```<code>$.jqplot.preDrawHooks.push(function () {
this.legend.show = true;});
</code>```

and my xhtml:

```<code><p:chart id="chart17" responsive="true" type="bar"  model="#{chart17Bean.barModel}"  />
<p:chart id="chart18" responsive="true" type="bar"  model="#{chart18Bean.barModel}" />
</code>```

Edited: I'm using Primefaces 6.1

答:
Add this JS function on page

```<code>function removeLegend()
{
     this.cfg.legend = {
          show: false
     };
}
</code>```

and then in your managed bean add

```<code>barModel.setExtender("removeLegend");
</code>```

where barModel is model of chart you want to have legend hidden.

Body:
I have 2 charts in the same page. I'd like to show legends just in one chart, not both, but I have just a global solution. Thats my javascript code:

$.jqplot.preDrawHooks.push(function () {
this.legend.show = true;});

and my xhtml:

Edited: I'm using Primefaces 6.1

Body:
Add this JS function on page

function removeLegend()
{
     this.cfg.legend = {
          show: false
     };
}

and then in your managed bean add

barModel.setExtender("removeLegend");

where barModel is model of chart you want to have legend hidden.


问:
How aut create raw number in column B if relevant cell in column C is empty via VBA?
How Can I create code in VBA, which can do below command:
- Once any info (value or data) entered to the relative cell in column C, automatically create number for that raw in column B.
For example: once user entered request text in column C4,AUT create request number in column B4. I have created below code, however it is not working. Could you please help what is wrong?

```<code>Sub requestnumber()

Dim lRow As Integer
Dim i As Integer
Dim m As Integer

lRow = Cells(Rows.Count, 2).End(xlUp).Row

For i = 1 To i = lRow

m = Range("B1").Offset(i, 0).Activate

If Range("B1").Offset(i, 0) <> "" Then

Range("A1").Offset(i, 0) = lRow

Exit For

End If

Next i

End Sub
</code>```

Thanks!
Shahla H.

答:
I think what you want to do is assign a unique request id number in col B when people make an entry in Col C. In which case you need to only run your code after data entry, so you need to attach your code to the worksheet update event in the code module for the sheet:</p>

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
 If Target.Column = 3 Then
      Target.Offset(0, -1).Value = Application.WorksheetFunction.Max(Range("b:b")) + 1

 End If
End Sub
</code>```

Body:
How Can I create code in VBA, which can do below command:
- Once any info (value or data) entered to the relative cell in column C, automatically create number for that raw in column B.
For example: once user entered request text in column C4,AUT create request number in column B4. I have created below code, however it is not working. Could you please help what is wrong?

Sub requestnumber()

Dim lRow As Integer
Dim i As Integer
Dim m As Integer

lRow = Cells(Rows.Count, 2).End(xlUp).Row

For i = 1 To i = lRow

m = Range("B1").Offset(i, 0).Activate

If Range("B1").Offset(i, 0) <> "" Then

Range("A1").Offset(i, 0) = lRow

Exit For

End If

Next i

End Sub

Thanks!
Shahla H.

Body:
I think what you want to do is assign a unique request id number in col B when people make an entry in Col C. In which case you need to only run your code after data entry, so you need to attach your code to the worksheet update event in the code module for the sheet:

Private Sub Worksheet_Change(ByVal Target As Range)
 If Target.Column = 3 Then
      Target.Offset(0, -1).Value = Application.WorksheetFunction.Max(Range("b:b")) + 1

 End If
End Sub


问:
Get the Count of a List of unknown type
I am calling a function that returns an object and in certain circumstances this object will be a List.

A GetType on this object might gives me:

```<code>{System.Collections.Generic.List`1[Class1]}
</code>```

or

```<code>{System.Collections.Generic.List`1[Class2]}
</code>```

etc

I don't care what this type is, all I want is a Count.

I've tried:

```<code>Object[] methodArgs=null;
var method = typeof(Enumerable).GetMethod("Count");
int count = (int)method.Invoke(list, methodArgs);
</code>```

but this gives me an AmbiguousMatchException which I can't seem to get around without knowing the type.

I've tried casting to IList but I get:

Unable to cast object of type 'System.Collections.Generic.List'1[ClassN]' to type 'System.Collections.Generic.IList'1[System.Object]'.

UPDATE

Marcs answer below is actually correct. The reason it wasn't working for me is that I have:

```<code>using System.Collections.Generic;
</code>```

at the top of my file. This means I was always using the Generic versions of IList and ICollection. If I specify System.Collections.IList then this works ok.

答:
You can do this</p>

```<code>var countMethod = typeof(Enumerable).GetMethods().Single(method => method.Name == "Count" && method.IsStatic && method.GetParameters().Length == 1);
</code>```

Title: Get the Count of a List of unknown type

Body:
I am calling a function that returns an object and in certain circumstances this object will be a List.

A GetType on this object might gives me:

{System.Collections.Generic.List`1[Class1]}

or

{System.Collections.Generic.List`1[Class2]}

etc

I don't care what this type is, all I want is a Count.

I've tried:

Object[] methodArgs=null;
var method = typeof(Enumerable).GetMethod("Count");
int count = (int)method.Invoke(list, methodArgs);

but this gives me an AmbiguousMatchException which I can't seem to get around without knowing the type.

I've tried casting to IList but I get:

Unable to cast object of type 'System.Collections.Generic.List'1[ClassN]' to type 'System.Collections.Generic.IList'1[System.Object]'.

UPDATE

Marcs answer below is actually correct. The reason it wasn't working for me is that I have:

using System.Collections.Generic;

at the top of my file. This means I was always using the Generic versions of IList and ICollection. If I specify System.Collections.IList then this works ok.

Body:
You can do this

var countMethod = typeof(Enumerable).GetMethods().Single(method => method.Name == "Count" && method.IsStatic && method.GetParameters().Length == 1);


问:
Firebase and recyclerView
Hi I'm new in firebase and android studio and I have a problem

I want to store the data of this database in an array and next use the array to make a recycler view

Then in the main activity I wrote this:

And if I run the app only this is shown:

But if I do the same but instead of firebase i use a String[] with the data i want to show it works but i don't know why with firebase i can't.

if I change the references by this:

```<code>reference = database.getReference(FirebaseReferences.POKEMONS_REFERENCES);
      reference.child(FirebaseReferences.APP_REFERENCES).addValueEventListener(new ValueEventListener() {
</code>```

when I run the app, it automatically closes and i don't know what to do.

Could you please tell me what i'm doing wrong?

Thank you in advance.

Here is the logCat
https://github.com/adcasna/SearchViewPrueba2/wiki

答:
Fisrts of all, please note that the Firebase documentation recommends against using arrays. Using an array is an anti-pattern when it comes to Firebase. One of the many reasons Firebase recommends against using arrays is that it makes the security rules impossible to write. If you still want to use this kind of structure, for getting those names and store them in an  ArrayList, please use the following code:

```<code>DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference appRef = rootRef.child("pokemons").child("app");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<String> list = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String c_name = ds.child("c_name").getValue(String.class);
            list.add(c_name);
            Log.d("TAG", c_name);
        }
        Log.d("TAG", list );
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
appRef.addListenerForSingleValueEvent(eventListener);
</code>```

Title: Firebase and recyclerView

Body:
Hi I'm new in firebase and android studio and I have a problem

I want to store the data of this database in an array and next use the array to make a recycler view

Then in the main activity I wrote this:

And if I run the app only this is shown:

But if I do the same but instead of firebase i use a String[] with the data i want to show it works but i don't know why with firebase i can't.

if I change the references by this:

reference = database.getReference(FirebaseReferences.POKEMONS_REFERENCES);
      reference.child(FirebaseReferences.APP_REFERENCES).addValueEventListener(new ValueEventListener() {

when I run the app, it automatically closes and i don't know what to do.

Could you please tell me what i'm doing wrong?

Thank you in advance.

Here is the logCat
https://github.com/adcasna/SearchViewPrueba2/wiki

Body:
Fisrts of all, please note that the Firebase documentation recommends against using arrays. Using an array is an anti-pattern when it comes to Firebase. One of the many reasons Firebase recommends against using arrays is that it makes the security rules impossible to write. If you still want to use this kind of structure, for getting those names and store them in an  ArrayList, please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference appRef = rootRef.child("pokemons").child("app");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<String> list = new ArrayList<>();
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String c_name = ds.child("c_name").getValue(String.class);
            list.add(c_name);
            Log.d("TAG", c_name);
        }
        Log.d("TAG", list );
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
appRef.addListenerForSingleValueEvent(eventListener);


问:
Best language for generating Mandelbrot Set images?
I tried coding something in c#, which generates a mandelbrot set image (with smooth coloring), and it worked but produced very slow, probably because c# isn't the best language for it. What woould be the best language to generate lots of images in the shortest time?</p>

答:
The programming language does not matter. The fastest is to do the calculation on the GPU using eg CUDA or OpenCL.

Just do a search for Mandelbrot Set Realtime GPU. Some examples that I found:

https://www.thanassis.space/mandelSSE.html

http://www.fractalforums.com/programming/source-code-mandelbrot-c-opencl-and-opengl/

(Disclaimer, none of them is mine, but I use Renderscript for a similar purpose in Android)

Side note 1: You can also implement a fractal renderer directly in C# and it will be equally fast as any other in C or C#, but you should not create new objects on the heap for each calculation step (or use a library for complex numbers that does exactly this). Either use double-variables or reuse existing objects.

Side note 2: Using arbitrary precision will always be slow.


问:
Get listitems from Current Site
I am trying to create a Page Layout, that should have a lookup field. Lookup field should always get populated with a list's items.

This list will exist in all subsites, so whereever I create this page, list should get populated with listitems from current site.

I tried using site column lookup field, but it always point to list under top site and not the current site.

Any suggestion on how to make it work or better alternative? Thanks!

Let me know if I can provide more info.

答:
Solution 1 - Use http://sp2010filteredlookup.codeplex.com/

Use filtered lookup solution. So let's say you have your custom Page Layout and custom Page Content Type.
Every time you create new subsite, you should remember go to Pages list settings and edit Page Content Type by adding cross site lookup (with the same field "internal name").
So you still have one Page Layout (and one Content Type). But for each Pages library instance, Content Type contains diff fields (but with the same Internal Name). It will allow you run CAML queries and other things needed without any problems.

Solution 2 - develop custom sharepoint field type.

In edit mode, control will render "dropdown list" and populate data from list instance that is on current subsite. In the field settings you can have relative list url.

Solution 3 - hidden text field / js snippet solution

Page Content Type can contain hidden text field (it can contains selected field value in json format for example). Develop js snippet that will handle all the logic (rendering in edit/view mode, saving etc) and put it on Page Layout (aspx).

I would suggest to use solution #1 or #2.

Title: Get listitems from Current Site


问:
Can a C# AnyCPU project include a platform specific dll
Our product is based on a bunch of C++ projects but we are now using C# projects for the front end.  We are also now doing a 64 bit version.

Our plan is to build all of the C# dlls as AnyCPU.  The C# projects will have references to the C++ dlls in a common bin folder.  When building x64 the bin folder will contain x64 versions of our c++ dlls and when building Win32 the bin folder will contain 32 bit versions of our C++ dlls.  So the C# projects will be building AnyCPU but including either an x64 or Win32 c++ dll.

My question is, will this work?  At runtime everything should be either all 32 or all 64 depending on which exe we are running, but can compile time handle a project targeting AnyCPU that includes a platform specific dll?  Or will we have to make platform specific versions of all our C# dlls?
Thanks

答:
This is primarily a deployment problem, getting the right DLLs selected for the right operating system.  Pretty straight-forward if you create two setup projects, one for x86 and another for x64.

Making it work transparently is possible too.  You'd create, say, an x86 and an x64 sub-directory in the directory that contains your EXE and put respectively the 32-bit and the 64-bit builds of the DLLs in those sub-directories.  At startup, check IntPtr.Size to know the bit-ness of your process.  Then pinvoke SetDllDirectory accordingly so that Windows will find the correct DLL.  Like this:

```<code>using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;
...
        public static void SetupDllDirectory() {
            string path = Assembly.GetEntryAssembly().Location;
            path = Path.Combine(path, IntPtr.Size == 8 ? "x64" : "x86");
            bool ok = SetDllDirectory(path);
            if (!ok) throw new System.ComponentModel.Win32Exception();
        }

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool SetDllDirectory(string path);
</code>```

Use a post build event to copy the DLLs.  Using Environment.SetEnvironmentVariable() to append the directory to the PATH environment variable is yet another approach.

Body:
This is primarily a deployment problem, getting the right DLLs selected for the right operating system.  Pretty straight-forward if you create two setup projects, one for x86 and another for x64.

Making it work transparently is possible too.  You'd create, say, an x86 and an x64 sub-directory in the directory that contains your EXE and put respectively the 32-bit and the 64-bit builds of the DLLs in those sub-directories.  At startup, check IntPtr.Size to know the bit-ness of your process.  Then pinvoke SetDllDirectory accordingly so that Windows will find the correct DLL.  Like this:

using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;
...
        public static void SetupDllDirectory() {
            string path = Assembly.GetEntryAssembly().Location;
            path = Path.Combine(path, IntPtr.Size == 8 ? "x64" : "x86");
            bool ok = SetDllDirectory(path);
            if (!ok) throw new System.ComponentModel.Win32Exception();
        }

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool SetDllDirectory(string path);

Use a post build event to copy the DLLs.  Using Environment.SetEnvironmentVariable() to append the directory to the PATH environment variable is yet another approach.


问:
Attempting to create a shapefile with lines form a csv file of endpoints in python
I copied a python script off of the gis.stackexchange website.  The purpose is to covert a list of start and end points into a gis shapefile with lines that start and end at these same endpoints.  I have not used python before, so please be patient with me.

Here is the script:

```<code>import arcpy

outPath = r"S:\GIS data\Matthew Damage areas" #output path for the feature class
featureClass = "roadSegments.shp" #the name of your shapefile
spatialRef = arcpy.SpatialReference("WGS 1984") #the spatial reference you want; set it to whatever you want

arcpy.CreateFeatureclass_management(outPath, featureClass, "POLYLINE", " ", "DISABLED", "DISABLED", spatialRef) #sets up the shapefile we're using

arcpy.AddField_management(outPath + "\\" + featureClass, "segmentID", "SHORT", 15) #I assume that each segment has some sort of ID number that you might want to import into

roadArray = arcpy.Array() #this will hold the coordinates for each line segment until we write it to the shapefile.

roadFile = open(r"S:\GIS data\Matthew Damage areas\roadlines.csv") #the path to your road lines file
headerLine = roadFile.readline()
indexList = headerLine.split(",")

#now we need the index locations for the columns that contain the latitude and longitude points for the starting and ending points for each line segment.  I'm also assuming that each segment has some sort of ID value in your segment.  Change the value inside the parenthesis to reflect whatever you named your column for those values.

idValueIndex = indexList.index('segmentID')
fromLatValueIndex = indexList.index('fromLat')
fromLongValueIndex = indexList.index('fromLong')
toLatValueIndex = indexList.index('toLat')
toLongValueIndex = indexList.index('toLong')

roadCursor = arcpy.InsertCursor(outPath + "\\" + featureClass)

for fileLine in roadFile.readlines():
    readline = fileLine.split(",")
    idNumber = int(readline[idValueIndex])
    fromLat = float(readline[fromLatValueIndex])
    fromLong = float(readline[fromLongValueIndex])
    toLat = float(readline[toLatValueIndex])
    toLong = float(readline[toLongValueIndex])

    #now let's add the points and draw the lines
    fromVertex = arcpy.Point(fromLong, fromLat)
    roadArray.add(fromVertex)
    toVertex = arcpy.Point(toLong, toLat)
    roadArray.add(toVertex)

    roadCursor = arcpy.InsertCursor(outPath + "\\" + featureClass)
    feature = roadCursor.newRow()
    polyline = arcpy.Polyline(roadArray, spatialRef)
    feature.shape = polyline
    feature.setValue("segmentID", idNumber) #adds the segmentID in the attribute table

    roadCursor.insertRow(feature)
    roadArray.removeAll()

del roadCursor

print "Finished!"
print arcpy.GetMessages()
</code>```

A shapefile is created, but the file does not contain data.

Error:

Runtime error

Traceback (most recent call last):

File "", line 23, in

ValueError: 'toLong' is not in list

答:
Presumming first line of roadlines.csv is segmentID,fromLat,fromLong,toLat,toLong you need remove final \n from the header :

```<code>headerLine = roadFile.readline().strip()
</code>```

You can also simplify the code using Python CSV module

Body:
I copied a python script off of the gis.stackexchange website.  The purpose is to covert a list of start and end points into a gis shapefile with lines that start and end at these same endpoints.  I have not used python before, so please be patient with me.

Here is the script:

import arcpy

outPath = r"S:\GIS data\Matthew Damage areas" #output path for the feature class
featureClass = "roadSegments.shp" #the name of your shapefile
spatialRef = arcpy.SpatialReference("WGS 1984") #the spatial reference you want; set it to whatever you want

arcpy.CreateFeatureclass_management(outPath, featureClass, "POLYLINE", " ", "DISABLED", "DISABLED", spatialRef) #sets up the shapefile we're using

arcpy.AddField_management(outPath + "\\" + featureClass, "segmentID", "SHORT", 15) #I assume that each segment has some sort of ID number that you might want to import into

roadArray = arcpy.Array() #this will hold the coordinates for each line segment until we write it to the shapefile.

roadFile = open(r"S:\GIS data\Matthew Damage areas\roadlines.csv") #the path to your road lines file
headerLine = roadFile.readline()
indexList = headerLine.split(",")

#now we need the index locations for the columns that contain the latitude and longitude points for the starting and ending points for each line segment.  I'm also assuming that each segment has some sort of ID value in your segment.  Change the value inside the parenthesis to reflect whatever you named your column for those values.

idValueIndex = indexList.index('segmentID')
fromLatValueIndex = indexList.index('fromLat')
fromLongValueIndex = indexList.index('fromLong')
toLatValueIndex = indexList.index('toLat')
toLongValueIndex = indexList.index('toLong')

roadCursor = arcpy.InsertCursor(outPath + "\\" + featureClass)

for fileLine in roadFile.readlines():
    readline = fileLine.split(",")
    idNumber = int(readline[idValueIndex])
    fromLat = float(readline[fromLatValueIndex])
    fromLong = float(readline[fromLongValueIndex])
    toLat = float(readline[toLatValueIndex])
    toLong = float(readline[toLongValueIndex])

    #now let's add the points and draw the lines
    fromVertex = arcpy.Point(fromLong, fromLat)
    roadArray.add(fromVertex)
    toVertex = arcpy.Point(toLong, toLat)
    roadArray.add(toVertex)

    roadCursor = arcpy.InsertCursor(outPath + "\\" + featureClass)
    feature = roadCursor.newRow()
    polyline = arcpy.Polyline(roadArray, spatialRef)
    feature.shape = polyline
    feature.setValue("segmentID", idNumber) #adds the segmentID in the attribute table

    roadCursor.insertRow(feature)
    roadArray.removeAll()

del roadCursor

print "Finished!"
print arcpy.GetMessages()

A shapefile is created, but the file does not contain data.

Error:

Runtime error

Traceback (most recent call last):

File "", line 23, in

ValueError: 'toLong' is not in list

Body:
Presumming first line of roadlines.csv is segmentID,fromLat,fromLong,toLat,toLong you need remove final \n from the header :

headerLine = roadFile.readline().strip()

You can also simplify the code using Python CSV module


问:
Linux VPS harddisk showing 390 GB data out of 500GB
My Linux VPS harddisk showing 390GB data used out of 500GB, but when i see in my whm panel its showing only 22GB harddisk used, how can i check and solve the problem. Please find the attached image also.

whm panel
server

答:
You're looking at the VHD (virtual hard disk) container in your windows machine, not the disk usage value from inside the virtual machine.

The value in windows there is like looking on the front of a physical hard disk and reading "capacity: 500GB".
In the control panel, that's value is being called from inside the virtual machine, if you SSH into your virtual machine and run "df -h" it'll give you the correct usage as according to the virtual server itself.

The value in the windows machine is the size of the virtual machines entire hard disk drive.


问:
Sails.js session not saved upon first request
I'm using Sails.js and trying to do a simple login with saving the user information to the session. Here's my code for the login action:

```<code>AuthService.login(req.body.email, req.body.password).then(user => {

    // save user information in the session
    req.session.user = user;
    req.session.authenticated = true;

    return res.json({
      user:user,
      token:token
    });
}).catch(err => {
  sails.log.error(err);
  res.json(403, {
    callstack: err.callstack,
    error: 'Authentication error',
    reason : err.reason
  });
});
</code>```

This is my policy for the other pages (after login):

```<code>  module.exports = function(req, res, next) {

  // User is allowed, proceed to the next policy,
  if (req.session.authenticated && req.session.user) {
      return next();
  }

  // User is not allowed
  return res.forbidden('You are not permitted to perform this action. (Authenticated)');
  };
</code>```

The problem is that the session data is not saved for the first request meaning I'm getting 403 forbidden only after the first successful login. As a result I must then logout and then login again for the session data to appear.

The issue is not limited to the login (with authentication policy) but also applies for any action that requires the session data with or without policy. And occurs for each new session - not only the first time the server goes up.

I thought the problem was due to using memory session so I've also tried to configure Sail.js to work with Redis as the session store by modifying the config/session.js to the following:

```<code>  adapter: 'redis',

  // host: 'localhost',
  // port: 6379,
  // ttl: 60*60*20,
  // db: 0,
  // prefix: 'sess:',
</code>```

I uncommented the adapter line and tried with and without the optional redis connection parameters but then the req.session was declared undefined everywhere

答:
I'm using the connect-mongo adapter and found a similar problem. The reason is because when you use req.session.user = user the background code is saving your session to DB (in my case, Mongo, in yours Redis), and before it finishes, your code executes the res.json part.

To deal with the DB saving's asynchronous code, try to do something like this (haven't tested your code, but doing that to my case, solved the problem):

```<code>  AuthService.login(req.body.email, req.body.password).then(user => {

    // save user information in the session

    // this is on memory
    req.session.user = user;
    req.session.authenticated = true;

    // now the session is saved in DB
    req.session.save(function() {
      return res.json({
        user:user,
        token:token
      });
    }
  }).catch(err => {
  sails.log.error(err);
  res.json(403, {
    callstack: err.callstack,
    error: 'Authentication error',
    reason : err.reason
  });
});
</code>```

Body:
I'm using Sails.js and trying to do a simple login with saving the user information to the session. Here's my code for the login action:

AuthService.login(req.body.email, req.body.password).then(user => {

    // save user information in the session
    req.session.user = user;
    req.session.authenticated = true;

    return res.json({
      user:user,
      token:token
    });
}).catch(err => {
  sails.log.error(err);
  res.json(403, {
    callstack: err.callstack,
    error: 'Authentication error',
    reason : err.reason
  });
});

This is my policy for the other pages (after login):

  module.exports = function(req, res, next) {

  // User is allowed, proceed to the next policy,
  if (req.session.authenticated && req.session.user) {
      return next();
  }

  // User is not allowed
  return res.forbidden('You are not permitted to perform this action. (Authenticated)');
  };

The problem is that the session data is not saved for the first request meaning I'm getting 403 forbidden only after the first successful login. As a result I must then logout and then login again for the session data to appear.

The issue is not limited to the login (with authentication policy) but also applies for any action that requires the session data with or without policy. And occurs for each new session - not only the first time the server goes up.

I thought the problem was due to using memory session so I've also tried to configure Sail.js to work with Redis as the session store by modifying the config/session.js to the following:

  adapter: 'redis',

  // host: 'localhost',
  // port: 6379,
  // ttl: 60*60*20,
  // db: 0,
  // prefix: 'sess:',

I uncommented the adapter line and tried with and without the optional redis connection parameters but then the req.session was declared undefined everywhere

Body:
I'm using the connect-mongo adapter and found a similar problem. The reason is because when you use req.session.user = user the background code is saving your session to DB (in my case, Mongo, in yours Redis), and before it finishes, your code executes the res.json part.

To deal with the DB saving's asynchronous code, try to do something like this (haven't tested your code, but doing that to my case, solved the problem):

  AuthService.login(req.body.email, req.body.password).then(user => {

    // save user information in the session

    // this is on memory
    req.session.user = user;
    req.session.authenticated = true;

    // now the session is saved in DB
    req.session.save(function() {
      return res.json({
        user:user,
        token:token
      });
    }
  }).catch(err => {
  sails.log.error(err);
  res.json(403, {
    callstack: err.callstack,
    error: 'Authentication error',
    reason : err.reason
  });
});


问:
Weibull MLE in R
The loglikelihood function looks like this. I wrote to this a function in R, this return of negative one times the loglikelihood. I generated a vector with rWeibull with parameters shape=1.5, scale=0.5. But when i call the nlm function with my loglikelihood function, the estimated values for the parameters are: 2.124180 and 4.003675. What wrong with my R code?
The code:</p>

```<code>vec<-rWeibull(n=1000, params=list(shape=1.5, scale=0.5))
weibull_loglik<-function(parm){
n<-length(vec)
gamma<-parm[1]
lambda<-parm[2]
loglik<-n*log(gamma/lambda)+(gamma-1)*sum(vec-log((lambda^(gamma-1))))-sum((vec/lambda)^gamma)
return(-loglik)}
weibull<-nlm(weibull_loglik,parm<-c(1,1), hessian=TRUE)
weibull$estimate
</code>```

答:
I think it should be:

```<code>loglik<-n*log(gamma/lambda)+(gamma-1)*sum(vec)-log((lambda^(gamma-1)))-
sum((vec/lambda)^gamma)
</code>```

As you do not sum over the third part of the LogLik-function.

Title: Weibull MLE in R

Body:
The loglikelihood function looks like this. I wrote to this a function in R, this return of negative one times the loglikelihood. I generated a vector with rWeibull with parameters shape=1.5, scale=0.5. But when i call the nlm function with my loglikelihood function, the estimated values for the parameters are: 2.124180 and 4.003675. What wrong with my R code?
The code:

vec<-rWeibull(n=1000, params=list(shape=1.5, scale=0.5))
weibull_loglik<-function(parm){
n<-length(vec)
gamma<-parm[1]
lambda<-parm[2]
loglik<-n*log(gamma/lambda)+(gamma-1)*sum(vec-log((lambda^(gamma-1))))-sum((vec/lambda)^gamma)
return(-loglik)}
weibull<-nlm(weibull_loglik,parm<-c(1,1), hessian=TRUE)
weibull$estimate

Body:
I think it should be:

loglik<-n*log(gamma/lambda)+(gamma-1)*sum(vec)-log((lambda^(gamma-1)))-
sum((vec/lambda)^gamma)

As you do not sum over the third part of the LogLik-function.


问:
Kubernetes RBAC authentication for default user
I am using kops in AWS to create my Kubernetes cluster.

I have created a cluster with RBAC enabled via --authorization=RBAC as described here.

I am trying to use the default service account token to interact with the cluster and getting this error:

Error from server (Forbidden): User "system:serviceaccount:default:default" cannot list pods in the namespace "default". (get pods)

Am I missing a role or binding somewhere?

答:
try to give admin role and try.</p>

```<code>kubectl create clusterrolebinding add-on-cluster-admin --clusterrole=cluster-admin  --serviceaccount=default:default
</code>```

Body:
try to give admin role and try.

kubectl create clusterrolebinding add-on-cluster-admin --clusterrole=cluster-admin  --serviceaccount=default:default


问:
LINQ query to check same date in the list?
I have a list of list complex object itemofsamestartDate means it has itemofsamestartDate[0],itemofsamestartDate[1],itemofsamestartDate[2].... and so on. itemofsamestartDate[i] has startDate property. I want to write a LINQ query to return True if all the list has same start date.

Below query, I tried -

```<code>var itemofsamestartDate = from aIndex in Enumerable.Range(0, itemOfSinglePrority.Count())
       from b in itemOfSinglePrority.Skip(aIndex + 1)
       let a = itemOfSinglePrority.ElementAt(aIndex)
       where a != b && a.StartDate == b.StartDate
       select new
       {
            object1 = a,
            object2 = b
       };
</code>```

Now  I am checking if itemofsamestartDate count is greater than 0, then it has the same startdate, but above is working fine if I have list count of 2 only i.e. itemofsamestartDate[0] & itemofsamestartDate[1].

What should be a LINQ query to check if the list has same startdata(DateTime datatype).

答:
Class ItemOfStartDate has a property StartDate.
You have a sequence of objects of this class, and you want to know if all objects in this sequence have the same value for StartDate.

In other words, you want to know if there is only one value used for StartDate.

You didn't mention what you want if the sequence is empty. Let's assume that all StartDates in an empty list are equal

```<code>IEnumerable<ItemOfStartDate> myItems = ...
bool onlyOneStartDates = !myItems    // from every element in my sequence
   .Select(item => item.StartDate)  // take the value of StartDate
   .Distinct();                     // and remove duplicates
   .Skip(1)
   .Any();                          // true if we have more than 1 left
</code>```

If you want to check uniqueness more often, consider creating an extension method:

```<code>static class EnumerableExtensions
{
    public static bool IsUnique<TSource, TKey>(this TSource source,
        Func<TSource, TKey> propertySelector)
    {
         return !source.Select(propertySelector)
             .Distinct()
             .Skip(1)
             .Any();
    }
}
</code>```

Usage:

```<code>IEnumerable<ItemOfStartDate> myItems = ...
bool onlyOneStartDates = IsUnique(item => item.StartDate);
</code>```

If desired you can add an overload IEqualityComparer to use in Distinct

Body:
I have a list of list complex object itemofsamestartDate means it has itemofsamestartDate[0],itemofsamestartDate[1],itemofsamestartDate[2].... and so on. itemofsamestartDate[i] has startDate property. I want to write a LINQ query to return True if all the list has same start date.

Below query, I tried -

var itemofsamestartDate = from aIndex in Enumerable.Range(0, itemOfSinglePrority.Count())
       from b in itemOfSinglePrority.Skip(aIndex + 1)
       let a = itemOfSinglePrority.ElementAt(aIndex)
       where a != b && a.StartDate == b.StartDate
       select new
       {
            object1 = a,
            object2 = b
       };

Now  I am checking if itemofsamestartDate count is greater than 0, then it has the same startdate, but above is working fine if I have list count of 2 only i.e. itemofsamestartDate[0] & itemofsamestartDate[1].

What should be a LINQ query to check if the list has same startdata(DateTime datatype).

Body:
Class ItemOfStartDate has a property StartDate.
You have a sequence of objects of this class, and you want to know if all objects in this sequence have the same value for StartDate.

In other words, you want to know if there is only one value used for StartDate.

You didn't mention what you want if the sequence is empty. Let's assume that all StartDates in an empty list are equal

IEnumerable<ItemOfStartDate> myItems = ...
bool onlyOneStartDates = !myItems    // from every element in my sequence
   .Select(item => item.StartDate)  // take the value of StartDate
   .Distinct();                     // and remove duplicates
   .Skip(1)
   .Any();                          // true if we have more than 1 left

If you want to check uniqueness more often, consider creating an extension method:

static class EnumerableExtensions
{
    public static bool IsUnique<TSource, TKey>(this TSource source,
        Func<TSource, TKey> propertySelector)
    {
         return !source.Select(propertySelector)
             .Distinct()
             .Skip(1)
             .Any();
    }
}

Usage:

IEnumerable<ItemOfStartDate> myItems = ...
bool onlyOneStartDates = IsUnique(item => item.StartDate);

If desired you can add an overload IEqualityComparer to use in Distinct


问:
Html Navigation bar item only last item clickable and the rest cannot
My navigation bar cannot click any item except the last item. I have checked and follow the tutorial from youtube but unfortunately I checked code is same but not working at all please anyone got solution please share to me.

Here's My html

```<code><html>
</code>```

```<code><title>UIA | Homepage</title>
<link href="Homepage.css" rel="stylesheet" type="text/css">
</code>```

```<code><header>
<div class="row">
    <div class="logo">
    <img src = "Logo.png">
    </div>

    <ul class="main-nav">
        <li class = "active"><a href="Homepage.html"> Home </a></li>
        <li><a href="Promotion.html"> Promotion </a></li>
        <li><a href=""> Booking </a></li>
        <li><a href=""> SignIn </a></li>
        <li><a href=""> About </a></li>

    </ul>

</div>

<div class="title">
<h1>Ready for another adventure?</h1>
</div>

</header>
</code>```

And here's my CSS.

```<code>*{
margin: 0;
padding: 0;

}

header{
background-image:
linear-gradient(rgba(0,0,0,0.8),rgba(0,0,0,0.8)), url(Homepage.jpg);
height:100vh;
background-position:center;
background-size: cover;

}

.main-nav{
float: right;
list-style: None;
margin-top: 30px;
}

 .main-nav li{

display: inline-block;
}

 .main-nav li a{

color: white;
text-decoration: none;
padding: 5px 20px;
font-family: "Roboto", Sans-serif;
font-size: 15px;
}

 .main-nav li.active a{
border: 1px solid white;
}

.main-nav li a:hover {

border: 1px solid white;
}

.logo img{
width: 150px;
height: auto;
margin-top:10px;
float: left;
}

.row{
max-width: 1200px;
margin: auto;
}

.title{
position:absolute;
width: 1200px;
margin-left: 0;
margin-top: 0;
 }

h1{
color: white;
font-size: 60px;
text-align: center;
margin-top: 255px;

}
</code>```

So did I miss out something please advice me Thank you.

答:
.title is overlapping the menu.

You can give the menu a higher z-index to ensure it is on top.

Information about z-index

updated code below

* {
  margin: 0;
  padding: 0;
}

header {
  background-image: linear-gradient(rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8)), url(Homepage.jpg);
  height: 100vh;
  background-position: center;
  background-size: cover;
}

.main-nav {
  float: right;
  list-style: None;
  margin-top: 30px;
  /* added */
  position: relative;
  z-index: 100;
}

.main-nav li {
  display: inline-block;
}

.main-nav li a {
  color: white;
  text-decoration: none;
  padding: 5px 20px;
  font-family: "Roboto", Sans-serif;
  font-size: 15px;
}

.main-nav li.active a {
  border: 1px solid white;
}

.main-nav li a:hover {
  border: 1px solid white;
}

.logo img {
  width: 150px;
  height: auto;
  margin-top: 10px;
  float: left;
}

.row {
  max-width: 1200px;
  margin: auto;
}

.title {
  position: absolute;
  width: 1200px;
  margin-left: 0;
  margin-top: 0;
}

h1 {
  color: white;
  font-size: 60px;
  text-align: center;
  margin-top: 255px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <div class="row">
    <div class="logo">
      <img src="Logo.png">
    </div>

    <ul class="main-nav">
      <li class="active"> Home </li>
      <li> Promotion </li>
      <li> Booking </li>
      <li> SignIn </li>
      <li> About </li>

    </ul>

  </div>

  <div class="title">
    <h1>Ready for another adventure?</h1>
  </div>

</header></code>```

Body:
My navigation bar cannot click any item except the last item. I have checked and follow the tutorial from youtube but unfortunately I checked code is same but not working at all please anyone got solution please share to me.

Here's My html

<title>UIA | Homepage</title>
<link href="Homepage.css" rel="stylesheet" type="text/css">

 Home

 Promotion

 Booking

 SignIn

 About

Ready for another adventure?

And here's my CSS.

*{
margin: 0;
padding: 0;

}

header{
background-image:
linear-gradient(rgba(0,0,0,0.8),rgba(0,0,0,0.8)), url(Homepage.jpg);
height:100vh;
background-position:center;
background-size: cover;

}

.main-nav{
float: right;
list-style: None;
margin-top: 30px;
}

 .main-nav li{

display: inline-block;
}

 .main-nav li a{

color: white;
text-decoration: none;
padding: 5px 20px;
font-family: "Roboto", Sans-serif;
font-size: 15px;
}

 .main-nav li.active a{
border: 1px solid white;
}

.main-nav li a:hover {

border: 1px solid white;
}

.logo img{
width: 150px;
height: auto;
margin-top:10px;
float: left;
}

.row{
max-width: 1200px;
margin: auto;
}

.title{
position:absolute;
width: 1200px;
margin-left: 0;
margin-top: 0;
 }

h1{
color: white;
font-size: 60px;
text-align: center;
margin-top: 255px;

}

So did I miss out something please advice me Thank you.

Body:
.title is overlapping the menu.

You can give the menu a higher z-index to ensure it is on top.

Information about z-index

updated code below

* {
  margin: 0;
  padding: 0;
}

header {
  background-image: linear-gradient(rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.8)), url(Homepage.jpg);
  height: 100vh;
  background-position: center;
  background-size: cover;
}

.main-nav {
  float: right;
  list-style: None;
  margin-top: 30px;
  /* added */
  position: relative;
  z-index: 100;
}

.main-nav li {
  display: inline-block;
}

.main-nav li a {
  color: white;
  text-decoration: none;
  padding: 5px 20px;
  font-family: "Roboto", Sans-serif;
  font-size: 15px;
}

.main-nav li.active a {
  border: 1px solid white;
}

.main-nav li a:hover {
  border: 1px solid white;
}

.logo img {
  width: 150px;
  height: auto;
  margin-top: 10px;
  float: left;
}

.row {
  max-width: 1200px;
  margin: auto;
}

.title {
  position: absolute;
  width: 1200px;
  margin-left: 0;
  margin-top: 0;
}

h1 {
  color: white;
  font-size: 60px;
  text-align: center;
  margin-top: 255px;
}

<header>
  <div class="row">
    <div class="logo">
      <img src="Logo.png">
    </div>

    <ul class="main-nav">
      <li class="active"><a href="Homepage.html"> Home </a></li>
      <li><a href="Promotion.html"> Promotion </a></li>
      <li><a href=""> Booking </a></li>
      <li><a href=""> SignIn </a></li>
      <li><a href=""> About </a></li>

    </ul>

  </div>

  <div class="title">
    <h1>Ready for another adventure?</h1>
  </div>

</header>


问:
Update information as needed
On the page I have a list of HTML-elements, each element has its status:

```<code><ul>
    <li>
        <span class='status'>ok</span>
        <span class='content'>content1</span>
    </li>
    <li>
        <span class='status'>not ok</span>
        <span class='content'>content2</span>
    </li>
    <li>
        <span class='status'>ok</span>
        <span class='content'>content3</span>
    </li>
</ul>
</code>```

This list is very big.

I need to update the status (without reloading the page).

What are the ways to do this?

I wanted to use AJAX. And periodically poll the database and get out status, etc.
What could be more options?

Update1:

I think that the use of Ajax in this way is not very good: the status change very rarely, and a list of objects is large.

答: I think AJAX is the best choice for you. You can use Jquery (a javascript framework) for AJAX functionality.</p>

Title: Update information as needed

Body:
On the page I have a list of HTML-elements, each element has its status:

        ok
        content1

        not ok
        content2

        ok
        content3

This list is very big.

I need to update the status (without reloading the page).

What are the ways to do this?

I wanted to use AJAX. And periodically poll the database and get out status, etc.
What could be more options?

Update1:

I think that the use of Ajax in this way is not very good: the status change very rarely, and a list of objects is large.


问:
Keyword still be executed even the condition is false on robot framework
```<code>${result}   get location
Do some click so the link will not same
${elem}     get location

Verify
run keyword unless  '${result}' == '${elem}'    keywordA
run keyword if      '${result}' == '${elem}'    keywordB
</code>```

I have this example code on robot framework
I want to run the
keywordA if > condition false
and run keywordB if > condition true

But however, if the condition false, the keywordA will executed, but keywordB as well.
Anyone can help with solutions? Thanks

basically I want if else statement like

```<code>if(condition true) { run B }
 else { run A }
</code>```

答:
Run Keyword If accepts an ELSE clause

```<code>Run keyword if  '${result}' == '${elem}'
...  keywordB
...  ELSE
...  keywordA
</code>```

Here's a complete working example:

```<code>*** Keywords ***
keywordA
    log to console   \nthis is keyword A

keywordB
    log to console   \nthis is keyword B

*** Variables ***
${result}  foo
${elem}    foo

*** Test Cases ***
test case A
    Run keyword if  '${result}' == '${elem}'
    ...  keywordB
    ...  ELSE
    ...  keywordA
</code>```

Body:
${result}   get location
Do some click so the link will not same
${elem}     get location

Verify
run keyword unless  '${result}' == '${elem}'    keywordA
run keyword if      '${result}' == '${elem}'    keywordB

I have this example code on robot framework
I want to run the
keywordA if > condition false
and run keywordB if > condition true

But however, if the condition false, the keywordA will executed, but keywordB as well.
Anyone can help with solutions? Thanks

basically I want if else statement like

if(condition true) { run B }
 else { run A }

Body:
Run Keyword If accepts an ELSE clause

Run keyword if  '${result}' == '${elem}'
...  keywordB
...  ELSE
...  keywordA

Here's a complete working example:

*** Keywords ***
keywordA
    log to console   \nthis is keyword A

keywordB
    log to console   \nthis is keyword B

*** Variables ***
${result}  foo
${elem}    foo

*** Test Cases ***
test case A
    Run keyword if  '${result}' == '${elem}'
    ...  keywordB
    ...  ELSE
    ...  keywordA


问:
Chef: Generate a self-signed CA
I would like to do the following with chef:

Generate a self-signed root CA (.cer)

Generate a certificate request  (.csr)

Sign that certificate request by the root CA and obtain the file (.crt)

How I could do that using chef? I've seen that cookbook https://supermarket.chef.io/cookbooks/openssl but there doesn't appear how to sign a certificate.

Following is the code that I actually use:

```<code>openssl req -newkey rsa:2048 -days 3650 -x509 -nodes -out root.cer
openssl req -newkey rsa:1024 -nodes -out vault.csr -keyout vault.key
openssl ca -batch -config root-ca.conf -notext -in vault.csr -out vault.crt

sudo update-ca-trust enable
mv root.cer /etc/pki/ca-trust/source/anchors/
sudo update-ca-trust extract
</code>```

答: If you really want chef to manage CA/PKI look at ssl certificate cookbook it may be more suitable. Although, more complicated than openssl cookbook.</p>

Title: Chef: Generate a self-signed CA

Body:
I would like to do the following with chef:

Generate a self-signed root CA (.cer)

Generate a certificate request  (.csr)

Sign that certificate request by the root CA and obtain the file (.crt)

How I could do that using chef? I've seen that cookbook https://supermarket.chef.io/cookbooks/openssl but there doesn't appear how to sign a certificate.

Following is the code that I actually use:

openssl req -newkey rsa:2048 -days 3650 -x509 -nodes -out root.cer
openssl req -newkey rsa:1024 -nodes -out vault.csr -keyout vault.key
openssl ca -batch -config root-ca.conf -notext -in vault.csr -out vault.crt

sudo update-ca-trust enable
mv root.cer /etc/pki/ca-trust/source/anchors/
sudo update-ca-trust extract


问:
How to apply Xib width conditionally based on device width?
how to fix the width of Xib based on device width? .I have created custom navigation bar with xib view ? but i am facing problem with width of the xib ?
`func loadNavigation() {

```<code>    self.navigationController?.navigationBar.isHidden = false
    self.navigationController?.navigationBar.isTranslucent = false
    self.navigationItem.hidesBackButton = true
    self.navigationController?.navigationBar.addSubview(customNavigation.view)
    customNavigation.leftBtn?.isHidden = false
    customNavigation.rightBtn?.isHidden = false
    customNavigation.titleLbl?.isHidden = false
    customNavigation.titleLbl?.text = NSLocalizedString("Teacher Profile", comment: "")
    customNavigation.leftBtn?.addTarget(self, action: #selector(PTeacherProfileViewController.BackAction(_:)), for: UIControlEvents.touchUpInside)
    customNavigation.rightBtn?.addTarget(self, action: #selector(PTeacherProfileViewController.DownAction(_:)), for: UIControlEvents.touchUpInside)
}`
</code>```

this is the way i am using navigation bar

答:
```<code>view.frame.size.width =  UIScreen.main.bounds.width
</code>```

Body:
how to fix the width of Xib based on device width? .I have created custom navigation bar with xib view ? but i am facing problem with width of the xib ?
`func loadNavigation() {

    self.navigationController?.navigationBar.isHidden = false
    self.navigationController?.navigationBar.isTranslucent = false
    self.navigationItem.hidesBackButton = true
    self.navigationController?.navigationBar.addSubview(customNavigation.view)
    customNavigation.leftBtn?.isHidden = false
    customNavigation.rightBtn?.isHidden = false
    customNavigation.titleLbl?.isHidden = false
    customNavigation.titleLbl?.text = NSLocalizedString("Teacher Profile", comment: "")
    customNavigation.leftBtn?.addTarget(self, action: #selector(PTeacherProfileViewController.BackAction(_:)), for: UIControlEvents.touchUpInside)
    customNavigation.rightBtn?.addTarget(self, action: #selector(PTeacherProfileViewController.DownAction(_:)), for: UIControlEvents.touchUpInside)
}`

this is the way i am using navigation bar