问:
Why array.push does not work on collection holding table data in Angular4 and PrimeNG?
So having following markup:

```<code><p-dataTable
                                    selectionMode="single"
                                    [(selection)]="selectedUsers"
                                    dataKey="id"
                                    [value]="users"
                                    [rows]="25" [paginator]="users.length>25" [pageLinks]="3"
                                    [rowsPerPageOptions]="[10,25,50,100]"
                                   >
</code>```

I am doing the following action to add record to table

```<code>applySelectedUsers() {
    // this.users.push(this.selectedUserToAdd);
    let arr=[];
    arr.push(this.selectedUserToAdd);
    this.users=this.users.concat(arr);
    this.selectedUserToAdd=null;
    this.hideUsersDialog();
}
</code>```

My question is, why commented line does not work? Record is not visible in table despite console.log(this.users) showing that collection is growing after each push

答:
PrimeNG's datable looks for changes in reference so it expects immutable data.
If you don't need to take advantage over what immutability gives you just set [immutable] property of p-dataTable to false. But keep in mind that it will force the datatable to check the collection you bound to the [value] property on every ngDoCheck lifecycle resulting in performance drop.

You can nicely see the reason why it's not changing in the view in the source code

```<code> set value(val:any[]) { // this will be triggered only by reassigning to this.users
        if(this.immutable) {
            this._value = val ? [...val] : null;
            this.handleDataChange();
        }
        else {
            this._value = val;
        }

        this.valueChange.emit(this.value);
    }
</code>```

now if you never reassign and set [immutable] to false it will check the differences in the lifecycle

```<code>    ngDoCheck() {
    if(!this.immutable) {
        let changes = this.differ.diff(this.value);
        if(changes) {
            this.handleDataChange();
        }
    }
}
</code>```

I hope I helped. Have a nice day and don't React :)

Body:
So having following markup:

25" [pageLinks]="3"
                                    [rowsPerPageOptions]="[10,25,50,100]"
                                   >

I am doing the following action to add record to table

applySelectedUsers() {
    // this.users.push(this.selectedUserToAdd);
    let arr=[];
    arr.push(this.selectedUserToAdd);
    this.users=this.users.concat(arr);
    this.selectedUserToAdd=null;
    this.hideUsersDialog();
}

My question is, why commented line does not work? Record is not visible in table despite console.log(this.users) showing that collection is growing after each push

Body:
PrimeNG's datable looks for changes in reference so it expects immutable data.
If you don't need to take advantage over what immutability gives you just set [immutable] property of p-dataTable to false. But keep in mind that it will force the datatable to check the collection you bound to the [value] property on every ngDoCheck lifecycle resulting in performance drop.

You can nicely see the reason why it's not changing in the view in the source code

 set value(val:any[]) { // this will be triggered only by reassigning to this.users
        if(this.immutable) {
            this._value = val ? [...val] : null;
            this.handleDataChange();
        }
        else {
            this._value = val;
        }

        this.valueChange.emit(this.value);
    }

now if you never reassign and set [immutable] to false it will check the differences in the lifecycle

    ngDoCheck() {
    if(!this.immutable) {
        let changes = this.differ.diff(this.value);
        if(changes) {
            this.handleDataChange();
        }
    }
}

I hope I helped. Have a nice day and don't React :)


来源: stackexchange

问:
Log requests on inexistent resources on API Gateway
How can I see requests made to a non created endpoint, provided by AWS API Gateway?
I.E: On my API gateway I had only the /customers resource (visible on cloudwatch). But for some reason I want to know if users are making requests to any other endpoint.</p>

答: API Gateway now supports access logs. https://aws.amazon.com/about-aws/whats-new/2017/11/amazon-api-gateway-supports-access-logging/</p>

ContentLicense: CC BY-SA 3.0


问:
Pandas difference in days between today's date and another date_time column?
I am running an analysis on transaction data, and want to calculate how long it has been in days since the most recent transaction for each unique customer.

My initial data frame (df1) looks like:

```<code>memberId     transactionDate
1111         2017-12-01
2222         2017-12-03
1111         2017-12-05
3333         2017-12-06
</code>```

TransactionDate is in datetime format.

This is my code trying to create a new dataframe with memberId and number of days since most recent transaction:

```<code>import datetime as dt
import pandas as pd

NOW=dt.datetime(2017,12,06)
gb=df1.groupby('memberId')
df2=gb.agg({'transactionDate': lambda x: (NOW-x.max())})
</code>```

This return as dataframe like:

```<code>memberId     transactionDate
1111         1 days
2222         3 days
3333         0 days
</code>```

But I want the days to be returns as an integer rather then with days.
My second try to fix this was:

```<code>NOW=dt.datetime(2017,12,06)
gb=df1.groupby('memberId')
df2=gb.agg({'transactionDate': lambda x: (NOW-x.max()).days})
</code>```

This returns something that looks like an epoch time for transactionDate, and output looks like:

```<code>memberId     transactionDate
1111         1970-01-01 00:00:00.000000001
2222         1970-01-01 00:00:00.000000003
3333         1970-01-01 00:00:00.000000000
</code>```

I think it is returning an epoch timestamp with number of days as microseconds.

How can I get an output like:

```<code>memberId     transactionDate
1111         1
2222         3
3333         0
</code>```

答:
Try forcing the Transaction Date before doing the calculation. I know you said it was in DateTime Format, but my solution is working on pandas version 0.20.2:

```<code>import datetime as dt
import pandas as pd

df1['transactionDate'] = pd.to_datetime(df1['transactionDate']) # <--- changing here
#can also try df1['transactionDate'] = pd.to_datetime(df1['transactionDate'], format='%Y-%M-%d', errors='coerce')
# will try to force the data into this format

#df1['transactionDate'].dtype
#dtype('<M8[ns]')

NOW=dt.datetime(2017,12,6)

# use NOW = dt.datetime.now() if you want to do this programmatically

gb=df1.groupby('memberId')
df2=gb.agg({'transactionDate': lambda x: (NOW-x.max()).days})
</code>```

output:

```<code>          transactionDate
memberId
1111                    1 #I get 1 for my answer since the max date of 1111 is 2017-12-05
2222                    3
3333                    0
</code>```

Body:
I am running an analysis on transaction data, and want to calculate how long it has been in days since the most recent transaction for each unique customer.

My initial data frame (df1) looks like:

memberId     transactionDate
1111         2017-12-01
2222         2017-12-03
1111         2017-12-05
3333         2017-12-06

TransactionDate is in datetime format.

This is my code trying to create a new dataframe with memberId and number of days since most recent transaction:

import datetime as dt
import pandas as pd

NOW=dt.datetime(2017,12,06)
gb=df1.groupby('memberId')
df2=gb.agg({'transactionDate': lambda x: (NOW-x.max())})

This return as dataframe like:

memberId     transactionDate
1111         1 days
2222         3 days
3333         0 days

But I want the days to be returns as an integer rather then with days.
My second try to fix this was:

NOW=dt.datetime(2017,12,06)
gb=df1.groupby('memberId')
df2=gb.agg({'transactionDate': lambda x: (NOW-x.max()).days})

This returns something that looks like an epoch time for transactionDate, and output looks like:

memberId     transactionDate
1111         1970-01-01 00:00:00.000000001
2222         1970-01-01 00:00:00.000000003
3333         1970-01-01 00:00:00.000000000

I think it is returning an epoch timestamp with number of days as microseconds.

How can I get an output like:

memberId     transactionDate
1111         1
2222         3
3333         0

Body:
Try forcing the Transaction Date before doing the calculation. I know you said it was in DateTime Format, but my solution is working on pandas version 0.20.2:

import datetime as dt
import pandas as pd

df1['transactionDate'] = pd.to_datetime(df1['transactionDate']) # <--- changing here
#can also try df1['transactionDate'] = pd.to_datetime(df1['transactionDate'], format='%Y-%M-%d', errors='coerce')
# will try to force the data into this format

#df1['transactionDate'].dtype
#dtype('<M8[ns]')

NOW=dt.datetime(2017,12,6)

# use NOW = dt.datetime.now() if you want to do this programmatically

gb=df1.groupby('memberId')
df2=gb.agg({'transactionDate': lambda x: (NOW-x.max()).days})

output:

          transactionDate
memberId
1111                    1 #I get 1 for my answer since the max date of 1111 is 2017-12-05
2222                    3
3333                    0


问:
How to use HtmlService in Gmail add-on using App Script
I am creating a Gmail Add-on. The following reference page says -
https://developers.google.com/gmail/add-ons/reference/

"Gmail add-ons are built using Apps Script and the many services it provides. You can use any of the Apps Script services when building your add-on"

Basically, I want to have the small screen to pop up on clicking a button in my Gmail add-on.

As of now I have added a button in my section as follows and tied it to an action handler 'htmltest':-

```<code>var htmlTest = CardService.newAction().setFunctionName('htmlTest');
var button = CardService.newTextButton().setText("htmlTest").setOnClickAction(htmlTest);
section.addWidget(button);
</code>```

This is how htmlTest looks like:-

```<code>function htmlTest(e){
return HtmlService.createHtmlOutputFromFile('doubleCheck');
}
</code>```

And this is the doubleCheck.html file I want it to pop up:-

```<code><!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    Hello, World!
  </body>
</html>
</code>```

But when I click the button it gives a run-time error:-
Missing required fields in markup:

Any clues how to use HtmlService while creating Gmail

答:
In the overview section of the CardService, It quotes:

“Currently you can only use this service to construct Gmail add-ons.“

So HtmlService is not available in constructing Gmail addon’s currently.

https://developers.google.com/apps-script/reference/card-service/

ContentLicense: CC BY-SA 4.0

Body:
I am creating a Gmail Add-on. The following reference page says -
https://developers.google.com/gmail/add-ons/reference/

"Gmail add-ons are built using Apps Script and the many services it provides. You can use any of the Apps Script services when building your add-on"

Basically, I want to have the small screen to pop up on clicking a button in my Gmail add-on.

As of now I have added a button in my section as follows and tied it to an action handler 'htmltest':-

var htmlTest = CardService.newAction().setFunctionName('htmlTest');
var button = CardService.newTextButton().setText("htmlTest").setOnClickAction(htmlTest);
section.addWidget(button);

This is how htmlTest looks like:-

function htmlTest(e){
return HtmlService.createHtmlOutputFromFile('doubleCheck');
}

And this is the doubleCheck.html file I want it to pop up:-

<!DOCTYPE html>

    <base target="_top">

    Hello, World!

But when I click the button it gives a run-time error:-
Missing required fields in markup:

Any clues how to use HtmlService while creating Gmail


问:
Rails 5 - Unable to Cleanse Test DB
I've recently started testing my app using RSpec. Being the testing noob that i am, i did not install the full suite of tools that people normally use (namely FactoryGirl, also now known as FactoryBot. And DatabaseCleaner).

Anyway here's what happened. After getting my feet wet with RSpec, i started using FactoryBot so that my tests looks less convoluted. Note that :user is a Devise object.

```<code># spec/models/first_test_spec.rb

FactoryBot.create(:user)
#Other Code
</code>```

So i'm doing stuff with my first_test_spec.rb and i run it and everything is working perfectly fine. I then create my 2nd spec file

```<code># spec/models/second_test_spec.rb

FactoryBot.create(:user)
#Other Code
</code>```

Now here comes the problem. My tests are failing because FactoryBot.create(:user) is invalid, due to Devise requiring unique emails. Clearly this indicates that the data from my first_test_spec is persisting hence the error.

So i attempt to install DatabaseCleaner and hopefully clear my Test DB after each run. My rails_helper looks like this:

```<code>require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require 'support/factory_bot'

# Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = false

  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:each, js: true) do
    DatabaseCleaner.strategy = :truncation
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

  config.infer_spec_type_from_file_location!
  config.filter_rails_from_backtrace!
end
</code>```

I think i've got everything set up correctly, so i'm uncertain if the errors are still occurring due to my DatabaseCleaner being set up wrongly.

Anyway, running rspec still throws the same error, where second_test_spec cannot create the user object because the email already exists (a validation that comes with Devise itself).

I then proceed to run the following:

```<code>rake db:test:prepare
rspec spec/models/second_test_spec.rb
</code>```

And it still throws the same error. So right now, i have no idea if my database is being cleanse after running rspec. But i'm quite certain that i have been unable to purge my test database.

So i guess i really have 2 questions/problems:

1) How do you purge your test database? (Googling reveals that rake db:test:prepare is the way)

2) Is my DatabaseCleaner setup correctly? If so, shouldn't it be purging the database?

UPDATE:
As suggested to me in the comments, using sequence for creating unique fields with FactoryBot is recommended. Obviously that made the problem go away because there would no longer be validation errors from Devise.

I then went on to test a couple of things.

rails c test
I ran this to check my test database and it was indeed empty. This indicates that DatabaseCleaner is working perfectly fine. What i fail to understand then, is why the need to sequence my email creation in FactoryBot? Or i suppose, i fail to understand how does RSpec "compile & run".

puts @user.email
So i wanted to print out the emails to look at the sequencing to see if i'm able to decipher the problem. Here's what happens:

running rspec spec/models/first_test_spec.rb
Tutor email yields the number 2.

running rspec spec/models/second_test_spec.rb
Tutor email yields the number 3.

running rspec
Tutor email yields the numbers 2 & 5.

So i'm not sure if there are "problems" with my test suite. Clearly my original problem has been fixed, and this is a separate topic altogether. But i figured if anyone would like to explain this mystery to anyone else who chances upon this thread may wish to do so.

答:
Seeing your full spec files would help. If you are running the specs as you've written - creating a user outside of an example group or a before block - that will cause records to be written outside of the cleaning strategy scope and can cause data to remain across examples. Your DBcleaner config looks to be set up fine otherwise.

rake db:test:prepare is the correct way to clean out your test db but shouldn't need to be ran often unless you have migration changes. You can jump into a rails console within the test environment rails c test and look around to see if there are any records left behind.

As a side note you can flip config.use_transactional_fixtures from false to true and remove DBcleaner altogether from your app. Just make sure there is no residual data in your database before going this route.

Title: Rails 5 - Unable to Cleanse Test DB

Body:
I've recently started testing my app using RSpec. Being the testing noob that i am, i did not install the full suite of tools that people normally use (namely FactoryGirl, also now known as FactoryBot. And DatabaseCleaner).

Anyway here's what happened. After getting my feet wet with RSpec, i started using FactoryBot so that my tests looks less convoluted. Note that :user is a Devise object.

# spec/models/first_test_spec.rb

FactoryBot.create(:user)
#Other Code

So i'm doing stuff with my first_test_spec.rb and i run it and everything is working perfectly fine. I then create my 2nd spec file

# spec/models/second_test_spec.rb

FactoryBot.create(:user)
#Other Code

Now here comes the problem. My tests are failing because FactoryBot.create(:user) is invalid, due to Devise requiring unique emails. Clearly this indicates that the data from my first_test_spec is persisting hence the error.

So i attempt to install DatabaseCleaner and hopefully clear my Test DB after each run. My rails_helper looks like this:

require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'rspec/rails'
require 'support/factory_bot'

# Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
ActiveRecord::Migration.maintain_test_schema!

RSpec.configure do |config|
  config.fixture_path = "#{::Rails.root}/spec/fixtures"
  config.use_transactional_fixtures = false

  config.before(:suite) do
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.strategy = :transaction
  end

  config.before(:each, js: true) do
    DatabaseCleaner.strategy = :truncation
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end

  config.infer_spec_type_from_file_location!
  config.filter_rails_from_backtrace!
end

I think i've got everything set up correctly, so i'm uncertain if the errors are still occurring due to my DatabaseCleaner being set up wrongly.

Anyway, running rspec still throws the same error, where second_test_spec cannot create the user object because the email already exists (a validation that comes with Devise itself).

I then proceed to run the following:

rake db:test:prepare
rspec spec/models/second_test_spec.rb

And it still throws the same error. So right now, i have no idea if my database is being cleanse after running rspec. But i'm quite certain that i have been unable to purge my test database.

So i guess i really have 2 questions/problems:

1) How do you purge your test database? (Googling reveals that rake db:test:prepare is the way)

2) Is my DatabaseCleaner setup correctly? If so, shouldn't it be purging the database?

UPDATE:
As suggested to me in the comments, using sequence for creating unique fields with FactoryBot is recommended. Obviously that made the problem go away because there would no longer be validation errors from Devise.

I then went on to test a couple of things.

rails c test
I ran this to check my test database and it was indeed empty. This indicates that DatabaseCleaner is working perfectly fine. What i fail to understand then, is why the need to sequence my email creation in FactoryBot? Or i suppose, i fail to understand how does RSpec "compile & run".

puts @user.email
So i wanted to print out the emails to look at the sequencing to see if i'm able to decipher the problem. Here's what happens:

running rspec spec/models/first_test_spec.rb
Tutor email yields the number 2.

running rspec spec/models/second_test_spec.rb
Tutor email yields the number 3.

running rspec
Tutor email yields the numbers 2 & 5.

So i'm not sure if there are "problems" with my test suite. Clearly my original problem has been fixed, and this is a separate topic altogether. But i figured if anyone would like to explain this mystery to anyone else who chances upon this thread may wish to do so.


问:
error while filtering data as per columns in django template
I am using Django template to display a table and I wish to filter data based on columns
In order to do so, I have taken two var q and r in my javascript

```<code>function go(){
    // alert("hellonikhar");
    var q = document.getElementById("search").value;
    var r=document.getElementById("columnName").value;

    window.open("/?q="+q+"&r="+r,"_self");
}
</code>```

In my home.html I have made a text-field and a drop-down menu

```<code><input type="text" class="text_field" id="search" placeholder="Search
for..." required>
<select name="columns" id="columnName">
    <option value="{{column.name}}"> Customer Name</option>
    <option value="{{column.name}}"> Status</option>
    <option value="{{column.name}}"> Product</option>
    <option value="{{column.name}}"> OS Type</option>
    <option value="{{column.name}}"> Server Type</option>
    <option value="{{column.name}}"> L3</option>
    <option value="{{column.name}}"> Version</option>
    <option value="{{column.name}}"> PM</option>
    <option value="{{column.name}}"> CDM</option>
</select>

<input type="button" class="button" onclick="go()" value="go" id="submit">
<input type="button" class="button" onclick="exp()" value="export" id="exp">
</code>```

I have defined a function in my views.py to check the value of r from the drop-down and q when the go button is clicked but the data is not filtered based on those columns

```<code>def user_profile(request):
    q = request.GET.get('q','')
    custom = Customer.objects.all()
    r= request.GET.get('r','')

    if q and r=="Status":
        custom1=custom.filter(name__contains=q)
</code>```

currently, I'm just testing when the value in the drop-down is status

答:
Missed r parameter.

```<code>window.open("/?q="+q+"&r="+r,"_self");
</code>```

Body:
I am using Django template to display a table and I wish to filter data based on columns
In order to do so, I have taken two var q and r in my javascript

function go(){
    // alert("hellonikhar");
    var q = document.getElementById("search").value;
    var r=document.getElementById("columnName").value;

    window.open("/?q="+q+"&r="+r,"_self");
}

In my home.html I have made a text-field and a drop-down menu

<input type="text" class="text_field" id="search" placeholder="Search
for..." required>
<select name="columns" id="columnName">
    <option value="{{column.name}}"> Customer Name</option>
    <option value="{{column.name}}"> Status</option>
    <option value="{{column.name}}"> Product</option>
    <option value="{{column.name}}"> OS Type</option>
    <option value="{{column.name}}"> Server Type</option>
    <option value="{{column.name}}"> L3</option>
    <option value="{{column.name}}"> Version</option>
    <option value="{{column.name}}"> PM</option>
    <option value="{{column.name}}"> CDM</option>
</select>

<input type="button" class="button" onclick="go()" value="go" id="submit">
<input type="button" class="button" onclick="exp()" value="export" id="exp">

I have defined a function in my views.py to check the value of r from the drop-down and q when the go button is clicked but the data is not filtered based on those columns

def user_profile(request):
    q = request.GET.get('q','')
    custom = Customer.objects.all()
    r= request.GET.get('r','')

    if q and r=="Status":
        custom1=custom.filter(name__contains=q)

currently, I'm just testing when the value in the drop-down is status

Body:
Missed r parameter.

window.open("/?q="+q+"&r="+r,"_self");


问:
PHPExcel save error - Cell coordinate string can not be a range of cells

I am currently trying to save an excel file loaded with PHPExcel. The template file has multiple sheets that reference other sheets in formulas. The template is being loaded from my local Apache server. After loading the file I try to save it and it throws an exception "Cell coordinate string can not be a range of cells". Using the HTML writer it displays perfectly.

Here is my code:

```<code>require_once "assets/vendors/PHPExcel/PHPExcel.php";
require_once 'assets/vendors/PHPExcel/PHPExcel/IOFactory.php';
$tmpfname = 'template_files/templateFile.xlsx';

$objReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
$objPHPExcel = $objReader->load($tmpfname);

try {
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    header('Content-Disposition: attachment;filename="myfile.xlsx"');
    header('Cache-Control: max-age=0');
    $objWriter->save('php://output');

} catch (Exception $e) {
        echo 'Caught exception: ',  $e->getMessage(), "\n";
}
</code>```

I expected my template sheet to be downloaded as usual in PHPExcel but cannot solve this issue. Has anyone else run into something similar?

The document that is downloaded is completely blank with the exception printed "Caught exception: Cell coordinate string can not be a range of cells".

答:
What's in the PHP output?

You have bad data somewhere.  This exception is thrown under three cases:

An attempt to find an absoluteCoordinate is passed a string containing ":" or ","

OR

An attempt to find an absoluteReference is passed a string containing ":" or ","

OR

coordinateFromString is called with ":" or "," in the string variable.

I'd look for a stray comma or full-colon where it's not supposed to be in the PHP output or a cell within your template file ...

Body:
I am currently trying to save an excel file loaded with PHPExcel. The template file has multiple sheets that reference other sheets in formulas. The template is being loaded from my local Apache server. After loading the file I try to save it and it throws an exception "Cell coordinate string can not be a range of cells". Using the HTML writer it displays perfectly.

Here is my code:

require_once "assets/vendors/PHPExcel/PHPExcel.php";
require_once 'assets/vendors/PHPExcel/PHPExcel/IOFactory.php';
$tmpfname = 'template_files/templateFile.xlsx';

$objReader = PHPExcel_IOFactory::createReaderForFile($tmpfname);
$objPHPExcel = $objReader->load($tmpfname);

try {
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    header('Content-Disposition: attachment;filename="myfile.xlsx"');
    header('Cache-Control: max-age=0');
    $objWriter->save('php://output');

} catch (Exception $e) {
        echo 'Caught exception: ',  $e->getMessage(), "\n";
}

I expected my template sheet to be downloaded as usual in PHPExcel but cannot solve this issue. Has anyone else run into something similar?

The document that is downloaded is completely blank with the exception printed "Caught exception: Cell coordinate string can not be a range of cells".


问:
How To Insert and Update Data From Same Form using Codeigniter
Can Anyone Help me to write Controller,Model and View From Which There Would Be a Single form(View) That takes the Hidden Id and Controller Checks whether The Request From View have id or not and depending upon that it would insert and update the same.</p>

答:
Basically you just have to check if the hidden id exists in your database or not. If it doesn't then you insert, if it does you update. Generally this is how you do it:

```<code><?php

class some_controller extends CI_Controller {

    /**
     * Submits the form
     *
     * @return boolean
     */
    public function submit_form() {
        $id = $this->input->post('id');
        $data = array(
            'somedata' => $this->input->post('somedata'),
            'someotherdata' => $this->input->post('someotherdata')
        );
        $this->load->model('some_model');
        if (!is_null($id) && $this->some_model->id_exists($id)) {
            return $this->db->update('sometable', array('id' => $id), $data);
        } else {
            // assumes sometable autoincrements id
            // otherwise $data = array_merge(array('id' => $id), $data);
            return $this->db->insert('sometable', $data);
        }
    }

}

class some_model extends CI_Model {

    /**
     * Checks if id exists in sometable
     *
     * @return boolean TRUE if item with $id exists in sometable
     */
    public function id_exists($id) {
        $this->db->where('id', $id);
        return $this->db->count_all_results('sometable') > 0;
    }

}
</code>```

Please note: good practice would call for moving the insert and update (in fact all queries) into a model. This is just an example.

Body:
Basically you just have to check if the hidden id exists in your database or not. If it doesn't then you insert, if it does you update. Generally this is how you do it:

<?php

class some_controller extends CI_Controller {

    /**
     * Submits the form
     *
     * @return boolean
     */
    public function submit_form() {
        $id = $this->input->post('id');
        $data = array(
            'somedata' => $this->input->post('somedata'),
            'someotherdata' => $this->input->post('someotherdata')
        );
        $this->load->model('some_model');
        if (!is_null($id) && $this->some_model->id_exists($id)) {
            return $this->db->update('sometable', array('id' => $id), $data);
        } else {
            // assumes sometable autoincrements id
            // otherwise $data = array_merge(array('id' => $id), $data);
            return $this->db->insert('sometable', $data);
        }
    }

}

class some_model extends CI_Model {

    /**
     * Checks if id exists in sometable
     *
     * @return boolean TRUE if item with $id exists in sometable
     */
    public function id_exists($id) {
        $this->db->where('id', $id);
        return $this->db->count_all_results('sometable') > 0;
    }

}

Please note: good practice would call for moving the insert and update (in fact all queries) into a model. This is just an example.


问:
Filter with the Time in LINUX
I have text file that containing two columns and im trying to write a linux code to filter data. The data has "pass" & "fail" status. I need to Show all "pass" lines , when previous line is "fail" and both lines should be within the 30 second of time. pls help me to do this job. thank you. below shows my text file

```<code>12/3/2017 13:25:16 AM    fail
12/3/2017 13:25:35 AM    pass
12/3/2017 14:55:11 AM    pass
12/5/2017 23:46:31 AM    pass
12/7/2017 13:15:35 AM    pass
12/7/2017 19:25:51 AM    pass
12/1/2017 15:39:09 AM    fail
12/1/2017 15:39:20 AM    pass
12/9/2017 21:25:45 AM    pass
12/5/2017 16:25:51 AM    pass
</code>```

my required result

```<code>12/3/2017 13:25:35 AM    pass
12/1/2017 15:39:20 AM    pass
</code>```

答:
Extended GNU awk solution:

```<code>awk 'function get_time(d_str){
         split(d_str, d, /[/:[:space:]]/);
         return mktime(sprintf("%d %d %d %d %d %d",d[3],d[1],d[2],d[4],d[5],d[6]))
     }
     $4=="pass" && status=="fail" && (get_time(prev_date)-get_time($1" "$2))<=30;
     { prev_date=$1" "$2; status=$4 }' file
</code>```

The output:

```<code>12/3/2017 13:25:35 AM    pass
12/1/2017 15:39:20 AM    pass
</code>```

function get_time(d_str){ ... } - returns timestamp converted from d_str(datetime string)

Title: Filter with the Time in LINUX

Body:
I have text file that containing two columns and im trying to write a linux code to filter data. The data has "pass" & "fail" status. I need to Show all "pass" lines , when previous line is "fail" and both lines should be within the 30 second of time. pls help me to do this job. thank you. below shows my text file

12/3/2017 13:25:16 AM    fail
12/3/2017 13:25:35 AM    pass
12/3/2017 14:55:11 AM    pass
12/5/2017 23:46:31 AM    pass
12/7/2017 13:15:35 AM    pass
12/7/2017 19:25:51 AM    pass
12/1/2017 15:39:09 AM    fail
12/1/2017 15:39:20 AM    pass
12/9/2017 21:25:45 AM    pass
12/5/2017 16:25:51 AM    pass

my required result

12/3/2017 13:25:35 AM    pass
12/1/2017 15:39:20 AM    pass

Body:
Extended GNU awk solution:

awk 'function get_time(d_str){
         split(d_str, d, /[/:[:space:]]/);
         return mktime(sprintf("%d %d %d %d %d %d",d[3],d[1],d[2],d[4],d[5],d[6]))
     }
     $4=="pass" && status=="fail" && (get_time(prev_date)-get_time($1" "$2))<=30;
     { prev_date=$1" "$2; status=$4 }' file

The output:

12/3/2017 13:25:35 AM    pass
12/1/2017 15:39:20 AM    pass

function get_time(d_str){ ... } - returns timestamp converted from d_str(datetime string)


问:
Java decoupling issue
am new to Java. I am trying to decouple the Responder class from the WeatherSystem Class. But I get an error at Public NewResponder in the Responder class (invalid method declaration; return type required), I am really stuck at this point. I have tried changing all the class points at NewResponder and responder but can't rectify it. Could anyone point out why I am getting this issue, please?
(I also have InputReader class but that's not included below).

WeatherSystem Class

```<code>        import java.util.HashSet;

        public class WeatherSystem
        {
        private InputReader reader;
        private NewResponder responder;

        public WeatherSystem(NewResponder responder)
        {
        reader = new InputReader();
        this.responder = new Responder();
        }
         public void start()
         {
         boolean finished = false;

         printWelcome();

        while(!finished) {
        HashSet<String> input = reader.getInput();

        if(input.contains("exit")) {
            finished = true;
        }
        else {
            String response = this.responder.generateResponse(input);
            System.out.println(response);
        }
      }
     printGoodbye();
</code>```

.............................................

Class Responder

```<code>    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.Random;
    import WeatherSystem.NewResponder

    public class Responder implements NewResponder
    {

     private HashMap<String, String> responseMap;
     private ArrayList<String> defaultResponses;
     private Random randomGenerator;

    public NewResponder()
    {
    responseMap = new HashMap<>();
    defaultResponses = new ArrayList<>();
    fillResponseMap();
    fillDefaultResponses();
    randomGenerator = new Random();
    }

    public String generateResponse(HashSet<String> words)
    {
    for (String word : words) {
        String response = this.responseMap.get(word);
        if(response != null) {
            return response;
        }
    }
    return pickDefaultResponse();
</code>```

....................................................

答: You really need to check whether you need interface NewResponder inside WeatherSystem. Which you are implementing in Responder class with wrong constructor name.

Title: Java decoupling issue

Body:
am new to Java. I am trying to decouple the Responder class from the WeatherSystem Class. But I get an error at Public NewResponder in the Responder class (invalid method declaration; return type required), I am really stuck at this point. I have tried changing all the class points at NewResponder and responder but can't rectify it. Could anyone point out why I am getting this issue, please?
(I also have InputReader class but that's not included below).

WeatherSystem Class

        import java.util.HashSet;

        public class WeatherSystem
        {
        private InputReader reader;
        private NewResponder responder;

        public WeatherSystem(NewResponder responder)
        {
        reader = new InputReader();
        this.responder = new Responder();
        }
         public void start()
         {
         boolean finished = false;

         printWelcome();

        while(!finished) {
        HashSet<String> input = reader.getInput();

        if(input.contains("exit")) {
            finished = true;
        }
        else {
            String response = this.responder.generateResponse(input);
            System.out.println(response);
        }
      }
     printGoodbye();

.............................................

Class Responder

    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.Random;
    import WeatherSystem.NewResponder

    public class Responder implements NewResponder
    {

     private HashMap<String, String> responseMap;
     private ArrayList<String> defaultResponses;
     private Random randomGenerator;

    public NewResponder()
    {
    responseMap = new HashMap<>();
    defaultResponses = new ArrayList<>();
    fillResponseMap();
    fillDefaultResponses();
    randomGenerator = new Random();
    }

    public String generateResponse(HashSet<String> words)
    {
    for (String word : words) {
        String response = this.responseMap.get(word);
        if(response != null) {
            return response;
        }
    }
    return pickDefaultResponse();

....................................................


问:
Center logo in/over Bootstrap navbar
I have the code below which centers a logo in a Bootstrap 3 navbar. This works fine, but I actually would like for the logo to appear to float above the navbar in the center, so the navbar does not have the same height as the logo. I have looked over similar solutions on SO and none do what I would like to accomplish.

.main-nav-outer {
  padding: 0px;
  border-bottom: 1px solid #dddddd;
  box-shadow: 0 4px 5px -3px #ececec;
  position: relative;
  background: #fff;
}

.main-nav {
  text-align: center;
  margin: 10px 0 0px;
  padding: 0;
  list-style: none;
}

.main-nav li {
  display: inline;
  margin: 0 1px;
}

.main-nav li a {
  display: inline-block;
  color: #222222;
  text-transform: uppercase;
  font-family: 'Montserrat', sans-serif;
  text-decoration: none;
  line-height: 20px;
  margin: 17px 32px;
  transition: all 0.3s ease-in-out;
  -moz-transition: all 0.3s ease-in-out;
  -webkit-transition: all 0.3s ease-in-out;
}

.main-nav li a:hover {
  text-decoration: none;
  color: #7cc576;
}

.small-logo {
  padding: 0 32px;
}

.main-section {
  padding: 90px 0 110px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="header" id="header">
  <!--header-start-->
  <div class="container">
    large Hero
  </div>
</header>

<nav class="main-nav-outer" id="test">
  <!--main-nav-start-->
  <div class="container">
    <ul class="main-nav">
      <li>Home</li>
      <li>Services</li>
      <li>Portfolio</li>
      <li class="small-logo"><img src="~/Content/img/wop_small_logo.png" alt=""></li>
      <li>Clients</li>
      <li>Team</li>
      <li>Contact</li>
    </ul>
    <i class="fa-bars"></i>
  </div>
</nav>

<section class="main-section" id="service">
  <!--main-section-start-->
  <div class="container">
    Bunch o stuff
  </div>
</section><!--main-section-end--></code>```

答:
Do you mean that you would like the logo centered above the navbar? Then you can edit your code like this:

.main-nav-outer{
    padding:0px;
    border-bottom:1px solid #dddddd;
    box-shadow:0 4px 5px -3px #ececec;
    position:relative;
    background:#fff;
}
.main-nav{
    text-align:center;
    margin:10px 0 0px;
    padding:0;
    list-style:none;
}
.main-nav li{
    display:inline;
    margin:0 1px;
}
.main-nav li a{
    display:inline-block;
    color:#222222;
    text-transform:uppercase;
    font-family: 'Montserrat', sans-serif;
    text-decoration: none;
    line-height:20px;
    margin:17px 32px;
    transition:all 0.3s ease-in-out;
    -moz-transition:all 0.3s ease-in-out;
    -webkit-transition:all 0.3s ease-in-out;
}

.main-nav li a:hover{
    text-decoration:none;
    color: #7cc576;
}

.small-logo{
    padding:0 32px;
}

.main-section{
    padding:90px 0 110px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header class="header" id="header">
        <!--header-start-->
        <div class="container">
            large Hero
        </div>
    </header>
<div class="small-logo" style="text-align:center"><img src="~/Content/img/wop_small_logo.png" alt="logo"></div>
    <nav class="main-nav-outer" id="test">
        <!--main-nav-start-->
        <div class="container">
            <ul class="main-nav">
                <li>Home</li>
                <li>Services</li>
                <li>Portfolio</li>
                <li>Clients</li>
                <li>Team</li>
                <li>Contact</li>
            </ul>
            <i class="fa-bars"></i>
        </div>
    </nav>

    <section class="main-section" id="service">
    <!--main-section-start-->
    <div class="container">
       Bunch o stuff
    </div>
</section><!--main-section-end--></code>```

Title: Center logo in/over Bootstrap navbar

Body:
I have the code below which centers a logo in a Bootstrap 3 navbar. This works fine, but I actually would like for the logo to appear to float above the navbar in the center, so the navbar does not have the same height as the logo. I have looked over similar solutions on SO and none do what I would like to accomplish.

.main-nav-outer {
  padding: 0px;
  border-bottom: 1px solid #dddddd;
  box-shadow: 0 4px 5px -3px #ececec;
  position: relative;
  background: #fff;
}

.main-nav {
  text-align: center;
  margin: 10px 0 0px;
  padding: 0;
  list-style: none;
}

.main-nav li {
  display: inline;
  margin: 0 1px;
}

.main-nav li a {
  display: inline-block;
  color: #222222;
  text-transform: uppercase;
  font-family: 'Montserrat', sans-serif;
  text-decoration: none;
  line-height: 20px;
  margin: 17px 32px;
  transition: all 0.3s ease-in-out;
  -moz-transition: all 0.3s ease-in-out;
  -webkit-transition: all 0.3s ease-in-out;
}

.main-nav li a:hover {
  text-decoration: none;
  color: #7cc576;
}

.small-logo {
  padding: 0 32px;
}

.main-section {
  padding: 90px 0 110px;
}

    large Hero

Home

Services

Portfolio

Clients

Team

Contact

    Bunch o stuff

Body:
Do you mean that you would like the logo centered above the navbar? Then you can edit your code like this:

.main-nav-outer{
    padding:0px;
    border-bottom:1px solid #dddddd;
    box-shadow:0 4px 5px -3px #ececec;
    position:relative;
    background:#fff;
}
.main-nav{
    text-align:center;
    margin:10px 0 0px;
    padding:0;
    list-style:none;
}
.main-nav li{
    display:inline;
    margin:0 1px;
}
.main-nav li a{
    display:inline-block;
    color:#222222;
    text-transform:uppercase;
    font-family: 'Montserrat', sans-serif;
    text-decoration: none;
    line-height:20px;
    margin:17px 32px;
    transition:all 0.3s ease-in-out;
    -moz-transition:all 0.3s ease-in-out;
    -webkit-transition:all 0.3s ease-in-out;
}

.main-nav li a:hover{
    text-decoration:none;
    color: #7cc576;
}

.small-logo{
    padding:0 32px;
}

.main-section{
    padding:90px 0 110px;
}

<header class="header" id="header">
        <!--header-start-->
        <div class="container">
            large Hero
        </div>
    </header>
<div class="small-logo" style="text-align:center"><a href="#header"><img src="~/Content/img/wop_small_logo.png" alt="logo"></a></div>
    <nav class="main-nav-outer" id="test">
        <!--main-nav-start-->
        <div class="container">
            <ul class="main-nav">
                <li><a href="#header">Home</a></li>
                <li><a href="#service">Services</a></li>
                <li><a href="#Portfolio">Portfolio</a></li>
                <li><a href="#client">Clients</a></li>
                <li><a href="#team">Team</a></li>
                <li><a href="#contact">Contact</a></li>
            </ul>
            <a class="res-nav_click" href="#"><i class="fa-bars"></i></a>
        </div>
    </nav>

    <section class="main-section" id="service">
    <!--main-section-start-->
    <div class="container">
       Bunch o stuff
    </div>
</section><!--main-section-end-->


问:
How to generate a value using pre defined mask
I am working on a hardware that is a bit tricky...for example one its 32bit registers looks like this (the upper 16bits are all zero)

```<code>#define MASK_DBG_CTRL_FIFO_SPLIT            0b0000000000000001
#define MASK_DBG_CTRL_FIFO_ENABLE           0b0000000000000010
#define MASK_DBG_CTRL_ADC_SPLIT             0b0000000000000100
#define MASK_DBG_CTRL_ADC_ENABLE            0b0000000000001000
#define MASK_DBG_CTRL_MAX_COUNTER           0b1111111111110000

#define NO_SPLIT                            0
#define WITH_SPLIT                          1
#define DISABLE                             0
#define ENABLE                              1
</code>```

My question is, how can I generate a number that I need to write into this register. E.g. I will have a function that gets numbers from user and returns the value ready to be written to register.

This seems to be a very painfull process...I have a dozen of similar registers that have different bit-width and stuff...How can I make this easier?

For one, How do I even write a desired value at the MASK_DBG_CTRL_MAX_COUNTER bits?

```<code>uint32_t generateDebugRegister(uint8_t fifoSplit, uint8_t fifoEnable,
                                uint8_t adcSplit, uint8_t adcEnable,
                                uint16_t counter) {
    uint32_t output = 0;

    switch(fifoSplit) {
    case NO_SPLIT:
        //do nothing;
        break;
    case WITH_SPLIT:
        output = 1UL >> 1; //set bit 0 to 1
        break;
    }

    switch(fifoEnable) {
    case DISABLE:
        //do nothing;
        break;
    case ENABLE:
        output = 1UL >> 2; //set bit 2 to 1
        break;
    }

    switch(adcSplit) {
    case NO_SPLIT:
        //do nothing;
        break;
    case WITH_SPLIT:
        output = 1UL >> 3; //set bit 3 to 1
        break;
    }

    switch(adcEnable) {
    case DISABLE:
        //do nothing;
        break;
    case ENABLE:
        output = 1UL >> 4; //set bit 4 to 1
        break;
    }

    //how to evenset the counter value???

    return output;
}
</code>```

Example of calling function:

```<code>void setDebugRegister(uint32_t value) { /*write to reg*/ };

uint32_t toWrite = generateDebugRegister(NO_SPLIT, DISABLE, WITH_SPLIT, ENABLE, 4256);

setDebugRegister( toWrite);
</code>```

Here is another set of register masks...here I neeed to set the low 10 bits spliced into two 5 bits:

```<code>#define MASK_DAD_NUM_ADDR                   0b0000000000011111
#define MASK_DAD_NUM_DECI                   0b0000001111100000
</code>```

Here, top 8 bits and low 8 bits:

```<code>#define MASK_DBG_REG_ID                     0b1111111100000000;
#define MASK_DBG_REG_CNTR                   0b0000000011111111;
</code>```

答:
How to generate a value using pre defined mask (?)

To address OP's first part:

Consider a re-write of the function signature.  Other suggested changes below as comment code.

```<code>// uint32_t generateDebugRegister(uint8_t fifoSplit, uint8_t fifoEnable,
//     uint8_t adcSplit, uint8_t adcEnable, uint16_t counter) { ...

// use bool for simple T/F values
uint32_t generateDebugRegister(bool fifoSplit, bool fifoEnable, bool adcSplit,
    bool adcEnable, uint16_t counter) {

  uint32_t output = 0;
  if (fifoSplit == WITH_SPLIT) {   // use an `if()`
    output |= MASK_DBG_CTRL_FIFO_SPLIT; // use an 'or' of the mask
  }
  if (fifoEnable == ENABLE) {
    output |= MASK_DBG_CTRL_FIFO_ENABLE;
  }
  .... // like-wise with  adcSplit, adcEnable

  // add an `offset` to simplify shifting needs
  #define MASK_DBG_CTRL_MAX_BIT_OFFSET 4
  #define MASK_DBG_CTRL_MAX_MAX (MASK_DBG_CTRL_MAX_COUNTER >> MASK_DBG_CTRL_MAX_BIT_OFFSET)

  // test, since 16 bits do not fit in 12
  if (counter > MASK_DBG_CTRL_MAX_MAX) {
    Handle_error_with_TBD_Code();
  }
  else {
    output |= (uint32_t)counter << MASK_DBG_CTRL_MAX_BIT_OFFSET;
  }

  return out;
}
</code>```

I have a dozen of similar registers that have different bit-width and stuff...How can I make this easier?

Need to see some of those for a good general answer.

Body:
I am working on a hardware that is a bit tricky...for example one its 32bit registers looks like this (the upper 16bits are all zero)

#define MASK_DBG_CTRL_FIFO_SPLIT            0b0000000000000001
#define MASK_DBG_CTRL_FIFO_ENABLE           0b0000000000000010
#define MASK_DBG_CTRL_ADC_SPLIT             0b0000000000000100
#define MASK_DBG_CTRL_ADC_ENABLE            0b0000000000001000
#define MASK_DBG_CTRL_MAX_COUNTER           0b1111111111110000

#define NO_SPLIT                            0
#define WITH_SPLIT                          1
#define DISABLE                             0
#define ENABLE                              1

My question is, how can I generate a number that I need to write into this register. E.g. I will have a function that gets numbers from user and returns the value ready to be written to register.

This seems to be a very painfull process...I have a dozen of similar registers that have different bit-width and stuff...How can I make this easier?

For one, How do I even write a desired value at the MASK_DBG_CTRL_MAX_COUNTER bits?

uint32_t generateDebugRegister(uint8_t fifoSplit, uint8_t fifoEnable,
                                uint8_t adcSplit, uint8_t adcEnable,
                                uint16_t counter) {
    uint32_t output = 0;

    switch(fifoSplit) {
    case NO_SPLIT:
        //do nothing;
        break;
    case WITH_SPLIT:
        output = 1UL >> 1; //set bit 0 to 1
        break;
    }

    switch(fifoEnable) {
    case DISABLE:
        //do nothing;
        break;
    case ENABLE:
        output = 1UL >> 2; //set bit 2 to 1
        break;
    }

    switch(adcSplit) {
    case NO_SPLIT:
        //do nothing;
        break;
    case WITH_SPLIT:
        output = 1UL >> 3; //set bit 3 to 1
        break;
    }

    switch(adcEnable) {
    case DISABLE:
        //do nothing;
        break;
    case ENABLE:
        output = 1UL >> 4; //set bit 4 to 1
        break;
    }

    //how to evenset the counter value???

    return output;
}

Example of calling function:

void setDebugRegister(uint32_t value) { /*write to reg*/ };

uint32_t toWrite = generateDebugRegister(NO_SPLIT, DISABLE, WITH_SPLIT, ENABLE, 4256);

setDebugRegister( toWrite);

Here is another set of register masks...here I neeed to set the low 10 bits spliced into two 5 bits:

#define MASK_DAD_NUM_ADDR                   0b0000000000011111
#define MASK_DAD_NUM_DECI                   0b0000001111100000

Here, top 8 bits and low 8 bits:

#define MASK_DBG_REG_ID                     0b1111111100000000;
#define MASK_DBG_REG_CNTR                   0b0000000011111111;

Body:
How to generate a value using pre defined mask (?)

To address OP's first part:

Consider a re-write of the function signature.  Other suggested changes below as comment code.

// uint32_t generateDebugRegister(uint8_t fifoSplit, uint8_t fifoEnable,
//     uint8_t adcSplit, uint8_t adcEnable, uint16_t counter) { ...

// use bool for simple T/F values
uint32_t generateDebugRegister(bool fifoSplit, bool fifoEnable, bool adcSplit,
    bool adcEnable, uint16_t counter) {

  uint32_t output = 0;
  if (fifoSplit == WITH_SPLIT) {   // use an `if()`
    output |= MASK_DBG_CTRL_FIFO_SPLIT; // use an 'or' of the mask
  }
  if (fifoEnable == ENABLE) {
    output |= MASK_DBG_CTRL_FIFO_ENABLE;
  }
  .... // like-wise with  adcSplit, adcEnable

  // add an `offset` to simplify shifting needs
  #define MASK_DBG_CTRL_MAX_BIT_OFFSET 4
  #define MASK_DBG_CTRL_MAX_MAX (MASK_DBG_CTRL_MAX_COUNTER >> MASK_DBG_CTRL_MAX_BIT_OFFSET)

  // test, since 16 bits do not fit in 12
  if (counter > MASK_DBG_CTRL_MAX_MAX) {
    Handle_error_with_TBD_Code();
  }
  else {
    output |= (uint32_t)counter << MASK_DBG_CTRL_MAX_BIT_OFFSET;
  }

  return out;
}

I have a dozen of similar registers that have different bit-width and stuff...How can I make this easier?

Need to see some of those for a good general answer.


问:
How to generate Options(CORS) with Swagger
For a project we are working on we are generating an Swagger File automatically. However at this moment we are struggling with the CORS part.

We are using the Amazon API gateway import api functionality. To use this in combination with Swagger and CORS, we have to create an additional action (operation) in our source code which allows CORS(options)  for each api method (operation)!
eg:

```<code>    [HttpOptions]
    [Route("{id}")]
    [ProducesResponseType((int)HttpStatusCode.OK)]
    public IActionResult UserOptions()
    {
        return new OkResult();
    }
</code>```

As you can see this makes the code a lot dirtier. this is a temporary fix, but we can not find another way. Is there any way to generate this in the swagger definition file automatically? Or how can we do this, Amazon API gateway required this (documentation: http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html)

答:
Do the steps to 'Enable CORS' using the easy one-click feature in the console, then deploy the API, and finally go to the Stage and Export the API back to swagger.

Now you can inspect the swagger to see how to configure CORS in your own swagger.

Body:
For a project we are working on we are generating an Swagger File automatically. However at this moment we are struggling with the CORS part.

We are using the Amazon API gateway import api functionality. To use this in combination with Swagger and CORS, we have to create an additional action (operation) in our source code which allows CORS(options)  for each api method (operation)!
eg:

    [HttpOptions]
    [Route("{id}")]
    [ProducesResponseType((int)HttpStatusCode.OK)]
    public IActionResult UserOptions()
    {
        return new OkResult();
    }

As you can see this makes the code a lot dirtier. this is a temporary fix, but we can not find another way. Is there any way to generate this in the swagger definition file automatically? Or how can we do this, Amazon API gateway required this (documentation: http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html)


问:
Checking if One String Equals Another Changing String at a Certain Point in Time with Javascript
There is a string that is always changing it's text.  I made a variable for this string by using querySelector:

```<code>var lastBall = document.querySelector('span#banner')
</code>```

What this string is is it's a countdown for a roulette wheel that spins every 30 seconds.  What I am currently trying to do is log a number (1234) into console anytime that the countdown is at 25.06 seconds remaining until the wheel spins.

I have tried using a while statement to log the number while lastBall is equal to "Rolling in 25.06" (This is the text that's displayed when there's 25.06 seconds remaining before the wheel spins)

```<code>while (lastBall.innerText == "Rolling in 25.06") {
console.log("1234")
</code>```

}

This only returned "undefined" in the console.  I'm assuming that a while statement won't work for what I'm trying to do.  Apparently a setInterval would work somehow, but I'm not sure exactly what code I need to paste into console in order to get this to work.

So in summary, I'm trying to log "1234" into console if the text of lastBall is equal to "Rolling in 25.06".  Any help is appreciated, thanks.

答:
```<code>setInterval(function(){
  if(lastBall.innerText === "Rolling in 25.06") console.log("1234");
}, 10);
</code>```

A whileloop blocks the execution while a really fast running Interval doesnt.

Body:
There is a string that is always changing it's text.  I made a variable for this string by using querySelector:

var lastBall = document.querySelector('span#banner')

What this string is is it's a countdown for a roulette wheel that spins every 30 seconds.  What I am currently trying to do is log a number (1234) into console anytime that the countdown is at 25.06 seconds remaining until the wheel spins.

I have tried using a while statement to log the number while lastBall is equal to "Rolling in 25.06" (This is the text that's displayed when there's 25.06 seconds remaining before the wheel spins)

while (lastBall.innerText == "Rolling in 25.06") {
console.log("1234")

}

This only returned "undefined" in the console.  I'm assuming that a while statement won't work for what I'm trying to do.  Apparently a setInterval would work somehow, but I'm not sure exactly what code I need to paste into console in order to get this to work.

So in summary, I'm trying to log "1234" into console if the text of lastBall is equal to "Rolling in 25.06".  Any help is appreciated, thanks.

Body:
setInterval(function(){
  if(lastBall.innerText === "Rolling in 25.06") console.log("1234");
}, 10);

A whileloop blocks the execution while a really fast running Interval doesnt.


问:
How to add Page Numbers for each printed page SSRS?
I want to make it so that when you print a page in SSRS, it will correctly show you the number of each page you print out. Is that possible in ssrs? </p>

答:
You can simply add a footer (or header) to your report and use the Globals!PageNumber and/or Globals!TotalPages in a textbox. You can combine the two as well. So, add a footer to the report, add a new textbox and set the expression to

="page " & Globals!PageNumber & " of " & Globals!TotalPages

Note: The page numbers will differ from viewing on screen to printing as the interactive size is not always the same as the printed size.


问:
How to find url parameters in JavaScript, or jQuery, then apply an event listener?
So I have this url:
/somepage/goes-here/something?image=main_image.jpg&type=shirt

How do I get out the two different attributes to then apply an eventListener to them?

I've tried the following:

```<code>var originalUrl = window.location.href
var type = originalUrl.search.get("type");
var image = originalUrl.search.get("image");
</code>```

But I don't really think I'm getting the attributes with .search.get. Plus it errors with .search.get("type") is not a function.

I've also tried the following:

```<code>function getParam(param){
return new URLSearchParams(window.location.search).get(type);
}
</code>```

I'm honestly not too familiar with URLSearchParams but wouldn't it be similar to above? How would I get both params here?

I also have for jQuery, which I'm not familiar with, the following:

```<code>$(function(){
$.url.attr('image')
$.url.attr('type')
});
</code>```

This one...no idea. But it fails as it's not bringing in the url.

答:
Alternatively you could construct a URL object and grab them as so:

```<code>var originalUrl = new URL(location.href);
var type = originalUrl.searchParams.get('type');
var image = originalUrl.searchParams.get('image');
</code>```

One thing to note. As of this post it seems that it's not supported by IE.

Body:
So I have this url:
/somepage/goes-here/something?image=main_image.jpg&type=shirt

How do I get out the two different attributes to then apply an eventListener to them?

I've tried the following:

var originalUrl = window.location.href
var type = originalUrl.search.get("type");
var image = originalUrl.search.get("image");

But I don't really think I'm getting the attributes with .search.get. Plus it errors with .search.get("type") is not a function.

I've also tried the following:

function getParam(param){
return new URLSearchParams(window.location.search).get(type);
}

I'm honestly not too familiar with URLSearchParams but wouldn't it be similar to above? How would I get both params here?

I also have for jQuery, which I'm not familiar with, the following:

$(function(){
$.url.attr('image')
$.url.attr('type')
});

This one...no idea. But it fails as it's not bringing in the url.

Body:
Alternatively you could construct a URL object and grab them as so:

var originalUrl = new URL(location.href);
var type = originalUrl.searchParams.get('type');
var image = originalUrl.searchParams.get('image');

One thing to note. As of this post it seems that it's not supported by IE.


问:
Generate Next Fibonacci numbers
I was given this question about generating fib numbers. The recursive implementation of fib numbers which I've seen were always from top to previous like fib(n)=fib(n-1) + fib(n-2) but this question is assuming fib(n-1), fib(n-2) exist calculate next and so forth.</p>

```<code>public class Fibonacci {
    int[] fiboNums;

    public Fibonacci(int n) {
        // TODO: generate the first n fibonacci numbers
    }

    private void generateNextFibo(int n, int lastFibo, int lastLastFibo) {
        // TODO: Implement this recursive function to compute next
        // fibonacci number.
    }

    public int[] getAll() {
        return  fiboNums;
    }
}
</code>```

答:
The first tricky part is with what passing params generateNextFibo needs to be called. the second part is the exit condition of generateNextFibo method.</p>

```<code>public class Fibonacci {
    int fiboNums[];

    public Fibonacci(int n) {
        // generate the first n fibonacci numbers
        fiboNums = new int[n];
        fiboNums[0] = 1;
        fiboNums[1] = 1;

        // Start from 3 since the first two fibo numbers are given
        if (n >= 3)
            generateNextFibo(3, fiboNums[1], fiboNums[0]);
    }

    private void generateNextFibo(int n, int lastFibo, int lastLastFibo) {
        // Implement this recursive function to compute next fibo number.
        fiboNums[n - 1] = lastFibo + lastLastFibo;
        if (fiboNums.length > n) {
            lastLastFibo = lastFibo;
            lastFibo = fiboNums[n - 1];
            generateNextFibo(n + 1, lastFibo, lastLastFibo);
        }
    }

    public int[] getAll() {
        return  fiboNums;
    }
}
</code>```

Title: Generate Next Fibonacci numbers

Body:
I was given this question about generating fib numbers. The recursive implementation of fib numbers which I've seen were always from top to previous like fib(n)=fib(n-1) + fib(n-2) but this question is assuming fib(n-1), fib(n-2) exist calculate next and so forth.

public class Fibonacci {
    int[] fiboNums;

    public Fibonacci(int n) {
        // TODO: generate the first n fibonacci numbers
    }

    private void generateNextFibo(int n, int lastFibo, int lastLastFibo) {
        // TODO: Implement this recursive function to compute next
        // fibonacci number.
    }

    public int[] getAll() {
        return  fiboNums;
    }
}

Body:
The first tricky part is with what passing params generateNextFibo needs to be called. the second part is the exit condition of generateNextFibo method.

public class Fibonacci {
    int fiboNums[];

    public Fibonacci(int n) {
        // generate the first n fibonacci numbers
        fiboNums = new int[n];
        fiboNums[0] = 1;
        fiboNums[1] = 1;

        // Start from 3 since the first two fibo numbers are given
        if (n >= 3)
            generateNextFibo(3, fiboNums[1], fiboNums[0]);
    }

    private void generateNextFibo(int n, int lastFibo, int lastLastFibo) {
        // Implement this recursive function to compute next fibo number.
        fiboNums[n - 1] = lastFibo + lastLastFibo;
        if (fiboNums.length > n) {
            lastLastFibo = lastFibo;
            lastFibo = fiboNums[n - 1];
            generateNextFibo(n + 1, lastFibo, lastLastFibo);
        }
    }

    public int[] getAll() {
        return  fiboNums;
    }
}


问:
using search functionality in thymeleaf with request parameters
I have a page where I get a list of entries. Now, I want to be able to search from those list.

my current url for retrieving list is this /show/products. I want to add a search form in this page so that I can search with request parameter.
Yes, I can use ajax but I have to do it with request parameters.

So if I search for a product name, then - /show/products?name=someName

<form ui-jp="parsley" th:action="@{/show/products(name=${pName})}" th:object="${pName}" method="get">

            Search by Name:
            <input id="filter" type="text" th:field="*{pName}" class="form-control input-sm w-auto inline m-r"/>
            <button class="md-btn md-fab m-b-sm indigo">
                
            </button>

</form>
```

<p>And this is what I tried in controller:</p>

```@GetMapping("/show/products")
public String getProduct(Model model,
                         @RequestParam(required = false) String name,
                         @ModelAttribute String pName) {

    List<Product> products = this.productService.getAllProducts(name)
    model.addAttribute("products", products);
    return "show_product";
}
```

<p>I am getting this error:</p>

```Neither BindingResult nor plain target object for bean name 'pName' available as request attribute
    at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153)
    at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:897)
```

答:
You are trying to use variable pName (Model attribute) as a form object.

In your view you are passing a model attribute to form like this th:object="${pName}" but instead you need to pass a form object.

A form object is not a class but rather a simple java object (POJO). You can think of form object as your form but on server side.

Before you can use form object in your view, you need to create it and add it to the Model.

you will define it like this

```<code>public class MyFormObject{
    private String pName;
    public String getPName(){
        return pName;
    }
    public void setPName(String pName){
        this.pName = pName;
    }
}
</code>```

now your controller method will become

```<code>@GetMapping("/show/products")
public String getProduct(Model model,
    @ModelAttribute("myFormObject") MyFormObject myFormObject,
    BindingResult result) {
    List<Product> products = this.productService.getAllProducts(myFormObject.getPName());
    model.addAttribute("products", products);
    return "show_product";
}
</code>```

Then you can pass the form object to your form like this

```<code>                       <form ui-jp="parsley" th:action="@{/show/products}" th:object="${myFormObject}" method="get">
                            <div class="row m-b">
                                <div class="col-sm-6">
                                    Search by Name: <input id="filter" type="text" th:field="*{pName}" class="form-control input-sm w-auto inline m-r"/>
                                    <button class="md-btn md-fab m-b-sm indigo"><i class="material-icons md-24"></i></button>
                                </div>
                            </div>
                        </form>
</code>```

You need to read the documentation, all these are explained there in detail.

Body:
I have a page where I get a list of entries. Now, I want to be able to search from those list.

my current url for retrieving list is this /show/products. I want to add a search form in this page so that I can search with request parameter.
Yes, I can use ajax but I have to do it with request parameters.

So if I search for a product name, then - /show/products?name=someName

<form ui-jp="parsley" th:action="@{/show/products(name=${pName})}" th:object="${pName}" method="get">

            Search by Name:
            <input id="filter" type="text" th:field="*{pName}" class="form-control input-sm w-auto inline m-r"/>
            <button class="md-btn md-fab m-b-sm indigo">
                
            </button>

</form>

And this is what I tried in controller:

@GetMapping("/show/products")
public String getProduct(Model model,
                         @RequestParam(required = false) String name,
                         @ModelAttribute String pName) {

    List<Product> products = this.productService.getAllProducts(name)
    model.addAttribute("products", products);
    return "show_product";
}

I am getting this error:

Neither BindingResult nor plain target object for bean name 'pName' available as request attribute
    at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153)
    at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:897)

Body:
You are trying to use variable pName (Model attribute) as a form object.

In your view you are passing a model attribute to form like this th:object="${pName}" but instead you need to pass a form object.

A form object is not a class but rather a simple java object (POJO). You can think of form object as your form but on server side.

Before you can use form object in your view, you need to create it and add it to the Model.

you will define it like this

public class MyFormObject{
    private String pName;
    public String getPName(){
        return pName;
    }
    public void setPName(String pName){
        this.pName = pName;
    }
}

now your controller method will become

@GetMapping("/show/products")
public String getProduct(Model model,
    @ModelAttribute("myFormObject") MyFormObject myFormObject,
    BindingResult result) {
    List<Product> products = this.productService.getAllProducts(myFormObject.getPName());
    model.addAttribute("products", products);
    return "show_product";
}

Then you can pass the form object to your form like this

                       <form ui-jp="parsley" th:action="@{/show/products}" th:object="${myFormObject}" method="get">
                            <div class="row m-b">
                                <div class="col-sm-6">
                                    Search by Name: <input id="filter" type="text" th:field="*{pName}" class="form-control input-sm w-auto inline m-r"/>
                                    <button class="md-btn md-fab m-b-sm indigo"><i class="material-icons md-24">&#xe8b6;</i></button>
                                </div>
                            </div>
                        </form>

You need to read the documentation, all these are explained there in detail.


问:
nginx + vueJS + static landing page
I need to open the landing page on /, and vueJS application on /app. Here is my current nginx setup:

```<code>server {
    listen 80;

    location /app {
            alias /var/www/app/dist/;
            try_files $uri $uri/ /index.html;
    }

    location / {
            alias /var/www/landing/dist/;
            try_files $uri $uri/ /index.html;
    }
}
</code>```

It opens landing on /, and vueJS app when I go to /app, however, if I open /app/login it goes to landing page instead of vue application. What am I doing wrong ?

答:
I have no idea why, but adding last to vue application configuration fixed it. Here is how the config looks now:

```<code>server {
    listen 80;

    location /app {
        alias /var/www/app/dist; # removed the / at the end
        try_files $uri $uri/ /index.html last; # here is the trick
    }

    location / {
        alias /var/www/landing/dist/;
        try_files $uri $uri/ /index.html;
    }
}
</code>```

Title: nginx + vueJS + static landing page

Body:
I need to open the landing page on /, and vueJS application on /app. Here is my current nginx setup:

server {
    listen 80;

    location /app {
            alias /var/www/app/dist/;
            try_files $uri $uri/ /index.html;
    }

    location / {
            alias /var/www/landing/dist/;
            try_files $uri $uri/ /index.html;
    }
}

It opens landing on /, and vueJS app when I go to /app, however, if I open /app/login it goes to landing page instead of vue application. What am I doing wrong ?

Body:
I have no idea why, but adding last to vue application configuration fixed it. Here is how the config looks now:

server {
    listen 80;

    location /app {
        alias /var/www/app/dist; # removed the / at the end
        try_files $uri $uri/ /index.html last; # here is the trick
    }

    location / {
        alias /var/www/landing/dist/;
        try_files $uri $uri/ /index.html;
    }
}


问:
Getting one element to match the scrolling of another
I have two tall and narrow elements of equal height that are next to each other. When I scroll one of these two elements, I want the other to scroll with it.

How can I do this using jQuery? I've tried the ScrollTo plugin but the documentation is so bad I can't figure out how to use it.

答:
This is not the answer you are looking for, but it needs to be said: what you are doing is bad design, it has been done many times before and has never been part of a nice userinterface. Instead of wasting a lot of energy on creating a solution where you battle the browsers, spend it coming up with a design that works better, and is easier to implement.

In your case: if you wish two lists of objects to scroll together, make them live under a single scrollbar.

For instance if it is two multiple select boxes, just make sure they both have the full height of their contents so their scrollbars become inactive/disappear, and then wrap them in a div with a smaller height and set it to overflow: scroll.

In general if you come up against something like this where there is no clear and easy way to do it, stop and think why that is, and maybe you will realize that it is because it is a bad idea.

This will certainly not always be true, but quite often it will.

ContentLicense: CC BY-SA 2.5


问:
libreoffice5.1.3 error while loading shared libraries: libdbus-glib-1.so.2
I installed libreoffice5.1.3 on my VPS centos 7

when i try to launch libreoffice it is showing following error

libreoffice5.3 javaldx: Could not find a Java Runtime Environment! Warning: failed to read path from javaldx /opt/libreoffice5.3/program/soffice.bin: error while loading shared libraries: libdbus-glib-1.so.2: cannot open shared object file: No such file

How can i resolve it

Thank you in advance

答:
Maybe is later but try to install this package:

```<code>yum install libdbus-glib-1.so.2
</code>```

So after require this packages:

```<code>libdbus-glib-1.so.2
libcairo.so.2
libcups.so.2libSM.so.6
</code>```

If it is, install all

Body:
Maybe is later but try to install this package:

yum install libdbus-glib-1.so.2

So after require this packages:

libdbus-glib-1.so.2
libcairo.so.2
libcups.so.2libSM.so.6

If it is, install all


问:
ERROR: Error installing yajl-ruby:
Please help... i was tryed all ruby versions and have the same error.

!!!!THIS IS WINDOWS!!!!

```<code>    gem install yajl-ruby
Temporarily enhancing PATH for MSYS/MINGW...
Building native extensions.  This could take a while...
ERROR:  Error installing yajl-ruby:
        ERROR: Failed to build gem native extension.

    current directory: C:/Ruby/lib/ruby/gems/2.4.0/gems/yajl-ruby-1.3.1/ext/yajl
C:/Ruby/bin/ruby.exe -r ./siteconf20171206-2828-1djbqt4.rb extconf.rb
creating Makefile

current directory: C:/Ruby/lib/ruby/gems/2.4.0/gems/yajl-ruby-1.3.1/ext/yajl
make "DESTDIR=" clean
"make" �� ���� ����७��� ��� ���譥�
��������, �ᯮ��塞�� �ணࠬ��� ��� ������ 䠩���.

current directory: C:/Ruby/lib/ruby/gems/2.4.0/gems/yajl-ruby-1.3.1/ext/yajl
make "DESTDIR="
"make" �� ���� ����७��� ��� ���譥�
��������, �ᯮ��塞�� �ணࠬ��� ��� ������ 䠩���.

make failed, exit code 1

Gem files will remain installed in C:/Ruby/lib/ruby/gems/2.4.0/gems/yajl-ruby-1.3.1 for inspection.
Results logged to C:/Ruby/lib/ruby/gems/2.4.0/extensions/x64-mingw32/2.4.0/yajl-ruby-1.3.1/gem_make.out
</code>```

google does not help me also.

UPDATE: the problem was fixed by installing kali linux.
the problem was the windows.
thank you all.
i lost my day on it.

答:
Most probably, the issue is due to msys2 not being installed properly. Check by updating msys2 by running ridk install

check here for more info on successfully ypdating msys2 Install Ruby 2.4.1 in windows within corporate proxy. MSYS2 update fails

Title: ERROR: Error installing yajl-ruby:

Body:
Please help... i was tryed all ruby versions and have the same error.

!!!!THIS IS WINDOWS!!!!

    gem install yajl-ruby
Temporarily enhancing PATH for MSYS/MINGW...
Building native extensions.  This could take a while...
ERROR:  Error installing yajl-ruby:
        ERROR: Failed to build gem native extension.

    current directory: C:/Ruby/lib/ruby/gems/2.4.0/gems/yajl-ruby-1.3.1/ext/yajl
C:/Ruby/bin/ruby.exe -r ./siteconf20171206-2828-1djbqt4.rb extconf.rb
creating Makefile

current directory: C:/Ruby/lib/ruby/gems/2.4.0/gems/yajl-ruby-1.3.1/ext/yajl
make "DESTDIR=" clean
"make" �� ���� ����७��� ��� ���譥�
��������, �ᯮ��塞�� �ணࠬ��� ��� ������ 䠩���.

current directory: C:/Ruby/lib/ruby/gems/2.4.0/gems/yajl-ruby-1.3.1/ext/yajl
make "DESTDIR="
"make" �� ���� ����७��� ��� ���譥�
��������, �ᯮ��塞�� �ணࠬ��� ��� ������ 䠩���.

make failed, exit code 1

Gem files will remain installed in C:/Ruby/lib/ruby/gems/2.4.0/gems/yajl-ruby-1.3.1 for inspection.
Results logged to C:/Ruby/lib/ruby/gems/2.4.0/extensions/x64-mingw32/2.4.0/yajl-ruby-1.3.1/gem_make.out

google does not help me also.

UPDATE: the problem was fixed by installing kali linux.
the problem was the windows.
thank you all.
i lost my day on it.


问:
how can the directory of a usb drive connected to a system be obtained?
I need to obtain the path to the directory created for a usb drive(I think it's something like /media/user/xxxxx) for a simple usb mass storage device browser that I am making. Can anyone suggest the best/simplest way to do this? I am using an Ubuntu 13.10 machine and will be using it on a linux device.

Need this in python.

答:
I had to modify @m.wasowski 's code to make it work on Python3.5.4 as follows.</p>

```<code>def get_mount_points(devices=None):
    devices = devices or get_usb_devices()  # if devices are None: get_usb_devices
    output = check_output(['mount']).splitlines()
    output = [tmp.decode('UTF-8') for tmp in output]

    def is_usb(path):
        return any(dev in path for dev in devices)
    usb_info = (line for line in output if is_usb(line.split()[0]))
    return [(info.split()[0], info.split()[2]) for info in usb_info]
</code>```

Body:
I had to modify @m.wasowski 's code to make it work on Python3.5.4 as follows.

def get_mount_points(devices=None):
    devices = devices or get_usb_devices()  # if devices are None: get_usb_devices
    output = check_output(['mount']).splitlines()
    output = [tmp.decode('UTF-8') for tmp in output]

    def is_usb(path):
        return any(dev in path for dev in devices)
    usb_info = (line for line in output if is_usb(line.split()[0]))
    return [(info.split()[0], info.split()[2]) for info in usb_info]


问:
Google Closure suppress warning messages for a particular file
I am using google closure compiler to compress all the javascript into single file.

While compliance it give lot of warning messages.In my case I have already compressed third party JS files, Which causes complete file to be printed on browser (i saw build progress in browser) for a single error. I cannot modify third party js due to licenses issue.

I am getting tons of warning messages with complete code in browser window, which causes browser to be hanged.

How can I suppressed all the warnings for particular file.

答: Use the --hide_warnings_for=node_modules/somelibrary flag.


问:
Matching fixed-format numbers and optional string in regex
Regex newbie! I would like to validate a time string in the format HH:MM with an optional space and AM or PM suffix.

Example: 10:30 or 10:30 AM will both be valid.

Here's what I have so far which is failing:

```<code>  $test = '12:34';
  if(!preg_match("/^\d{2}:\d{2}?\s(AM|PM)$/", $test))
  {
      echo "bad format!";
  }
</code>```

In addition, is it possible to validate that the HH or MM values are <= 12 and <=60 respectively within the same regex?

Regards, Ben.

答:
Alternative to using regular expression for matching valid minute and hour you can capture them and then use comparison operators as:</p>

```<code>$test = '12:14';
if( preg_match("/^(\d{2}):(\d{2})(?:\s?AM|PM)?$/", $test,$m) &&
    $m[1] >= 0 && $m[1] < 12 &&
    $m[2] >= 0 && $m[2] < 60) {
        echo "good format";
} else {
        echo "bad format!";
}
</code>```

Body:
Regex newbie! I would like to validate a time string in the format HH:MM with an optional space and AM or PM suffix.

Example: 10:30 or 10:30 AM will both be valid.

Here's what I have so far which is failing:

  $test = '12:34';
  if(!preg_match("/^\d{2}:\d{2}?\s(AM|PM)$/", $test))
  {
      echo "bad format!";
  }

In addition, is it possible to validate that the HH or MM values are <= 12 and <=60 respectively within the same regex?

Regards, Ben.

Body:
Alternative to using regular expression for matching valid minute and hour you can capture them and then use comparison operators as:

$test = '12:14';
if( preg_match("/^(\d{2}):(\d{2})(?:\s?AM|PM)?$/", $test,$m) &&
    $m[1] >= 0 && $m[1] < 12 &&
    $m[2] >= 0 && $m[2] < 60) {
        echo "good format";
} else {
        echo "bad format!";
}


问:
Remove classes from wc_get_product_cat_class Woocommerce Function
The wc_get_product_cat_class function in Woocommerce wc-template-functions.php adds the classes 'first' and 'last' to some of my
 elements.

I would like to remove those classes. Does anyone know how I can overwrite this in my functions.php without editing the actual Woocommerce functions?

I've searched everywhere but can't find any solutions. I'm still pretty new at this, hopefully this isn't too much of a dumbass question :/

Below is the function from wc-template-functions.php

```<code>function wc_get_product_cat_class( $class = '', $category = null ) {
    global $woocommerce_loop;

    $classes   = is_array( $class ) ? $class : array_map( 'trim', explode( ' ', $class ) );
    $classes[] = 'product-category';
    $classes[] = 'product';

    if ( 0 === ( $woocommerce_loop['loop'] - 1 ) % $woocommerce_loop['columns'] || 1 === $woocommerce_loop['columns'] ) {
        $classes[] = 'first';
    }

    if ( 0 === $woocommerce_loop['loop'] % $woocommerce_loop['columns'] ) {
        $classes[] = 'last';
    }

    $classes = apply_filters( 'product_cat_class', $classes, $class, $category );

    return array_unique( array_filter( $classes ) );
}
</code>```

And this is the code from content-product_cat.php template that calls the function

```<code><li <?php wc_product_cat_class( '', $category ); ?>>
    <?php
    /**
     * woocommerce_before_subcategory hook.
     *
     * @hooked woocommerce_template_loop_category_link_open - 10
     */
    do_action( 'woocommerce_before_subcategory', $category );

    /**
     * woocommerce_before_subcategory_title hook.
     *
     * @hooked woocommerce_subcategory_thumbnail - 10
     */
    do_action( 'woocommerce_before_subcategory_title', $category );

    /**
     * woocommerce_shop_loop_subcategory_title hook.
     *
     * @hooked woocommerce_template_loop_category_title - 10
     */
    do_action( 'woocommerce_shop_loop_subcategory_title', $category );

    /**
     * woocommerce_after_subcategory_title hook.
     */
    do_action( 'woocommerce_after_subcategory_title', $category );

    /**
     * woocommerce_after_subcategory hook.
     *
     * @hooked woocommerce_template_loop_category_link_close - 10
     */
    do_action( 'woocommerce_after_subcategory', $category ); ?>
</li>
</code>```

答:
Delayed but thought this may help. You can define your own wc_product_cat_class function and call it from content-product_cat.php

For example:
If you want to remove the "first" and "last" class, you can use the code below.

```<code>function your_own_wc_product_cat_class( $class = '', $category = null ) {
    $product_cat_classes = array_diff( wc_get_product_cat_class( $class, $category ), array( 'first', 'last' ) );
    echo 'class="' . esc_attr( join( ' ', $product_cat_classes ) ) . '"';
}
</code>```

Now you can call this from content-product_cat.php like this <?php ro_wc_product_cat_class() ?>

Body:
The wc_get_product_cat_class function in Woocommerce wc-template-functions.php adds the classes 'first' and 'last' to some of my
 elements.

I would like to remove those classes. Does anyone know how I can overwrite this in my functions.php without editing the actual Woocommerce functions?

I've searched everywhere but can't find any solutions. I'm still pretty new at this, hopefully this isn't too much of a dumbass question :/

Below is the function from wc-template-functions.php

function wc_get_product_cat_class( $class = '', $category = null ) {
    global $woocommerce_loop;

    $classes   = is_array( $class ) ? $class : array_map( 'trim', explode( ' ', $class ) );
    $classes[] = 'product-category';
    $classes[] = 'product';

    if ( 0 === ( $woocommerce_loop['loop'] - 1 ) % $woocommerce_loop['columns'] || 1 === $woocommerce_loop['columns'] ) {
        $classes[] = 'first';
    }

    if ( 0 === $woocommerce_loop['loop'] % $woocommerce_loop['columns'] ) {
        $classes[] = 'last';
    }

    $classes = apply_filters( 'product_cat_class', $classes, $class, $category );

    return array_unique( array_filter( $classes ) );
}

And this is the code from content-product_cat.php template that calls the function

<li <?php wc_product_cat_class( '', $category ); ?>>
    <?php
    /**
     * woocommerce_before_subcategory hook.
     *
     * @hooked woocommerce_template_loop_category_link_open - 10
     */
    do_action( 'woocommerce_before_subcategory', $category );

    /**
     * woocommerce_before_subcategory_title hook.
     *
     * @hooked woocommerce_subcategory_thumbnail - 10
     */
    do_action( 'woocommerce_before_subcategory_title', $category );

    /**
     * woocommerce_shop_loop_subcategory_title hook.
     *
     * @hooked woocommerce_template_loop_category_title - 10
     */
    do_action( 'woocommerce_shop_loop_subcategory_title', $category );

    /**
     * woocommerce_after_subcategory_title hook.
     */
    do_action( 'woocommerce_after_subcategory_title', $category );

    /**
     * woocommerce_after_subcategory hook.
     *
     * @hooked woocommerce_template_loop_category_link_close - 10
     */
    do_action( 'woocommerce_after_subcategory', $category ); ?>

Body:
Delayed but thought this may help. You can define your own wc_product_cat_class function and call it from content-product_cat.php

For example:
If you want to remove the "first" and "last" class, you can use the code below.

function your_own_wc_product_cat_class( $class = '', $category = null ) {
    $product_cat_classes = array_diff( wc_get_product_cat_class( $class, $category ), array( 'first', 'last' ) );
    echo 'class="' . esc_attr( join( ' ', $product_cat_classes ) ) . '"';
}

Now you can call this from content-product_cat.php like this <?php ro_wc_product_cat_class() ?>


问:
R filtering a data frame creates empty rows
I have a csv file imported into R where I want to filter out rows that don't include a certain letter in one of the columns. I've tried both subset and dplyr and both of them produce the column names but turn up empty rows. I know that the column contains the letter I'm looking for, so I don't understand why the rows are empty.
This is what I get when I call the head function on my data set:

```<code>head(dbbt)
   X.Focal_DB. X.Effect_size. X.Variance.            X.Study. X.BT.
1         165        -0.1931   0.0132000      'Agrawal_1998'   'B'
2          21        -1.4414   0.1938000      'Agrawal_1999'   'B'
3          19        -3.1642   0.2402559      'Agrawal_1999'   'B'
4          19        -1.0272   0.0731000 'Agrawal_1999-2000'   'B'
</code>```

(the colnames imported with an X. . around them, and I can't figure out why- they don't contain any forbidden characters)

when I try:

```<code> dbbtjustb <- subset(dbbt, X.BT. == "B")
</code>```

I get:

```<code>head(dbbtjustb)
[1] X.Focal_DB.    X.Effect_size. X.Variance.    X.Study.
[5] X.BT.
<0 rows> (or 0-length row.names)
</code>```

when I tried:

```<code>dbbt %>%
    select(X.F_DietBreadth., X.Effect_size., X.variance., X.Bottom_up_top_down.) %>%
    filter(X.Bottom_up_top_down. == "B")
</code>```

I got the same thing. Please help!

edit: structure (this is not my original data set, because that was huge)

```<code>structure(list(X.Focal_DB. = c(31L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 8L, 1L, 1L, 1L, 1L, 2L, 6L, 126L, 22L, 126L, 27L), X.Effect_size. = c(-0.0951,
0.4797, -0.1705, 0.713, -0.2661, -0.6614, -1.5941, -2.1892, -0.2133,
-0.2183, -0.0275, -0.268, -5.0499, -3.2934, -0.9469, 0.6316,
2.236, 0.1724, 1.6541, -1.5496), X.Variance. = c(0.1006223807,
0.0468390134, 0.0124, 0.014674063, 0.1385, 0.15, 0.3866, 0.4706,
0.1025, 0.3688, 0.1354, 0.1444, 0.1641758772, 0.0849100448, 0.0783,
0.040866755, 0.1814043974, 0.0535, 0.1503, 0.0999), X.Study. = structure(c(1L,
2L, 3L, 4L, 6L, 6L, 5L, 5L, 7L, 8L, 9L, 9L, 10L, 10L, 11L, 12L,
13L, 14L, 15L, 16L), .Label = c("'Bergeson & Messina_1997'",
"'Bergeson & Messina_1997- 1998'", "'Cronin & Abrahamson_1999'",
"'Dechert & Ulber_2004'", "'Denno_et_al. 2000'", "'Denno & Roderick_1992'",
"'Dorn_et_al. 2003'", "'Evans & England_1996'", "'Ferrenberg & Denno_2003'",
"'Finch & Jones_1989'", "'Floate & Whitham_1994'", "'Formusoh_et_al. 1992'",
"'Forrest_1971'", "'Fritz_1983'", "'Gange & Brown_1989'", "'Gianoli_2000'"
), class = "factor"), X.BT. = structure(c(2L, 3L, 2L, 2L, 2L,
2L, 4L, 2L, 3L, 4L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 2L), .Label = c("'ants'",
"'B'", "'NA'", "'T'"), class = "factor")), .Names = c("X.Focal_DB.",
"X.Effect_size.", "X.Variance.", "X.Study.", "X.BT."), class = "data.frame", row.names = c(NA,
-20L))
</code>```

Body:
I have a csv file imported into R where I want to filter out rows that don't include a certain letter in one of the columns. I've tried both subset and dplyr and both of them produce the column names but turn up empty rows. I know that the column contains the letter I'm looking for, so I don't understand why the rows are empty.
This is what I get when I call the head function on my data set:

head(dbbt)
   X.Focal_DB. X.Effect_size. X.Variance.            X.Study. X.BT.
1         165        -0.1931   0.0132000      'Agrawal_1998'   'B'
2          21        -1.4414   0.1938000      'Agrawal_1999'   'B'
3          19        -3.1642   0.2402559      'Agrawal_1999'   'B'
4          19        -1.0272   0.0731000 'Agrawal_1999-2000'   'B'

(the colnames imported with an X. . around them, and I can't figure out why- they don't contain any forbidden characters)

when I try:

 dbbtjustb <- subset(dbbt, X.BT. == "B")

I get:

head(dbbtjustb)
[1] X.Focal_DB.    X.Effect_size. X.Variance.    X.Study.
[5] X.BT.
<0 rows> (or 0-length row.names)

when I tried:

dbbt %>%
    select(X.F_DietBreadth., X.Effect_size., X.variance., X.Bottom_up_top_down.) %>%
    filter(X.Bottom_up_top_down. == "B")

I got the same thing. Please help!

edit: structure (this is not my original data set, because that was huge)

structure(list(X.Focal_DB. = c(31L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 8L, 1L, 1L, 1L, 1L, 2L, 6L, 126L, 22L, 126L, 27L), X.Effect_size. = c(-0.0951,
0.4797, -0.1705, 0.713, -0.2661, -0.6614, -1.5941, -2.1892, -0.2133,
-0.2183, -0.0275, -0.268, -5.0499, -3.2934, -0.9469, 0.6316,
2.236, 0.1724, 1.6541, -1.5496), X.Variance. = c(0.1006223807,
0.0468390134, 0.0124, 0.014674063, 0.1385, 0.15, 0.3866, 0.4706,
0.1025, 0.3688, 0.1354, 0.1444, 0.1641758772, 0.0849100448, 0.0783,
0.040866755, 0.1814043974, 0.0535, 0.1503, 0.0999), X.Study. = structure(c(1L,
2L, 3L, 4L, 6L, 6L, 5L, 5L, 7L, 8L, 9L, 9L, 10L, 10L, 11L, 12L,
13L, 14L, 15L, 16L), .Label = c("'Bergeson & Messina_1997'",
"'Bergeson & Messina_1997- 1998'", "'Cronin & Abrahamson_1999'",
"'Dechert & Ulber_2004'", "'Denno_et_al. 2000'", "'Denno & Roderick_1992'",
"'Dorn_et_al. 2003'", "'Evans & England_1996'", "'Ferrenberg & Denno_2003'",
"'Finch & Jones_1989'", "'Floate & Whitham_1994'", "'Formusoh_et_al. 1992'",
"'Forrest_1971'", "'Fritz_1983'", "'Gange & Brown_1989'", "'Gianoli_2000'"
), class = "factor"), X.BT. = structure(c(2L, 3L, 2L, 2L, 2L,
2L, 4L, 2L, 3L, 4L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 2L), .Label = c("'ants'",
"'B'", "'NA'", "'T'"), class = "factor")), .Names = c("X.Focal_DB.",
"X.Effect_size.", "X.Variance.", "X.Study.", "X.BT."), class = "data.frame", row.names = c(NA,
-20L))

Body:
The actual entry is 'B', which means you need to subset by "'B'".

> unique(df$X.BT.)
[1] 'B'    'NA'   'T'    'ants'

using dplyr

> filter(df, X.BT. == "'B'")
   X.Focal_DB. X.Effect_size. X.Variance.                   X.Study. X.BT.
1           31        -0.0951  0.10062238  'Bergeson & Messina_1997'   'B'
2            1        -0.1705  0.01240000 'Cronin & Abrahamson_1999'   'B'
3            1         0.7130  0.01467406     'Dechert & Ulber_2004'   'B'
4            1        -0.2661  0.13850000    'Denno & Roderick_1992'   'B'
5            1        -0.6614  0.15000000    'Denno & Roderick_1992'   'B'
6            1        -2.1892  0.47060000        'Denno_et_al. 2000'   'B'
7            1        -0.0275  0.13540000  'Ferrenberg & Denno_2003'   'B'
8            1        -0.2680  0.14440000  'Ferrenberg & Denno_2003'   'B'
9            1        -5.0499  0.16417588       'Finch & Jones_1989'   'B'
10           1        -3.2934  0.08491004       'Finch & Jones_1989'   'B'
11           6         0.6316  0.04086675     'Formusoh_et_al. 1992'   'B'
12         126         2.2360  0.18140440             'Forrest_1971'   'B'
13         126         1.6541  0.15030000       'Gange & Brown_1989'   'B'
14          27        -1.5496  0.09990000             'Gianoli_2000'   'B'


问:
Set baseURL in Artifactory via REST API
I am installing Artifactory using this docker image docker.bintray.io/jfrog/artifactory-oss:5.4.6 in kubernetes and then configuring an existing load balancer to point to it over https only.

When I curl to artifactory it redirects the https url to http:

```<code>< HTTP/2 302
< date: Tue, 05 Dec 2017 22:42:37 GMT
< content-length: 0
< location: http://dev-artifactory.lark.com/artifactory/webapp/
</code>```

According to https://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API#ArtifactoryRESTAPI-UpdateCustomURLBase I should be able to issue a curl command to change that base url. However when I try this, which is basically copied from the docs:

```<code>curl -v -X PUT "http://localhost:8081/artifactory/api/system/configuration/baseUrl" \
  -d 'https://dev-artifactory.lark.com/artifactory' \
  -uadmin:XXX -H "Content-type: text/plain"
</code>```

I get a 400 back but no error message:

```<code>< HTTP/1.1 400 Bad Request
</code>```

How can I change this base url? Ideally I could set an ENV var. If I can't figure this out I guess I'll have to add the header X-Artifactory-Override-Base-Url as described at https://www.jfrog.com/confluence/display/RTF/Configuring+Artifactory

答:
The exact command (adding the password) you posted works fine on the exact container version you mentioned. Are you trying to run this command as Artifactory is still starting up?

In any case, even if it worked, the better approach is to use the X-Artifactory-Override-Base-Url. This allows you to have potentially multiple different names for the Artifactory instance and avoids having to change any Artifactory configuration.

Title: Set baseURL in Artifactory via REST API

Body:
I am installing Artifactory using this docker image docker.bintray.io/jfrog/artifactory-oss:5.4.6 in kubernetes and then configuring an existing load balancer to point to it over https only.

When I curl to artifactory it redirects the https url to http:

< HTTP/2 302
< date: Tue, 05 Dec 2017 22:42:37 GMT
< content-length: 0
< location: http://dev-artifactory.lark.com/artifactory/webapp/

According to https://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API#ArtifactoryRESTAPI-UpdateCustomURLBase I should be able to issue a curl command to change that base url. However when I try this, which is basically copied from the docs:

curl -v -X PUT "http://localhost:8081/artifactory/api/system/configuration/baseUrl" \
  -d 'https://dev-artifactory.lark.com/artifactory' \
  -uadmin:XXX -H "Content-type: text/plain"

I get a 400 back but no error message:

< HTTP/1.1 400 Bad Request

How can I change this base url? Ideally I could set an ENV var. If I can't figure this out I guess I'll have to add the header X-Artifactory-Override-Base-Url as described at https://www.jfrog.com/confluence/display/RTF/Configuring+Artifactory