问:
How to remove duplicates in particular set of data?
Let's suppose we have two childs who want to get same number or coins (coin nominals 1,2,6,12). Childs don't care about the value.
Example container of permutations which I want to share between two childs:

```<code>{1, 1, 1, 1, 1, 1},
{1, 1, 2, 2},
{1, 2, 1, 2},
{1, 2, 2, 1},
{2, 1, 1, 2},
{2, 1, 2, 1},
{2, 2, 1, 1}
</code>```

Now I`d like to have collections without duplicates:

```<code>child A     child B
2 2         1 1
2 1         2 1
1 1         2 2
1 1 1       1 1 1
</code>```

That permutations are wrong:

```<code>1 2 1 2
1 2 2 1
2 1 1 2
</code>```

because

```<code>child A     child B
1 2         1 2
</code>```

is permutation of

```<code>child A     child B
2 1         2 1
</code>```

which we already have. These collections: 1 2 2 1 and 2 1 1 2 are permutations, as well.

My solution is here, works correctly for that particular input but if you add more coins with different nominals, it doesn't!

```<code>#include <iostream>
#include <vector>
#include <unordered_set>

using namespace std;

int main()
{
    vector<vector<int>> permutations =
    {
        {1, 1, 1, 1, 1, 1},
        {1, 1, 2, 2},
        {1, 2, 1, 2},
        {1, 2, 2, 1},
        {2, 1, 1, 2},
        {2, 1, 2, 1},
        {2, 2, 1, 1}
    };
    vector<pair<unordered_multiset<int>, unordered_multiset<int>>> childSubsets;

    for(const auto &currentPermutation : permutations)
    {
            size_t currentPermutationSize = currentPermutation.size();
            size_t currentPermutationHalfSize = currentPermutationSize / 2;
            //left
            unordered_multiset<int> leftSet;

            for(int i=0;i<currentPermutationHalfSize;++i)
                leftSet.insert(currentPermutation[i]);

            bool leftSubsetExist = false;
            for(const auto &subset : childSubsets)
            {
                if(subset.first == leftSet)
                {
                    leftSubsetExist = true;
                    break;
                }
            }
            //right
            unordered_multiset<int> rightSet;

            for(int i = currentPermutationHalfSize; i < currentPermutationSize; ++i)
                rightSet.insert(currentPermutation[i]);

            bool rightSubsetExist = false;
            for(const auto &subset : childSubsets)
            {
                if(subset.second == rightSet)
                {
                    rightSubsetExist = true;
                    break;
                }
            }
            //summarize
            if(!leftSubsetExist || !rightSubsetExist) childSubsets.push_back({leftSet, rightSet});
    }
    cout << childSubsets.size() << endl;
}
</code>```

How to change the solution to make optimal and less complex?

答:
You should add

```<code>if (leftSubsetExist)
  continue;
</code>```

after first cycle (as optimization)

Could you add some "wrong" permutations (with another coins)?

Body:
Let's suppose we have two childs who want to get same number or coins (coin nominals 1,2,6,12). Childs don't care about the value.
Example container of permutations which I want to share between two childs:

{1, 1, 1, 1, 1, 1},
{1, 1, 2, 2},
{1, 2, 1, 2},
{1, 2, 2, 1},
{2, 1, 1, 2},
{2, 1, 2, 1},
{2, 2, 1, 1}

Now I`d like to have collections without duplicates:

child A     child B
2 2         1 1
2 1         2 1
1 1         2 2
1 1 1       1 1 1

That permutations are wrong:

1 2 1 2
1 2 2 1
2 1 1 2

because

child A     child B
1 2         1 2

is permutation of

child A     child B
2 1         2 1

which we already have. These collections: 1 2 2 1 and 2 1 1 2 are permutations, as well.

My solution is here, works correctly for that particular input but if you add more coins with different nominals, it doesn't!

#include <iostream>
#include <vector>
#include <unordered_set>

using namespace std;

int main()
{
    vector<vector<int>> permutations =
    {
        {1, 1, 1, 1, 1, 1},
        {1, 1, 2, 2},
        {1, 2, 1, 2},
        {1, 2, 2, 1},
        {2, 1, 1, 2},
        {2, 1, 2, 1},
        {2, 2, 1, 1}
    };
    vector<pair<unordered_multiset<int>, unordered_multiset<int>>> childSubsets;

    for(const auto &currentPermutation : permutations)
    {
            size_t currentPermutationSize = currentPermutation.size();
            size_t currentPermutationHalfSize = currentPermutationSize / 2;
            //left
            unordered_multiset<int> leftSet;

            for(int i=0;i<currentPermutationHalfSize;++i)
                leftSet.insert(currentPermutation[i]);

            bool leftSubsetExist = false;
            for(const auto &subset : childSubsets)
            {
                if(subset.first == leftSet)
                {
                    leftSubsetExist = true;
                    break;
                }
            }
            //right
            unordered_multiset<int> rightSet;

            for(int i = currentPermutationHalfSize; i < currentPermutationSize; ++i)
                rightSet.insert(currentPermutation[i]);

            bool rightSubsetExist = false;
            for(const auto &subset : childSubsets)
            {
                if(subset.second == rightSet)
                {
                    rightSubsetExist = true;
                    break;
                }
            }
            //summarize
            if(!leftSubsetExist || !rightSubsetExist) childSubsets.push_back({leftSet, rightSet});
    }
    cout << childSubsets.size() << endl;
}

How to change the solution to make optimal and less complex?

Body:
You should add

if (leftSubsetExist)
  continue;

after first cycle (as optimization)

Could you add some "wrong" permutations (with another coins)?


来源: stackexchange

问:
Observable.of does not work as expected in HttpClient Interceptor

Problem

The Observable.of convert arguments to an observable sequence means it can be used as a mock response to another Observable which is subscribe.
But now, It seems Observable.of does not work when its called from an interceptor because methods which are subscribing to it does not execute

Expected behavior:

When Observable.of is called with the given data, the HttpClient should return the data to the method which is already subscribing to it

Demo

Live Demo  (open DevTools console to read logs)

There is a service (mock.service.ts) which makes a mock HTTP get request using HttpClient, the request arrives at mock.interceptor.ts and it want's to answer with the mock data using Observable.of (means wants to not let the request to goes over the network), the mock.service has a subscriber in app.component which is waiting for the response of the HttpClient. No data arrives in subscriber, nor error.

Any idea about how to implement interceptor that works with Observable.of?

答:
Try to change the return statement in interceptor intercept method to:

```<code>return Observable.of( new HttpResponse<any>( { body: mockData }))
</code>```

Live Demo

ContentLicense: CC BY-SA 3.0

Body:
Try to change the return statement in interceptor intercept method to:

return Observable.of( new HttpResponse<any>( { body: mockData }))

Live Demo


问:
update div after image update in jQuery form js
I Have made a live image upload using jquery.form.js using following function.

```<code>$('#photoimg').on('change', function(){
      $("#imageform").ajaxForm({
        target: '#preview'
      }).submit();
      //AFTER SUCCESS I WANTS TO REFRESH DIV
});
</code>```

And Html is

```<code><div class="col-xs-12 col-sm-4 col-md-2 col-lg-2" id="profileimage">
  <div class="thmb" align="center">
    <div class="thmb-prev">
      <img src="<?=$img_folder.$user->logo_img?>" class="img-responsive" height="200" alt="logo_img" width="200" alt="" />
    </div>
    <h5 class="fm-title" style="text-align:center;">
      <form id="imageform" method="post" enctype="multipart/form-data" action='ajax/ajax_update_profileimage.php'>
        <input type="file" name="photoimg" id="photoimg" />
      </form>
    </h5>
    <h5 class="fm-title" style="text-align:center;">
      <a href=""><i class="fa fa-trash"></i> Remove</a>
    </h5>
  </div><!-- thmb -->
</div>
</code>```

I wants to refresh Profileimage div Only so updated image can be shown.so how to update image or page. i tries

```<code>$('#form').submit(function(){
    $.ajax({
      url: $('#form').attr('action'),
      type: 'POST',
      data : $('#form').serialize(),
      success: function(){
        console.log('form submitted.');
      }
    });
    return false;
});
</code>```

but it doesn't work for me.

答:
Return Actual image path after upload in your ajax. For example :

```<code>$('#form').submit(function(){
    $.ajax({
      url: $('#form').attr('action'),
      type: 'POST',
      data : $('#form').serialize(),
      success: function(result){
        // result can be uploaded image path or a json containing success and image path both like : {sucess:1,image:'sample/image/path'}
        if(result.sucess) {
            $('.thmb-prev img').attr('src',result.image);
        }
      }
   });
   return false;
});
</code>```

I hope this helped.

Body:
I Have made a live image upload using jquery.form.js using following function.

$('#photoimg').on('change', function(){
      $("#imageform").ajaxForm({
        target: '#preview'
      }).submit();
      //AFTER SUCCESS I WANTS TO REFRESH DIV
});

And Html is

      <img src="<?=$img_folder.$user->logo_img?>" class="img-responsive" height="200" alt="logo_img" width="200" alt="" />

      <form id="imageform" method="post" enctype="multipart/form-data" action='ajax/ajax_update_profileimage.php'>
        <input type="file" name="photoimg" id="photoimg" />
      </form>

       Remove

I wants to refresh Profileimage div Only so updated image can be shown.so how to update image or page. i tries

$('#form').submit(function(){
    $.ajax({
      url: $('#form').attr('action'),
      type: 'POST',
      data : $('#form').serialize(),
      success: function(){
        console.log('form submitted.');
      }
    });
    return false;
});

but it doesn't work for me.

Body:
Return Actual image path after upload in your ajax. For example :

$('#form').submit(function(){
    $.ajax({
      url: $('#form').attr('action'),
      type: 'POST',
      data : $('#form').serialize(),
      success: function(result){
        // result can be uploaded image path or a json containing success and image path both like : {sucess:1,image:'sample/image/path'}
        if(result.sucess) {
            $('.thmb-prev img').attr('src',result.image);
        }
      }
   });
   return false;
});

I hope this helped.


问:
Remove part of string but getting the deleted part as result
So, quick question (searched a lot in Google, but only found the answer which produces same response as below):

code:

```<code>var teste = '10/12/2017';
console.log(teste); //returns 10/12/2017
var teste_cut = teste.substr(6,2);
console.log(teste_cut); //returns only 20
</code>```

What I want is 10/12/17. I can't change how the string is created, so I need to change it after getting said string. Does a method for doing this exist, or should I work around with other functions? I'm feeling stupid right now, since it seens to be a fairly obvious answer, but I guess we all get our stupid moments :P

答:
Simple regular expression with replace. match 4 numbers, keep the last two. </p>

```<code>var t = '10/12/2017';
console.log(t.replace(/\d{2}(\d{2})$/, '$1'))
</code>```

Body:
So, quick question (searched a lot in Google, but only found the answer which produces same response as below):

code:

var teste = '10/12/2017';
console.log(teste); //returns 10/12/2017
var teste_cut = teste.substr(6,2);
console.log(teste_cut); //returns only 20

What I want is 10/12/17. I can't change how the string is created, so I need to change it after getting said string. Does a method for doing this exist, or should I work around with other functions? I'm feeling stupid right now, since it seens to be a fairly obvious answer, but I guess we all get our stupid moments :P

Body:
Simple regular expression with replace. match 4 numbers, keep the last two.

var t = '10/12/2017';
console.log(t.replace(/\d{2}(\d{2})$/, '$1'))


问:
Rails: No route matches [POST] nested resources
In the routes.rb I have this nested resource

```<code># OBSERVATIVE SESSIONS
resources :observative_sessions do
# OBSERVATIONS
  resources :observations
end
</code>```

In observations_controller.rb

```<code> def new
   @observative_session = ObservativeSession.find(params[:observative_session_id])
   @observation = Observation.new
   @observation.observative_session_id = @observative_session.id
 end

def create
  @observative_session = ObservativeSession.find(params[:observative_session_id])
  @observation = @observative_session.observations.build(observation_params)
  @observation.user_id = current_user.id

   respond_to do |format|
    if @observation.save
     format.html { redirect_to [@observative_session, @observation], notice: 'Observation was successfully created.' }
     format.json { render :show, status: :created, location: @observation }
    else
     format.html { render :new }
     format.json { render json: @observation.errors, status: :unprocessable_entity }
    end
  end
end
</code>```

And in observations_controller_test.rb I set up both observation and observative session. The test of new works just fine.

```<code>class ObservationsControllerTest < ActionDispatch::IntegrationTest
include Devise::Test::IntegrationHelpers

setup do
  @observative_session = observative_sessions(:one)
  @observation = observations(:two)
  sign_in users(:admin_user)
end

test "should get new" do
  get new_observative_session_observation_path(@observative_session)
  assert_response :success
end

test "should create observation" do
  assert_difference('Observation.count') do
   post observative_session_observation_path(@observative_session, @observation), params: { observation: { start_time: @observation.start_time, description: @observation.description, rating: @observation.rating, notes: @observation.notes, celestial_body_name: @observation.celestial_body_name, telescope_name: @observation.telescope_name, binocular_name: @observation.binocular_name, eyepiece_name: @observation.eyepiece_name, filter_name: @observation.filter_name, user_id: @observation.user_id, observative_session_id: @observation.observative_session_id }}
 end
</code>```

But this is the error I get in the creation test

```<code> test_should_create_observation
 ActionController::RoutingError: No route matches [POST] "/observative_sessions/980190962/observations/298486374"
</code>```

I can't understand what I'm doing wrong.
Thanks for your help.

答:
When you say POST observation_session_observation_path(@observation_session, @observation) you are telling it to post to a url the has both  :observation_session_id and an :id in the params, where the id is that of @obseravtion. However, POST paths for create actions don’t take that last id param (ostensibly you are creating a new record with that action).

Try dropping @observation from your path helper (and make sure you are using the correct create path: observation_session_observations_path(@observation_session).
You can do rake routes to see your routes in your terminal, or localhost:3000/rails/info/routes to see it in the browser.

I also see in your new action you are assigning the observation_session_id manually. I recommend you either do what you do later and call @obervation_session.observations.build, or Observation.new(observation_session: @observation_session). You should avoid setting ids like that.

Body:
In the routes.rb I have this nested resource

# OBSERVATIVE SESSIONS
resources :observative_sessions do
# OBSERVATIONS
  resources :observations
end

In observations_controller.rb

 def new
   @observative_session = ObservativeSession.find(params[:observative_session_id])
   @observation = Observation.new
   @observation.observative_session_id = @observative_session.id
 end

def create
  @observative_session = ObservativeSession.find(params[:observative_session_id])
  @observation = @observative_session.observations.build(observation_params)
  @observation.user_id = current_user.id

   respond_to do |format|
    if @observation.save
     format.html { redirect_to [@observative_session, @observation], notice: 'Observation was successfully created.' }
     format.json { render :show, status: :created, location: @observation }
    else
     format.html { render :new }
     format.json { render json: @observation.errors, status: :unprocessable_entity }
    end
  end
end

And in observations_controller_test.rb I set up both observation and observative session. The test of new works just fine.

class ObservationsControllerTest < ActionDispatch::IntegrationTest
include Devise::Test::IntegrationHelpers

setup do
  @observative_session = observative_sessions(:one)
  @observation = observations(:two)
  sign_in users(:admin_user)
end

test "should get new" do
  get new_observative_session_observation_path(@observative_session)
  assert_response :success
end

test "should create observation" do
  assert_difference('Observation.count') do
   post observative_session_observation_path(@observative_session, @observation), params: { observation: { start_time: @observation.start_time, description: @observation.description, rating: @observation.rating, notes: @observation.notes, celestial_body_name: @observation.celestial_body_name, telescope_name: @observation.telescope_name, binocular_name: @observation.binocular_name, eyepiece_name: @observation.eyepiece_name, filter_name: @observation.filter_name, user_id: @observation.user_id, observative_session_id: @observation.observative_session_id }}
 end

But this is the error I get in the creation test

 test_should_create_observation
 ActionController::RoutingError: No route matches [POST] "/observative_sessions/980190962/observations/298486374"

I can't understand what I'm doing wrong.
Thanks for your help.


问:
PHPexcel array values to column
I have a problem filling columns with array values with PHPexcel i got my query results into arrays. Column A,B,C... not rows !

```<code>while (($red = pg_fetch_assoc($resultID))) {
$nivelacija[] = $red ['nivelacija'];
$dokument[] = $red ['dokument'];
$sifra[] = $red ['sifra'];
$naziv[] = $red ['naziv'];
$kol[] = $red ['kol'];
$pdv[] = $red ['pdv'];
$datum[] = $red ['datum'];
$stara[] = $red ['stara'];
$nova[] = $red ['nova'];
$marza[] = $red ['marza'];
$razlika[] = $red ['razlika'];
$zaduzenje[] = $red ['zaduzenje'];

    }
</code>```

I have tried doing it like

```<code>    for ($i = 1; $i <= 10; $i++) {
$objPHPExcel->getActiveSheet()->fromArray($nivelacija, null, 'A' . $i);
}
</code>```

but no success, looks like fromArray function can only target specific cell. So i have tried changing to this

```<code>for ($i = 1 , $vrednost=0; $i <= 50; $i++ , $vrednost++ ) {
$objPHPExcel->getActiveSheet()->setCellValue('A' .$i, "$nivelacija[$vrednost]" ); }
</code>```

but like this I get results in Column A but everywhere it writes Array(0) to Array (49)

I have tested this it works when I write "$nivelacija[0]" it writes value to targeted column.

I have no idea how to get my array values for each array to a diffrent column, all i have managed to do is to export it to a row but that just doesnt do the job for me.

Can i get somehow pg query directly to excel without arrays ? Even so i would like to solve array to column problem.

EDITS:

result of var_dump ($nivelacija);

```<code>array(8) { [0]=> string(8) "NMP03945" [1]=> string(8) "NMP03944" [2]=> string(8) "NMP03943" [3]=> string(8) "NMP03942" [4]=> string(8) "NMP03942" [5]=> string(8) "NMP03942" [6]=> string(8) "NMP03941" [7]=> string(8) "NMP03940" }
</code>```

It has only 8 values cause the date is selected for only 1 day. It suppose to be used monthly withunknown numbers of values

----Added $sve array

```<code>$sve = array($nivelacija, $dokument, $sifra, $naziv, $kol, $pdv, $datum, $stara, $nova, $marza, $razlika, $zaduzenje);
</code>```

result of var_dumping

```<code>array(12) { [0]=> array(8) { [0]=> string(8) "NMP03945" [1]=> string(8) "NMP03944" [2]=> string(8) "NMP03943" [3]=> string(8) "NMP03942" [4]=> string(8) "NMP03942" [5]=> string(8) "NMP03942" [6]=> string(8) "NMP03941" [7]=> string(8) "NMP03940" } [1]=> array(8) { [0]=> string(8) "RNB15269" [1]=> string(8) "RNB15266" [2]=> string(8) "RNB15264" [3]=> string(8) "RNB15261" [4]=> string(8) "RNB15261" [5]=> string(8) "RNB15261" [6]=> string(8) "RNB15262" [7]=> string(8) "RNB15255" } [2]=> array(8) { [0]=> string(7) "0670723" [1]=> string(7) "4610602" [2]=> string(7) "4610800" [3]=> string(7) "1011910" [4]=> string(7) "4320350" [5]=> string(7) "0291415" [6]=> string(7) "2631463" [7]=> string(7) "4610513" } [3]=> array(8) { [0]=> string(40) "Gree Viola Profi inverter Wifi klima 18k" [1]=> string(16) "Matrix HDMI 1.5m" [2]=> string(31) "CCP-USB2-AMBM-10 USB Printer 3m" [3]=> string(28) "Green PC G1840/H81/4GB/320GB" [4]=> string(21) "HP LaserJet Pro M102a" [5]=> string(31) "Monitor 19 Philips 193V5LSB2/10" [6]=> string(25) "Maxell speedboat USB 16GB" [7]=> string(20) "PC-186 naponski kabl" } [4]=> array(8) { [0]=> string(1) "1" [1]=> string(1) "3" [2]=> string(1) "1" [3]=> string(1) "1" [4]=> string(1) "1" [5]=> string(1) "1" [6]=> string(1) "1" [7]=> string(1) "1" } [5]=> array(8) { [0]=> string(2) "20" [1]=> string(2) "20" [2]=> string(2) "20" [3]=> string(2) "20" [4]=> string(2) "20" [5]=> string(2) "20" [6]=> string(2) "20" [7]=> string(2) "20" } [6]=> array(8) { [0]=> string(10) "2017-11-18" [1]=> string(10) "2017-11-18" [2]=> string(10) "2017-11-18" [3]=> string(10) "2017-11-18" [4]=> string(10) "2017-11-18" [5]=> string(10) "2017-11-18" [6]=> string(10) "2017-11-18" [7]=> string(10) "2017-11-18" } [7]=> array(8) { [0]=> string(10) "94990.0000" [1]=> string(8) "280.0000" [2]=> string(8) "290.0000" [3]=> string(10) "22990.0000" [4]=> string(9) "9990.0000" [5]=> string(9) "9990.0000" [6]=> string(9) "1190.0000" [7]=> string(8) "290.0000" } [8]=> array(8) { [0]=> string(10) "94000.0000" [1]=> string(8) "200.0000" [2]=> string(8) "150.0000" [3]=> string(10) "22000.0000" [4]=> string(9) "9500.0000" [5]=> string(9) "8700.0000" [6]=> string(9) "1050.0000" [7]=> string(8) "250.0000" } [9]=> array(8) { [0]=> string(7) "-1.0422" [1]=> string(8) "-28.5714" [2]=> string(8) "-48.2759" [3]=> string(7) "-4.3062" [4]=> string(7) "-4.9049" [5]=> string(8) "-12.9129" [6]=> string(8) "-11.7647" [7]=> string(8) "-13.7931" } [10]=> array(8) { [0]=> string(9) "-990.0000" [1]=> string(8) "-80.0000" [2]=> string(9) "-140.0000" [3]=> string(9) "-990.0000" [4]=> string(9) "-490.0000" [5]=> string(10) "-1290.0000" [6]=> string(9) "-140.0000" [7]=> string(8) "-40.0000" } [11]=> array(8) { [0]=> string(4) "-990" [1]=> string(4) "-240" [2]=> string(4) "-140" [3]=> string(4) "-990" [4]=> string(4) "-490" [5]=> string(5) "-1290" [6]=> string(4) "-140" [7]=> string(3) "-40" } }
</code>```

答:
If the array you provide as an argument to fromArray() is a simple 1-d array, then it will be treated as a row, with entries for each cell in that row. If you want to write columns using fromArray(), then you need a 2-d array.

```<code>$objPHPExcel->getActiveSheet()->fromArray([$nivelacija], null, 'A1');
</code>```

will write a row for each element of the $nivelacija array in column A

Title: PHPexcel array values to column

Body:
I have a problem filling columns with array values with PHPexcel i got my query results into arrays. Column A,B,C... not rows !

while (($red = pg_fetch_assoc($resultID))) {
$nivelacija[] = $red ['nivelacija'];
$dokument[] = $red ['dokument'];
$sifra[] = $red ['sifra'];
$naziv[] = $red ['naziv'];
$kol[] = $red ['kol'];
$pdv[] = $red ['pdv'];
$datum[] = $red ['datum'];
$stara[] = $red ['stara'];
$nova[] = $red ['nova'];
$marza[] = $red ['marza'];
$razlika[] = $red ['razlika'];
$zaduzenje[] = $red ['zaduzenje'];

    }

I have tried doing it like

    for ($i = 1; $i <= 10; $i++) {
$objPHPExcel->getActiveSheet()->fromArray($nivelacija, null, 'A' . $i);
}

but no success, looks like fromArray function can only target specific cell. So i have tried changing to this

for ($i = 1 , $vrednost=0; $i <= 50; $i++ , $vrednost++ ) {
$objPHPExcel->getActiveSheet()->setCellValue('A' .$i, "$nivelacija[$vrednost]" ); }

but like this I get results in Column A but everywhere it writes Array(0) to Array (49)

I have tested this it works when I write "$nivelacija[0]" it writes value to targeted column.

I have no idea how to get my array values for each array to a diffrent column, all i have managed to do is to export it to a row but that just doesnt do the job for me.

Can i get somehow pg query directly to excel without arrays ? Even so i would like to solve array to column problem.

EDITS:

result of var_dump ($nivelacija);

array(8) { [0]=> string(8) "NMP03945" [1]=> string(8) "NMP03944" [2]=> string(8) "NMP03943" [3]=> string(8) "NMP03942" [4]=> string(8) "NMP03942" [5]=> string(8) "NMP03942" [6]=> string(8) "NMP03941" [7]=> string(8) "NMP03940" }

It has only 8 values cause the date is selected for only 1 day. It suppose to be used monthly withunknown numbers of values

----Added $sve array

$sve = array($nivelacija, $dokument, $sifra, $naziv, $kol, $pdv, $datum, $stara, $nova, $marza, $razlika, $zaduzenje);

result of var_dumping

array(12) { [0]=> array(8) { [0]=> string(8) "NMP03945" [1]=> string(8) "NMP03944" [2]=> string(8) "NMP03943" [3]=> string(8) "NMP03942" [4]=> string(8) "NMP03942" [5]=> string(8) "NMP03942" [6]=> string(8) "NMP03941" [7]=> string(8) "NMP03940" } [1]=> array(8) { [0]=> string(8) "RNB15269" [1]=> string(8) "RNB15266" [2]=> string(8) "RNB15264" [3]=> string(8) "RNB15261" [4]=> string(8) "RNB15261" [5]=> string(8) "RNB15261" [6]=> string(8) "RNB15262" [7]=> string(8) "RNB15255" } [2]=> array(8) { [0]=> string(7) "0670723" [1]=> string(7) "4610602" [2]=> string(7) "4610800" [3]=> string(7) "1011910" [4]=> string(7) "4320350" [5]=> string(7) "0291415" [6]=> string(7) "2631463" [7]=> string(7) "4610513" } [3]=> array(8) { [0]=> string(40) "Gree Viola Profi inverter Wifi klima 18k" [1]=> string(16) "Matrix HDMI 1.5m" [2]=> string(31) "CCP-USB2-AMBM-10 USB Printer 3m" [3]=> string(28) "Green PC G1840/H81/4GB/320GB" [4]=> string(21) "HP LaserJet Pro M102a" [5]=> string(31) "Monitor 19 Philips 193V5LSB2/10" [6]=> string(25) "Maxell speedboat USB 16GB" [7]=> string(20) "PC-186 naponski kabl" } [4]=> array(8) { [0]=> string(1) "1" [1]=> string(1) "3" [2]=> string(1) "1" [3]=> string(1) "1" [4]=> string(1) "1" [5]=> string(1) "1" [6]=> string(1) "1" [7]=> string(1) "1" } [5]=> array(8) { [0]=> string(2) "20" [1]=> string(2) "20" [2]=> string(2) "20" [3]=> string(2) "20" [4]=> string(2) "20" [5]=> string(2) "20" [6]=> string(2) "20" [7]=> string(2) "20" } [6]=> array(8) { [0]=> string(10) "2017-11-18" [1]=> string(10) "2017-11-18" [2]=> string(10) "2017-11-18" [3]=> string(10) "2017-11-18" [4]=> string(10) "2017-11-18" [5]=> string(10) "2017-11-18" [6]=> string(10) "2017-11-18" [7]=> string(10) "2017-11-18" } [7]=> array(8) { [0]=> string(10) "94990.0000" [1]=> string(8) "280.0000" [2]=> string(8) "290.0000" [3]=> string(10) "22990.0000" [4]=> string(9) "9990.0000" [5]=> string(9) "9990.0000" [6]=> string(9) "1190.0000" [7]=> string(8) "290.0000" } [8]=> array(8) { [0]=> string(10) "94000.0000" [1]=> string(8) "200.0000" [2]=> string(8) "150.0000" [3]=> string(10) "22000.0000" [4]=> string(9) "9500.0000" [5]=> string(9) "8700.0000" [6]=> string(9) "1050.0000" [7]=> string(8) "250.0000" } [9]=> array(8) { [0]=> string(7) "-1.0422" [1]=> string(8) "-28.5714" [2]=> string(8) "-48.2759" [3]=> string(7) "-4.3062" [4]=> string(7) "-4.9049" [5]=> string(8) "-12.9129" [6]=> string(8) "-11.7647" [7]=> string(8) "-13.7931" } [10]=> array(8) { [0]=> string(9) "-990.0000" [1]=> string(8) "-80.0000" [2]=> string(9) "-140.0000" [3]=> string(9) "-990.0000" [4]=> string(9) "-490.0000" [5]=> string(10) "-1290.0000" [6]=> string(9) "-140.0000" [7]=> string(8) "-40.0000" } [11]=> array(8) { [0]=> string(4) "-990" [1]=> string(4) "-240" [2]=> string(4) "-140" [3]=> string(4) "-990" [4]=> string(4) "-490" [5]=> string(5) "-1290" [6]=> string(4) "-140" [7]=> string(3) "-40" } }

Body:
If the array you provide as an argument to fromArray() is a simple 1-d array, then it will be treated as a row, with entries for each cell in that row. If you want to write columns using fromArray(), then you need a 2-d array.

$objPHPExcel->getActiveSheet()->fromArray([$nivelacija], null, 'A1');

will write a row for each element of the $nivelacija array in column A


问:
Redirect non-www domain to www, preserving staging
I have two domains, www.example.com and staging.example.com (both hosted on the same box).

I'd like to always redirect example.com to www.example.com, but when I use solutions from other SO threads it breaks the staging domain.

Can someone point me in the right direction?

Thanks!

UPDATE: Does this cover https as well? If not, what do I have to do to get that working?

答:
You need this in your .htaccess file at the root of your directory :

```<code>RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
</code>```

the magic lies in the ^ which indicates that it should only rewrite the url if the adress STARTS by example.com. This leaves staging.example.com out of the loop.

In case you need to do that for HTTPS as well just add the following line to the conditions and tweak it for your need (=on or !=on) :

RewriteCond ${HTTPS} =on

Which gives you :

```<code>RewriteCond ${HTTPS} =on
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
</code>```

Oh and don't forget to put the RewriteEngine on line at the top of your .htaccess file

ContentLicense: CC BY-SA 2.5

Body:
You need this in your .htaccess file at the root of your directory :

RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

the magic lies in the ^ which indicates that it should only rewrite the url if the adress STARTS by example.com. This leaves staging.example.com out of the loop.

In case you need to do that for HTTPS as well just add the following line to the conditions and tweak it for your need (=on or !=on) :

RewriteCond ${HTTPS} =on

Which gives you :

RewriteCond ${HTTPS} =on
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

Oh and don't forget to put the RewriteEngine on line at the top of your .htaccess file


问:
How to call a function with a reference lambda function?
Code:

```<code>typedef void(*callbackType) (int);

callbackType globalCallback;

void setit(callbackType callback) {
  globalCallback = callback;
}

int main() {
  int localVar = 5;
  setit([](int num) {
    std::cout << localVar; // there is an error here
  });
}
</code>```

I need to use localVar in lambda function that i send to setit

I guess i have to use [&]{ }

But how can i do it? How should i declare setit and globalCallback?

答:
There are some problems with the code above.

If you didn't need to capture anything, you could use + with lambda to convert it to a function pointer:

```<code>typedef void(*callbackType)(int);

callbackType globalCallback;

void setit(callbackType callback) {
  globalCallback = callback;
}

int main() {
  setit(+[](int){});
}
</code>```

But this trick works with capturless lambdas only.

One possible solution is to change callbackType and use std::function instead:

```<code>using callbackType = std::function<void(int)>;

callbackType globalCallback;

void setit(callbackType callback) {
  globalCallback = callback;
}

int main() {
    int localVar = 5;

    setit([localVar](int num) {
        std::cout << localVar; // there is an error here
    });
}
</code>```

which works well.

Body:
Code:

typedef void(*callbackType) (int);

callbackType globalCallback;

void setit(callbackType callback) {
  globalCallback = callback;
}

int main() {
  int localVar = 5;
  setit([](int num) {
    std::cout << localVar; // there is an error here
  });
}

I need to use localVar in lambda function that i send to setit

I guess i have to use [&]{ }

But how can i do it? How should i declare setit and globalCallback?

Body:
There are some problems with the code above.

If you didn't need to capture anything, you could use + with lambda to convert it to a function pointer:

typedef void(*callbackType)(int);

callbackType globalCallback;

void setit(callbackType callback) {
  globalCallback = callback;
}

int main() {
  setit(+[](int){});
}

But this trick works with capturless lambdas only.

One possible solution is to change callbackType and use std::function instead:

using callbackType = std::function<void(int)>;

callbackType globalCallback;

void setit(callbackType callback) {
  globalCallback = callback;
}

int main() {
    int localVar = 5;

    setit([localVar](int num) {
        std::cout << localVar; // there is an error here
    });
}

which works well.


问:
Java Generics - method which accept different generic interfaces
Say I have this code:

```<code>IOperation<?> parameter1 = null;
ITotallyDifferentOperation<?> parameter2 = null;

switch (OPERATION_TYPE) {
  case TYPE_1:
    parameter1 = new MyOperation<Type1>();
    parameter2 = new MyTotallyDifferentOperation<Type1>();
    break;
  case TYPE_2:
    parameter1 = new MyOperation<Type2>();
    parameter2 = new MyTotallyDifferentOperation<Type2>();
    break;

...

switch (DB_OPERATION_TYPE) {
  case DB_TYPE_1:
    myMethod(parameter1, parameter2);
    break;
  case DB_TYPE_2:
    myOtherMethod(parameter1, parameter2);
    break;

...
</code>```

The method which accept the two interfaces implemented by MyOperation and MyTotallyDifferentOperation:

```<code>void myMethod(final IOperation<?> operation, final ITotallyDifferentOperation<?> totallyDifferentOperation) {
  operation.processList(totallyDifferentOperation.getList());
}
</code>```

totallyDifferentOperation.getList() returns a List<T> which is equal in type of the List<T> accepted by operation.processList().

This code obviously does not compile.

Are there other patterns to obtain the same result or this code can be corrected?

As requested I posted a bit more of the method. I cannot disclose any further unfortunately, and this is a mockup.

I need this kind of pattern to avoid duplication of code.

答:
Read this Java tutorial about generic method parameters. You can add a type parameter to you method to make sure that the operation and the totallyDifferentOperation are applicable for the same type:

```<code><T> void myMethod(IOperation<T> operation,
                  ITotallyDifferentOperation<T> totallyDifferentOperation)
{
    operation.processList(totallyDifferentOperation.getList());
}
</code>```

This way you move the responsibility to make sure that both parameters are typed the same way to the caller:

```<code>// compiles
myMethod(new MyOperation<Type1>(), new MyTotallyDifferentOperation<Type1>())
// does not compile
myMethod(new MyOperation<Type1>(), new MyTotallyDifferentOperation<Type2>())
</code>```

This is the simplest example. You can use upper and lower bounds to make the restrictions more flexible. This might enable you to mix types as long as they are compatible (imagine an IOperation that can handle any Number input, and different ITotallyDifferentOperations that supply Long, Double, ...). This tutorial explains this.

After you added code, maybe you could have a look at this:

```<code>Operations<?> parameters = null;

switch (OPERATION_TYPE)
{
    case TYPE_1 :
        parameters = new Operations<>(new MyOperation<Type1>(),
                                      new MyTotallyDifferentOperation<Type1>());
        break;
}
switch (DB_OPERATION_TYPE)
{
    case DB_TYPE_1 :
        myMethod(parameters);
        break;
}

static <T> void myMethod(final Operations<T> operations)
{
    operations.operation.processList(operations.totallyDifferentOperation.getList());
}

static class Operations<T>
{
    public final IOperation<T>                 operation;
    public final ITotallyDifferentOperation<T> totallyDifferentOperation;

    public Operations(IOperation<T> operation, ITotallyDifferentOperation<T> totallyDifferentOperation)
    {
        this.operation = operation;
        this.totallyDifferentOperation = totallyDifferentOperation;
    }
}
</code>```

By wrapping the two operations into a typed parameter object you can make sure that they are of the same type. This means of course that your dbOperations need to accept that param object indtead of two parameters seperately.

Body:
Say I have this code:

IOperation<?> parameter1 = null;
ITotallyDifferentOperation<?> parameter2 = null;

switch (OPERATION_TYPE) {
  case TYPE_1:
    parameter1 = new MyOperation<Type1>();
    parameter2 = new MyTotallyDifferentOperation<Type1>();
    break;
  case TYPE_2:
    parameter1 = new MyOperation<Type2>();
    parameter2 = new MyTotallyDifferentOperation<Type2>();
    break;

...

switch (DB_OPERATION_TYPE) {
  case DB_TYPE_1:
    myMethod(parameter1, parameter2);
    break;
  case DB_TYPE_2:
    myOtherMethod(parameter1, parameter2);
    break;

...

The method which accept the two interfaces implemented by MyOperation and MyTotallyDifferentOperation:

void myMethod(final IOperation<?> operation, final ITotallyDifferentOperation<?> totallyDifferentOperation) {
  operation.processList(totallyDifferentOperation.getList());
}

totallyDifferentOperation.getList() returns a List<T> which is equal in type of the List<T> accepted by operation.processList().

This code obviously does not compile.

Are there other patterns to obtain the same result or this code can be corrected?

As requested I posted a bit more of the method. I cannot disclose any further unfortunately, and this is a mockup.

I need this kind of pattern to avoid duplication of code.

Body:
Read this Java tutorial about generic method parameters. You can add a type parameter to you method to make sure that the operation and the totallyDifferentOperation are applicable for the same type:

<T> void myMethod(IOperation<T> operation,
                  ITotallyDifferentOperation<T> totallyDifferentOperation)
{
    operation.processList(totallyDifferentOperation.getList());
}

This way you move the responsibility to make sure that both parameters are typed the same way to the caller:

// compiles
myMethod(new MyOperation<Type1>(), new MyTotallyDifferentOperation<Type1>())
// does not compile
myMethod(new MyOperation<Type1>(), new MyTotallyDifferentOperation<Type2>())

This is the simplest example. You can use upper and lower bounds to make the restrictions more flexible. This might enable you to mix types as long as they are compatible (imagine an IOperation that can handle any Number input, and different ITotallyDifferentOperations that supply Long, Double, ...). This tutorial explains this.

After you added code, maybe you could have a look at this:

Operations<?> parameters = null;

switch (OPERATION_TYPE)
{
    case TYPE_1 :
        parameters = new Operations<>(new MyOperation<Type1>(),
                                      new MyTotallyDifferentOperation<Type1>());
        break;
}
switch (DB_OPERATION_TYPE)
{
    case DB_TYPE_1 :
        myMethod(parameters);
        break;
}

static <T> void myMethod(final Operations<T> operations)
{
    operations.operation.processList(operations.totallyDifferentOperation.getList());
}

static class Operations<T>
{
    public final IOperation<T>                 operation;
    public final ITotallyDifferentOperation<T> totallyDifferentOperation;

    public Operations(IOperation<T> operation, ITotallyDifferentOperation<T> totallyDifferentOperation)
    {
        this.operation = operation;
        this.totallyDifferentOperation = totallyDifferentOperation;
    }
}

By wrapping the two operations into a typed parameter object you can make sure that they are of the same type. This means of course that your dbOperations need to accept that param object indtead of two parameters seperately.


问:
Converting a char to &str
I have a match statement which returns a &str:

```<code>match k {
    SP_KEY_1 => "KEY_1",
    SP_KEY_2 => "KEY_2",
    SP_KEY_3 => "KEY_3",
    SP_KEY_4 => "KEY_4",
    SP_KEY_5 => "KEY_5",
    SP_KEY_6 => "KEY_6",
    _ => (k as char), // I want to convert this to &str
}.as_bytes()
</code>```

I have tried to convert a char to a string first, and then taking a slice of that:

```<code>&(k as char).to_string()[..]
</code>```

But that gave me the lifetime error:

error[E0597]: borrowed value does not live long enough
```

Stating that (k as char).to_string()  is a temporary value, which makes sense as from what I can tell to_string() returns a clone.

I can add .to_string() to every &str literal above to make the return value String, but that seems both ugly (a lot of repeated code), and probably inefficient, as to_string() clones the original string slice.

The specific question is how would I make a char into a &str, but the broader question is that is there a better solution, what is commonly done this situation.

答:
So long as you don't need to return the &str from the function, you can completely avoid heap allocation using char::encode_utf8:

```<code>const SP_KEY_1: u8 = 0;
const SP_KEY_2: u8 = 1;
const SP_KEY_3: u8 = 2;
const SP_KEY_4: u8 = 3;
const SP_KEY_5: u8 = 4;
const SP_KEY_6: u8 = 5;

fn main() {
    let k = 42u8;

    let mut tmp = [0; 4];

    let s = match k {
        SP_KEY_1 => "KEY_1",
        SP_KEY_2 => "KEY_2",
        SP_KEY_3 => "KEY_3",
        SP_KEY_4 => "KEY_4",
        SP_KEY_5 => "KEY_5",
        SP_KEY_6 => "KEY_6",
        _ => (k as char).encode_utf8(&mut tmp),
    };

    println!("{}", s);
}
</code>```

This could be paired with a closure if you needed more control:

```<code>fn adapt<F, B>(k: u8, f: F) -> B
where
    for<'a> F: FnOnce(&'a str) -> B,
{
    let mut tmp = [0; 4];

    let s = match k {
        SP_KEY_1 => "KEY_1",
        SP_KEY_2 => "KEY_2",
        SP_KEY_3 => "KEY_3",
        SP_KEY_4 => "KEY_4",
        SP_KEY_5 => "KEY_5",
        SP_KEY_6 => "KEY_6",
        _ => (k as char).encode_utf8(&mut tmp),
    };

    f(s)
}

fn main() {
    adapt(0, |s| println!("{}", s));
    let owned = adapt(0, |s| s.to_owned());
}
</code>```

Or stored in a struct to provide a little bit of abstraction:

```<code>#[derive(Debug, Default)]
struct Foo {
    tmp: [u8; 4],
}

impl Foo {
    fn adapt(&mut self, k: u8) -> &str {
        match k {
            SP_KEY_1 => "KEY_1",
            SP_KEY_2 => "KEY_2",
            SP_KEY_3 => "KEY_3",
            SP_KEY_4 => "KEY_4",
            SP_KEY_5 => "KEY_5",
            SP_KEY_6 => "KEY_6",
            _ => (k as char).encode_utf8(&mut self.tmp),
        }
    }
}

fn main() {
    let mut foo = Foo::default();
    {
        let s = foo.adapt(0);
    }
    {
        let s = foo.adapt(42);
    }
}
</code>```

Title: Converting a char to &str

Body:
I have a match statement which returns a &str:

match k {
    SP_KEY_1 => "KEY_1",
    SP_KEY_2 => "KEY_2",
    SP_KEY_3 => "KEY_3",
    SP_KEY_4 => "KEY_4",
    SP_KEY_5 => "KEY_5",
    SP_KEY_6 => "KEY_6",
    _ => (k as char), // I want to convert this to &str
}.as_bytes()

I have tried to convert a char to a string first, and then taking a slice of that:

&(k as char).to_string()[..]

But that gave me the lifetime error:

error[E0597]: borrowed value does not live long enough

Stating that (k as char).to_string()  is a temporary value, which makes sense as from what I can tell to_string() returns a clone.

I can add .to_string() to every &str literal above to make the return value String, but that seems both ugly (a lot of repeated code), and probably inefficient, as to_string() clones the original string slice.

The specific question is how would I make a char into a &str, but the broader question is that is there a better solution, what is commonly done this situation.

Body:
So long as you don't need to return the &str from the function, you can completely avoid heap allocation using char::encode_utf8:

const SP_KEY_1: u8 = 0;
const SP_KEY_2: u8 = 1;
const SP_KEY_3: u8 = 2;
const SP_KEY_4: u8 = 3;
const SP_KEY_5: u8 = 4;
const SP_KEY_6: u8 = 5;

fn main() {
    let k = 42u8;

    let mut tmp = [0; 4];

    let s = match k {
        SP_KEY_1 => "KEY_1",
        SP_KEY_2 => "KEY_2",
        SP_KEY_3 => "KEY_3",
        SP_KEY_4 => "KEY_4",
        SP_KEY_5 => "KEY_5",
        SP_KEY_6 => "KEY_6",
        _ => (k as char).encode_utf8(&mut tmp),
    };

    println!("{}", s);
}

This could be paired with a closure if you needed more control:

fn adapt<F, B>(k: u8, f: F) -> B
where
    for<'a> F: FnOnce(&'a str) -> B,
{
    let mut tmp = [0; 4];

    let s = match k {
        SP_KEY_1 => "KEY_1",
        SP_KEY_2 => "KEY_2",
        SP_KEY_3 => "KEY_3",
        SP_KEY_4 => "KEY_4",
        SP_KEY_5 => "KEY_5",
        SP_KEY_6 => "KEY_6",
        _ => (k as char).encode_utf8(&mut tmp),
    };

    f(s)
}

fn main() {
    adapt(0, |s| println!("{}", s));
    let owned = adapt(0, |s| s.to_owned());
}

Or stored in a struct to provide a little bit of abstraction:

#[derive(Debug, Default)]
struct Foo {
    tmp: [u8; 4],
}

impl Foo {
    fn adapt(&mut self, k: u8) -> &str {
        match k {
            SP_KEY_1 => "KEY_1",
            SP_KEY_2 => "KEY_2",
            SP_KEY_3 => "KEY_3",
            SP_KEY_4 => "KEY_4",
            SP_KEY_5 => "KEY_5",
            SP_KEY_6 => "KEY_6",
            _ => (k as char).encode_utf8(&mut self.tmp),
        }
    }
}

fn main() {
    let mut foo = Foo::default();
    {
        let s = foo.adapt(0);
    }
    {
        let s = foo.adapt(42);
    }
}


问:
SQL Function not working the way I want
I wrote these 2 functions:

```<code>USE muziekdatabase
GO
CREATE FUNCTION fnSpecNivAantal
    (
        @Niveau as char(1)
    )

RETURNS char(1)
AS

BEGIN

    DECLARE @Aantal AS int

    IF @Niveau = 'A'
    SET @Aantal = (SELECT COUNT(*) FROM STUK WHERE niveaucode = 'A')

    ELSE IF @Niveau = 'B'
    SET @Aantal = (SELECT COUNT(*) FROM STUK WHERE niveaucode = 'B')

    ELSE IF @Niveau = 'C'
    SET @Aantal = (SELECT COUNT(*) FROM STUK WHERE niveaucode = 'C')

RETURN @Aantal

END

USE muziekdatabase
GO

ALTER FUNCTION fnHoogsteNummer
    (
        @EersteNummer as numeric,
        @TweedeNummer as numeric
    )
RETURNS numeric
AS
BEGIN

    DECLARE @HoogsteNummer as VARCHAR(MAX)

    IF MAX(@Eerstenummer) > MAX(@TweedeNummer)
    SET @HoogsteNummer = @EersteNummer
    ELSE IF
    MAX(@Tweedenummer) > MAX(@Eerstenummer)
    SET @HoogsteNummer = @TweedeNummer
    ELSE IF
    @EersteNummer = @TweedeNummer
    SET @HoogsteNummer = 'Nummers zijn gelijk'
    ELSE
    SET @HoogsteNummer = 'Er is iets fout gegaan'

    RETURN @HoogsteNummer
END
</code>```

Now they pretty much work like they should. But there's one thing that's not quite right. When I insert a value into my function, the outcome is a whole list with the same answer. Like 10 rows with just a 3, where it only should be 1 row with the number 3. I know I can use DISTINCT, but I think something is wrong with the function. I tried to use CASE / WHEN but that's not working either..

答:
```<code>CREATE FUNCTION fnSpecNivAantal
(
 @Niveau as char(1)
)
RETURNS INT  --<-- since you are returning count use INT variable not char
AS
BEGIN

    DECLARE @Aantal AS int;

    IF (@Niveau IN ('A' , 'B', 'C'))
     BEGIN
       SELECT @Aantal = COUNT(*)
       FROM STUK WHERE niveaucode = @Niveau
     END

RETURN @Aantal

END
</code>```

<p>And sorry cannot make any sense of your second function. </p>

Title: SQL Function not working the way I want

Body:
I wrote these 2 functions:

USE muziekdatabase
GO
CREATE FUNCTION fnSpecNivAantal
    (
        @Niveau as char(1)
    )

RETURNS char(1)
AS

BEGIN

    DECLARE @Aantal AS int

    IF @Niveau = 'A'
    SET @Aantal = (SELECT COUNT(*) FROM STUK WHERE niveaucode = 'A')

    ELSE IF @Niveau = 'B'
    SET @Aantal = (SELECT COUNT(*) FROM STUK WHERE niveaucode = 'B')

    ELSE IF @Niveau = 'C'
    SET @Aantal = (SELECT COUNT(*) FROM STUK WHERE niveaucode = 'C')

RETURN @Aantal

END

USE muziekdatabase
GO

ALTER FUNCTION fnHoogsteNummer
    (
        @EersteNummer as numeric,
        @TweedeNummer as numeric
    )
RETURNS numeric
AS
BEGIN

    DECLARE @HoogsteNummer as VARCHAR(MAX)

    IF MAX(@Eerstenummer) > MAX(@TweedeNummer)
    SET @HoogsteNummer = @EersteNummer
    ELSE IF
    MAX(@Tweedenummer) > MAX(@Eerstenummer)
    SET @HoogsteNummer = @TweedeNummer
    ELSE IF
    @EersteNummer = @TweedeNummer
    SET @HoogsteNummer = 'Nummers zijn gelijk'
    ELSE
    SET @HoogsteNummer = 'Er is iets fout gegaan'

    RETURN @HoogsteNummer
END

Now they pretty much work like they should. But there's one thing that's not quite right. When I insert a value into my function, the outcome is a whole list with the same answer. Like 10 rows with just a 3, where it only should be 1 row with the number 3. I know I can use DISTINCT, but I think something is wrong with the function. I tried to use CASE / WHEN but that's not working either..

Body:
CREATE FUNCTION fnSpecNivAantal
(
 @Niveau as char(1)
)
RETURNS INT  --<-- since you are returning count use INT variable not char
AS
BEGIN

    DECLARE @Aantal AS int;

    IF (@Niveau IN ('A' , 'B', 'C'))
     BEGIN
       SELECT @Aantal = COUNT(*)
       FROM STUK WHERE niveaucode = @Niveau
     END

RETURN @Aantal

END

And sorry cannot make any sense of your second function.


问:
How to find evenly divisible values in array javascript?
It sounds like the goal is to find the only two numbers in each row where one evenly divides the other - that is, where the result of the division operation is a whole number. They would like you to find those numbers on each line, divide them, and add up each line's result.

For example, given the following spreadsheet:

[5, 9, 2, 8]

[9, 4, 7, 3]

[3, 8, 6, 5]

In the first row, the only two numbers that evenly divide are 8 and 2; the result of this division is 4.
In the second row, the two numbers are 9 and 3; the result is 3.
In the third row, the result is 2.
In this example, the sum of the results would be 4 + 3 + 2 = 9.

Find the evenly divisible values in next array:

[1224, 926, 1380, 688, 845, 109, 118, 88, 1275, 1306, 91, 796, 102, 1361]
[1928, 2097,138, 1824, 198, 117, 1532, 2000, 1478 ,539, 1982]

how to use for loop or reduce in this case?

https://codepen.io/marinashumeyko/pen/EbreoJ?editors=1011

答:
Just use filter and modulo %

```<code>const input =  [1224, 926, 1380, 688, 845, 109, 118, 88, 1275, 1306, 91, 796, 102, 1361]
const result = input.filter(val => val %2 === 0);
console.log(result);
</code>```

Well it looks like some scope-creep since i first read this. If you want divisibles between values in the array, then you can do:

```<code>const input =  [1224, 926, 1380, 688, 6, 3, 845, 109, 118, 88, 1275, 1306, 91, 796, 102, 1361]
const result = input.reduce((acc, val) => {
  const divisibles = input.filter(v => val !== v && val % v === 0).map(v => val / v);
  return [...acc, ...divisibles];
}, []);
console.log(result);
</code>```

You now appear to be using an array of arrays as input; if that is the case then you will have to do a further level of nesting of the above single array example - but it gives you the idea.

Body:
Just use filter and modulo %

const input =  [1224, 926, 1380, 688, 845, 109, 118, 88, 1275, 1306, 91, 796, 102, 1361]
const result = input.filter(val => val %2 === 0);
console.log(result);

Well it looks like some scope-creep since i first read this. If you want divisibles between values in the array, then you can do:

const input =  [1224, 926, 1380, 688, 6, 3, 845, 109, 118, 88, 1275, 1306, 91, 796, 102, 1361]
const result = input.reduce((acc, val) => {
  const divisibles = input.filter(v => val !== v && val % v === 0).map(v => val / v);
  return [...acc, ...divisibles];
}, []);
console.log(result);

You now appear to be using an array of arrays as input; if that is the case then you will have to do a further level of nesting of the above single array example - but it gives you the idea.


问:
executing bash loop while command is running
I want to build a bash script that executes a command and in the meanwhile performs other stuff, with the possibility of killing the command if the script is killed. Say, executes a cp of a large file and in the meanwhile prints the elapsed time since copy started, but if the script is killed it kills also the copy.
I don't want to use rsync, for 2 reasons: 1) is slow and 2) I want to learn how to do it, it could be useful.
I tried this:

```<code>until cp SOURCE DEST
do
#evaluates time, stuff, commands, file dimensions, not important now
#and echoes something
done
</code>```

but it doesn't execute the do - done block, as it is waiting that the copy ends. Could you please suggest something?

答:
here is the simplest way to do that using ps -p :

```<code>[command_1_to_execute] &
pid=$!

while ps -p $pid &>/dev/null; do
    [command_2_to_be_executed meanwhile command_1 is running]
    sleep 10
done
</code>```

This will run every 10 seconds the command_2 if the command_1 is still running in background .

hope this will help you :)

Body:
I want to build a bash script that executes a command and in the meanwhile performs other stuff, with the possibility of killing the command if the script is killed. Say, executes a cp of a large file and in the meanwhile prints the elapsed time since copy started, but if the script is killed it kills also the copy.
I don't want to use rsync, for 2 reasons: 1) is slow and 2) I want to learn how to do it, it could be useful.
I tried this:

until cp SOURCE DEST
do
#evaluates time, stuff, commands, file dimensions, not important now
#and echoes something
done

but it doesn't execute the do - done block, as it is waiting that the copy ends. Could you please suggest something?

Body:
here is the simplest way to do that using ps -p :

[command_1_to_execute] &
pid=$!

while ps -p $pid &>/dev/null; do
    [command_2_to_be_executed meanwhile command_1 is running]
    sleep 10
done

This will run every 10 seconds the command_2 if the command_1 is still running in background .

hope this will help you :)


问:
Fetching and Posting data to a rest microservice
I am trying to implement HTTP services GET and POST with my Rest micro service created.

I am able to fetch data from my Rest micro service.

But I am unable make a POST request.

Below shown is my code for Rest micro service

WebController.java

```<code>package com.central.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.central.model.Users;
import com.central.repository.UsersRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@RestController
public class WebController {
    private static final String NULL = null;
    @Autowired
    UsersRepository userRepo;

    @CrossOrigin(origins = "http://localhost:4200")
    @RequestMapping("/checkUsers")
    public String checkLogin() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        List<Users> useObj = (List<Users>) userRepo.findAll();
        return (mapper.writeValueAsString(useObj));
    }

    @CrossOrigin(origins = "http://localhost:4200")
    @RequestMapping(value = "/checkByCredential", method = RequestMethod.POST)
    public String checkLoginByName(@RequestBody Users user) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        Users useObj1 = userRepo.findByUsernameAndPassword(user.username, user.password);
        return (mapper.writeValueAsString(useObj1));
    }
}
</code>```

app.module.ts

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { BasicService } from './basic.service';

@NgModule({
  declarations  : [ AppComponent],
  imports       : [BrowserModule,HttpModule,FormsModule ],
  providers     : [BasicService],
  bootstrap     : [AppComponent]
})

export class AppModule { }
</code>```

app.component.ts

```<code>import { Component } from '@angular/core';
import { BasicService } from './basic.service';

@Component({
  selector: 'app-root',
  template: `<h1>{{ title }}</h1>
                <div style="margin-left:50px; height: 200px; overflow: auto;">
                 <table>
                     <tr><td>Username</td>  <td>Password</td></tr>
                     <tr *ngFor= " let item of data">
                 <td>{{ item.username }}</td>  <td>{{ item.password }}</td>
                 </tr>
                 </table>
                </div>

      <h2>Login</h2>
        <form role="form">
          <div ng-control-group="credentials">
            <label for="username">Username</label>
            <input
              type="text"
              #username
              id="username"
              ng-control="username"
              required>

            <label for="password">Password</label>
            <input
              type="password"
              #password
              id="password"
              ng-control="password"
              required>
          </div>
          <button (click)="checkByCredential(username,password)">Login</button>
        </form>`
})

export class AppComponent {
  title: string;
  data: any;

  constructor(private MyService: BasicService) {
    this.title = "Angular Service";

    this.MyService.GetUsers()
      .subscribe(users => { this.data = users });
  }

  checkByCredential(username: string, password: string) {
    this.MyService.checkByCredential(username, password).subscribe(users => { this.data = users });
  }
}
</code>```

basic.service.ts

```<code>import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class BasicService {
  constructor(private http: Http) { }

  GetUsers() {
    return this.http.get('http://localhost:8080/checkUsers')
      .map(result => result.json());
  }

  checkByCredential(username: string, password: string) {
    const user = { username: username, password: password };
    return this.http
      .post('http://localhost:8080/checkByCredential', user)
      .map(result => result.json());
  }
}
</code>```

And when I am submitting data via my form I am getting this error in my console as shown below in the images

But with my Postman when I am trying to make Post request with username and password ,I am able to get back the data as shown below in the images

can any body please help me out to resolve the Post request in angular 2

updated screen shots after updation in my framework

答:
You're getting a 400 from your service because you aren't acually sending a value to your server.

this line:

```<code><button (click)="checkByCredential(username,password)">Login</button>
</code>```

is the problematic one.  Those 2 variables are template variable, which refer to the actual input element, not the value of the input element, so you need to do this:

```<code><button (click)="checkByCredential(username.value,password.value)">Login</button>
</code>```

and this should work at that point. Though I'd recommend switching to reactive forms or ngModel as a longer term solution.

As for debugging this, using console.log, the network tab on chrome, and in this case, even the error message generated by your server framework all would've shown you exactly what was going wrong right away.

Something like this:

```<code>checkByCredential(username: string, password: string) {
    console.log(username, password);
    this.MyService.checkByCredential(username, password).subscribe(users => { this.data = users });
}
</code>```

would've immediately told you that you weren't getting the expected value.

As well, on the network tab in chrome, you can view the actual request body you're sending and make sure it isn't getting malformed.

Finally, if you look closely at the 400 error you're getting back (btw, 400 always means bad user input), it has a specific error message that probably gives you a clue as to what's going on.

Your secondary error is because you're trying to use ngFor to iterate an object, which is not allowed, you can only use ngFor with arrays.  Your real problem is that this is poorly designed and you try to show a master list and a single detail item in the same element.  You should redesign your page so that your "checked user" and your "user list" are different display elements.  But for testing, you can log to the console like this:

```<code>this.MyService.checkByCredential(username, password).subscribe(users => console.log(users));
</code>```

Body:
I am trying to implement HTTP services GET and POST with my Rest micro service created.

I am able to fetch data from my Rest micro service.

But I am unable make a POST request.

Below shown is my code for Rest micro service

WebController.java

package com.central.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.central.model.Users;
import com.central.repository.UsersRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@RestController
public class WebController {
    private static final String NULL = null;
    @Autowired
    UsersRepository userRepo;

    @CrossOrigin(origins = "http://localhost:4200")
    @RequestMapping("/checkUsers")
    public String checkLogin() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        List<Users> useObj = (List<Users>) userRepo.findAll();
        return (mapper.writeValueAsString(useObj));
    }

    @CrossOrigin(origins = "http://localhost:4200")
    @RequestMapping(value = "/checkByCredential", method = RequestMethod.POST)
    public String checkLoginByName(@RequestBody Users user) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        Users useObj1 = userRepo.findByUsernameAndPassword(user.username, user.password);
        return (mapper.writeValueAsString(useObj1));
    }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { HttpModule } from '@angular/http';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { BasicService } from './basic.service';

@NgModule({
  declarations  : [ AppComponent],
  imports       : [BrowserModule,HttpModule,FormsModule ],
  providers     : [BasicService],
  bootstrap     : [AppComponent]
})

export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import { BasicService } from './basic.service';

@Component({
  selector: 'app-root',
  template: `
{{ title }}

Username	  Password

                 {{ item.username }}	  {{ item.password }}

Login

        <form role="form">

            Username
            <input
              type="text"
              #username
              id="username"
              ng-control="username"
              required>

            Password
            <input
              type="password"
              #password
              id="password"
              ng-control="password"
              required>

          <button (click)="checkByCredential(username,password)">Login</button>
        </form>`
})

export class AppComponent {
  title: string;
  data: any;

  constructor(private MyService: BasicService) {
    this.title = "Angular Service";

    this.MyService.GetUsers()
      .subscribe(users => { this.data = users });
  }

  checkByCredential(username: string, password: string) {
    this.MyService.checkByCredential(username, password).subscribe(users => { this.data = users });
  }
}

basic.service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class BasicService {
  constructor(private http: Http) { }

  GetUsers() {
    return this.http.get('http://localhost:8080/checkUsers')
      .map(result => result.json());
  }

  checkByCredential(username: string, password: string) {
    const user = { username: username, password: password };
    return this.http
      .post('http://localhost:8080/checkByCredential', user)
      .map(result => result.json());
  }
}

And when I am submitting data via my form I am getting this error in my console as shown below in the images

But with my Postman when I am trying to make Post request with username and password ,I am able to get back the data as shown below in the images

can any body please help me out to resolve the Post request in angular 2

updated screen shots after updation in my framework

Body:
You're getting a 400 from your service because you aren't acually sending a value to your server.

this line:

<button (click)="checkByCredential(username,password)">Login</button>

is the problematic one.  Those 2 variables are template variable, which refer to the actual input element, not the value of the input element, so you need to do this:

<button (click)="checkByCredential(username.value,password.value)">Login</button>

and this should work at that point. Though I'd recommend switching to reactive forms or ngModel as a longer term solution.

As for debugging this, using console.log, the network tab on chrome, and in this case, even the error message generated by your server framework all would've shown you exactly what was going wrong right away.

Something like this:

checkByCredential(username: string, password: string) {
    console.log(username, password);
    this.MyService.checkByCredential(username, password).subscribe(users => { this.data = users });
}

would've immediately told you that you weren't getting the expected value.

As well, on the network tab in chrome, you can view the actual request body you're sending and make sure it isn't getting malformed.

Finally, if you look closely at the 400 error you're getting back (btw, 400 always means bad user input), it has a specific error message that probably gives you a clue as to what's going on.

Your secondary error is because you're trying to use ngFor to iterate an object, which is not allowed, you can only use ngFor with arrays.  Your real problem is that this is poorly designed and you try to show a master list and a single detail item in the same element.  You should redesign your page so that your "checked user" and your "user list" are different display elements.  But for testing, you can log to the console like this:

this.MyService.checkByCredential(username, password).subscribe(users => console.log(users));


问:
Web scraping multiple sites in python
I signed up to this website just to ask this question as I have been searching for hours over multiple days and haven't found anything.
I am trying to, within 10 seconds, scrape the 2-3 characters from 5 websites, combine them, and paste them into a box.
I have a rough idea of what I would need, but no idea how to go about this.
I believe I want to assign variables the scraped contents from a certain website, and then get it to print the combination of these variables for me to copy and paste.
I'm not an expert by any means in Python, so if possible, a copy/pasteable script would be great.
The websites are:
https://assess.joincyberdiscovery.com/challenge-files/clock-pt1?verify=BY%2F8lhw%2BtbBgvOMDiHeB5A%3D%3D
https://assess.joincyberdiscovery.com/challenge-files/clock-pt2?verify=BY%2F8lhw%2BtbBgvOMDiHeB5A%3D%3D
https://assess.joincyberdiscovery.com/challenge-files/clock-pt3?verify=BY%2F8lhw%2BtbBgvOMDiHeB5A%3D%3D
https://assess.joincyberdiscovery.com/challenge-files/clock-pt4?verify=BY%2F8lhw%2BtbBgvOMDiHeB5A%3D%3D
https://assess.joincyberdiscovery.com/challenge-files/clock-pt5?verify=BY%2F8lhw%2BtbBgvOMDiHeB5A%3D%3D
Keeping this up now only because I cannot take it down. Thank you to those who have helped, I hope this helps someone else.
Sorry for being dumb</p>

答:
I have done something very similar with just as poor results at the end. I did, however, leave this running for a while and notice that the clock follow a pattern. Some time ago the clock read all as "aaaaaaaaaaaaaaa"  then "aBaa1aafaa2aa3a" and "aDaafaaHaajaala". I'm going to wait for a full list and try suggesting the next clock sequence in the final URL. I'll get back to you if this works, just something to think about.

Also for help importing moduals I suggest :
https://programminghistorian.org/lessons/installing-python-modules-pip
&
https://docs.python.org/3/installing/index.html

```<code>import requests
abc = ""
while 1 == 1 :
    page1 = requests.get('your first link')
    page2 = requests.get('your second link')
    page3 = requests.get('your thrid link')
    page4 = requests.get('your fourth link')
    page5 = requests.get('your fith link')
    text = page1.text+page2.text+page3.text+page4.text+page5.text

    # abc1 = "the verify link except clock pts is replaced with "+"text>" so the end looks like this :string=<"+text+">"
    abc1 = text
    if abc1 != abc:
       print (abc1)
       abc = abc1
</code>```

Edit
The clock runs in 15-minute cycles with 90 codes altogether Im not sure how this helps as of yet but just posting ideas. I had to make some changes to get the codes to output cleanly and here is my improved version (this is very messy sorry):

```<code>import requests
abc = ""
page1 = requests.get('your first link')
page2 = requests.get('your second link')
page3 = requests.get('your thrid link')
page4 = requests.get('your fourth link')
page5 = requests.get('your fith link')
while 1 == 1 :
    page12 = requests.get('your first link')
    page22 = requests.get('your second link')
    page32 = requests.get('your thrid link')
    page42 = requests.get('your fourth link')
    page52 = requests.get('your fith link')
    if page1.text != page12.text and page2.text != page22.text and page3.text != page32.text and page4.text != page42.text and page5.text != page52.text:

        text = page12.text+page22.text+page32.text+page42.text+page52.text
        abc1 = text
        # abc1 = * your url for verification   with * string=<"+text+">"
        if abc1 != abc:
            print (abc1)
            abc = abc1
            page1 = page12
            page2 = page22
            page3 = page32
            page4 = page42
            page5 = page52
</code>```

Final edit
I had sepnt so long going down the path of figuring out how that made the tak and doing way too much work. When Submitting the final url dont incluede your solutin as a repalcement for the  section and NOT inside the <> so yours should likehttps://assess.joincyberdiscovery.com/challenge-files/get-flag?verify=*this is an identifiere*&string=*The string you get*

Title: Web scraping multiple sites in python

Body:
I have done something very similar with just as poor results at the end. I did, however, leave this running for a while and notice that the clock follow a pattern. Some time ago the clock read all as "aaaaaaaaaaaaaaa"  then "aBaa1aafaa2aa3a" and "aDaafaaHaajaala". I'm going to wait for a full list and try suggesting the next clock sequence in the final URL. I'll get back to you if this works, just something to think about.

Also for help importing moduals I suggest :
https://programminghistorian.org/lessons/installing-python-modules-pip
&
https://docs.python.org/3/installing/index.html

import requests
abc = ""
while 1 == 1 :
    page1 = requests.get('your first link')
    page2 = requests.get('your second link')
    page3 = requests.get('your thrid link')
    page4 = requests.get('your fourth link')
    page5 = requests.get('your fith link')
    text = page1.text+page2.text+page3.text+page4.text+page5.text

    # abc1 = "the verify link except clock pts is replaced with "+"text>" so the end looks like this :string=<"+text+">"
    abc1 = text
    if abc1 != abc:
       print (abc1)
       abc = abc1

Edit
The clock runs in 15-minute cycles with 90 codes altogether Im not sure how this helps as of yet but just posting ideas. I had to make some changes to get the codes to output cleanly and here is my improved version (this is very messy sorry):

import requests
abc = ""
page1 = requests.get('your first link')
page2 = requests.get('your second link')
page3 = requests.get('your thrid link')
page4 = requests.get('your fourth link')
page5 = requests.get('your fith link')
while 1 == 1 :
    page12 = requests.get('your first link')
    page22 = requests.get('your second link')
    page32 = requests.get('your thrid link')
    page42 = requests.get('your fourth link')
    page52 = requests.get('your fith link')
    if page1.text != page12.text and page2.text != page22.text and page3.text != page32.text and page4.text != page42.text and page5.text != page52.text:

        text = page12.text+page22.text+page32.text+page42.text+page52.text
        abc1 = text
        # abc1 = * your url for verification   with * string=<"+text+">"
        if abc1 != abc:
            print (abc1)
            abc = abc1
            page1 = page12
            page2 = page22
            page3 = page32
            page4 = page42
            page5 = page52

Final edit
I had sepnt so long going down the path of figuring out how that made the tak and doing way too much work. When Submitting the final url dont incluede your solutin as a repalcement for the  section and NOT inside the <> so yours should likehttps://assess.joincyberdiscovery.com/challenge-files/get-flag?verify=*this is an identifiere*&string=*The string you get*


问:
Overlay on top of tbody
I am trying to create a loading overlay on top of tbody (and only tbody). My current solution is to add tr as the last element of tbody and set it as position: absolute, and setting tbody as position: relative.

table {
  width: 100%;
}

tbody {
  position: relative;
}

.overlay {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(200, 200, 200, 0.7);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <tr>Label</tr>
  </thead>
  <tbody>
    <tr><td>Data</td></tr>
    <tr><td>Data</td></tr>
    <tr class="overlay">
      <td>My overlay</td>
    </tr>
  </tbody>
</table></code>```

Expected behavior is that an overlay covers tbody, but not thead. Also this overlay is supposed to contain some content (f.e. refresh button) so covering every td is not an option.

My solution works perfectly in Firefox, but not webkit. Webkit somehow ignores position: relative on tbody tag and thus the overlay covers the whole table and more.

RESOLVED
I have managed to make this approach work by adding display: table on tbody

答:
you have to remove the position relative on tbody and out it on table instead.

table {
  width: 100%;
  position: relative;
}

.overlay {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(200, 200, 200, 0.7);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <thead>
    <tr>Label</tr>
  </thead>
  <tbody>
    <tr><td>Data</td></tr>
    <tr><td>Data</td></tr>
    <tr class="overlay">
      <td><div>My overlay</div></td>
    </tr>
  </tbody>
</table></code>```

Title: Overlay on top of tbody

Body:
I am trying to create a loading overlay on top of tbody (and only tbody). My current solution is to add tr as the last element of tbody and set it as position: absolute, and setting tbody as position: relative.

table {
  width: 100%;
}

tbody {
  position: relative;
}

.overlay {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(200, 200, 200, 0.7);
}

Label

Data

Data

      My overlay

Expected behavior is that an overlay covers tbody, but not thead. Also this overlay is supposed to contain some content (f.e. refresh button) so covering every td is not an option.

My solution works perfectly in Firefox, but not webkit. Webkit somehow ignores position: relative on tbody tag and thus the overlay covers the whole table and more.

RESOLVED
I have managed to make this approach work by adding display: table on tbody

Body:
you have to remove the position relative on tbody and out it on table instead.

table {
  width: 100%;
  position: relative;
}

.overlay {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(200, 200, 200, 0.7);
}

<table>
  <thead>
    <tr>Label</tr>
  </thead>
  <tbody>
    <tr><td>Data</td></tr>
    <tr><td>Data</td></tr>
    <tr class="overlay">
      <td><div>My overlay</div></td>
    </tr>
  </tbody>
</table>


问:
Many similar resources in REST API
I’m developing an API for multimedia service. In database I have media table which stores different media (movies, music, series etc). There’re two types of users: admins and users.

Users can access media using different endpoints:

/movies

/cartoons

/music

/series

/seasons

/episodes

etc.

Each endpoint returns only data specific for media type. Each endpoint has specific search arguments.

API for admins will not be public. Is it normal create single endpoint to control media types? For example, I can create /media endpoint which will be used to CRUD different media types.

Should I separate API for admins and API for users in different projects?

How should I handle situations when resource has different fields for admins and users?

答:
How should I handle situations when resource has different fields for admins and users?

Should I separate API for admins and API for users in different projects?

Probably.  It may help to keep in mind that resources "adapt" your domain model for the web -- they are an integration concern.

The web is not your domain, it's a document management system.  All the HTTP verbs apply to the document management domain. URIs do NOT map onto domain objects - that violates encapsulation.  Work (ex: issuing commands to the domain model) is a side effect of managing resources.  In other words, the resources are part of the anti-corruption layer.  You should expect to have many many more resources in your integration domain than you do business objects in your business domain -- Jim Webber

Title: Many similar resources in REST API


问:
local drive audio use to codeigniter
I use codeigniter and stored a lot of audio files on my local drive.

C:\XtendLogger\Waves\20171129 is my audio file path to the audio files i want to use. Therefore I tried the following code, but it doesn't work:

```<code><audio src="C:\XtendLogger\Waves\20171129\Karuthavanlaam Galeejaam.mp3'" preload="auto" type="audio/mpeg" controls></audio>
</code>```

I don't want store this audio file in my codeigniter assets folder.

答:
You can simply play them using the audio class of javascript as bwlow:</p>

```<code>var audio = new Audio('C:\XtendLogger\Waves\file_name');
audio.play();
</code>```

Title: local drive audio use to codeigniter

Body:
I use codeigniter and stored a lot of audio files on my local drive.

C:\XtendLogger\Waves\20171129 is my audio file path to the audio files i want to use. Therefore I tried the following code, but it doesn't work:

<audio src="C:\XtendLogger\Waves\20171129\Karuthavanlaam Galeejaam.mp3'" preload="auto" type="audio/mpeg" controls></audio>

I don't want store this audio file in my codeigniter assets folder.

Body:
You can simply play them using the audio class of javascript as bwlow:

var audio = new Audio('C:\XtendLogger\Waves\file_name');
audio.play();


问:
Angular 4 search in two lists
I have started to develop a new app,trying to use angular in my app,however I am new and I need some orientation.

```<code> <form id="filter">
   <label>Searching for tel.no</label>
      <input type="text" ng-model="term" />
    </form>

    <ul *ngFor="let hero of listA |filter:term">
    <div class="single-hero">
    {{hero.price}}
    </div>
    </ul>
</code>```

filter.pipe

```<code>if(term===undefined) return listA;
    return listA.filter(function(hero){
        return hero.prefix.includes(term));
    })
</code>```

Currently it gives me term is not defined

```<code>export class AppComponent {
li = []; lu=[]
</code>```

Help would be appriciated

答:
You can use indexOF

```<code>export class MyFilter implements PipeTransform {

    transform(items: any[], term: any[]): any {
      if (!term)
        return items;
      return items.filter(item => item.prefix.indexOf(term) > -1);
    }
}
</code>```

DEMO

Title: Angular 4 search in two lists

Body:
I have started to develop a new app,trying to use angular in my app,however I am new and I need some orientation.

 <form id="filter">
   Searching for tel.no
      <input type="text" ng-model="term" />
    </form>

    {{hero.price}}

filter.pipe

if(term===undefined) return listA;
    return listA.filter(function(hero){
        return hero.prefix.includes(term));
    })

Currently it gives me term is not defined

export class AppComponent {
li = []; lu=[]

Help would be appriciated

Body:
You can use indexOF

export class MyFilter implements PipeTransform {

    transform(items: any[], term: any[]): any {
      if (!term)
        return items;
      return items.filter(item => item.prefix.indexOf(term) > -1);
    }
}

DEMO


问:
How to pass custom argument in inern 4
I have been deeveloping intern automation test from my product. I was using intern version 3 for this. But since intern's version 4 have arrived , I was trying to get familiar with it. Now my question is how to pass custom argument to intern 4. I intern 3 i used to pass it through start command like this

```<code>node_modules/intern/runner.js config=/Automation/intern -leaveRemoteOpen arg1=arg1 arg2=arg2
</code>```

and catching those argument using inter.args.arg1.

But since in intern 4 I'm starting test using npm test command I'm unable to figure out how to pass custom argument and how to catch it in code since intern 4 uses typescript.

答:
Intern 4 will accept arbitrary config arguments just like Intern 3 did; they're just accessed a bit differently. In Intern 4 you use the intern.config object rather than intern.args. For example, with the command line:

```<code>$ npx intern foo=bar
</code>```

a JS test could access the argument foo:

```<code>'some test'() {
    const foo = intern.config.foo;
}
</code>```

Assuming you're using TypeScript, you'll need to cast intern.config to any to get at custom arguments:

```<code>'some test'() {
    const foo = (<any>intern.config).foo;
}
</code>```

Title: How to pass custom argument in inern 4

Body:
I have been deeveloping intern automation test from my product. I was using intern version 3 for this. But since intern's version 4 have arrived , I was trying to get familiar with it. Now my question is how to pass custom argument to intern 4. I intern 3 i used to pass it through start command like this

node_modules/intern/runner.js config=/Automation/intern -leaveRemoteOpen arg1=arg1 arg2=arg2

and catching those argument using inter.args.arg1.

But since in intern 4 I'm starting test using npm test command I'm unable to figure out how to pass custom argument and how to catch it in code since intern 4 uses typescript.

Body:
Intern 4 will accept arbitrary config arguments just like Intern 3 did; they're just accessed a bit differently. In Intern 4 you use the intern.config object rather than intern.args. For example, with the command line:

$ npx intern foo=bar

a JS test could access the argument foo:

'some test'() {
    const foo = intern.config.foo;
}

Assuming you're using TypeScript, you'll need to cast intern.config to any to get at custom arguments:

'some test'() {
    const foo = (<any>intern.config).foo;
}


问:
Prevent Page from reloading after AJAX PUT Request
I need to prevent my page from reloading after an Ajax PUT Request.

Basically i have a PUT request to update my database which is fired from a button click, on success of this i want to call another function which is an ajax GET, to reload the data i have just updated, However when doing this, i hit the controller method and get the new list of data, but the page reloads to default and does nothing with my new list

Ajax PUT

```<code>function SendDeleteToController(checkid) {
    $.ajax({
        type: "PUT",
        url: '@Url.Action("PutCheck", "Admin")',
        contentType: "application/json; charset=utf-8",
        datatype: JSON,
        data: JSON.stringify({ methodParam: checkid }),
        success: function () {
            GetListofChecks();
        },
        error: function () {
            alert("error");
        }
</code>```

AJAX GET

```<code>function GetListofChecks() {
    var department = $('#department').val();
    var process = $('#process').val();

    $.ajax({
        type: 'GET',
        url: '@Url.Action("GetListofChecks", "Admin")',
        contentType: "application/json; charset=utf-8",
        datatype: JSON,
        data: { "Department": department, "Process": process },
        success: function (result) {
            $("#mainData").empty();

            $.each(JSON.parse(result),
                function (i, item) {
                    var row = i + 1;
                    $("#mainData").append()
        },
        error: function (result) {
            alert(result);
        }
    });
}
</code>```

controller that returns list of new data

```<code>public JsonResult GetListofChecks(string department, string process)
{
    var listofChecks = new List<Check>();

    listofChecks = AdminModel.GetListofchecks(department, process);

    var json = new JavaScriptSerializer().Serialize(listofChecks);
    return Json(json, JsonRequestBehavior.AllowGet);
}
</code>```

答:
You dont need to use another request (GET) to retrieve the data, just return it in your controller after you delete the item, the callback function will get a response object for use in your success/error callback functions

Try this (comments in code):

```<code>function SendDeleteToController(checkid){
  $.ajax({
      type: "PUT",
      url: '@Url.Action("PutCheck", "Admin")',
      contentType: "application/json; charset=utf-8",
      datatype: JSON,
      data: JSON.stringify({
        methodParam: checkid
      }),
      success: function(result) {
        //your request will return the json object for use in your callback function
        //something like below, though I dont know what your JSON result looks like
        $('body').append(result.id);
      },
      error: function(result) {
        alert("error " + result);
  });
});
</code>```

Body:
I need to prevent my page from reloading after an Ajax PUT Request.

Basically i have a PUT request to update my database which is fired from a button click, on success of this i want to call another function which is an ajax GET, to reload the data i have just updated, However when doing this, i hit the controller method and get the new list of data, but the page reloads to default and does nothing with my new list

Ajax PUT

function SendDeleteToController(checkid) {
    $.ajax({
        type: "PUT",
        url: '@Url.Action("PutCheck", "Admin")',
        contentType: "application/json; charset=utf-8",
        datatype: JSON,
        data: JSON.stringify({ methodParam: checkid }),
        success: function () {
            GetListofChecks();
        },
        error: function () {
            alert("error");
        }

AJAX GET

function GetListofChecks() {
    var department = $('#department').val();
    var process = $('#process').val();

    $.ajax({
        type: 'GET',
        url: '@Url.Action("GetListofChecks", "Admin")',
        contentType: "application/json; charset=utf-8",
        datatype: JSON,
        data: { "Department": department, "Process": process },
        success: function (result) {
            $("#mainData").empty();

            $.each(JSON.parse(result),
                function (i, item) {
                    var row = i + 1;
                    $("#mainData").append()
        },
        error: function (result) {
            alert(result);
        }
    });
}

controller that returns list of new data

public JsonResult GetListofChecks(string department, string process)
{
    var listofChecks = new List<Check>();

    listofChecks = AdminModel.GetListofchecks(department, process);

    var json = new JavaScriptSerializer().Serialize(listofChecks);
    return Json(json, JsonRequestBehavior.AllowGet);
}

Body:
You dont need to use another request (GET) to retrieve the data, just return it in your controller after you delete the item, the callback function will get a response object for use in your success/error callback functions

Try this (comments in code):

function SendDeleteToController(checkid){
  $.ajax({
      type: "PUT",
      url: '@Url.Action("PutCheck", "Admin")',
      contentType: "application/json; charset=utf-8",
      datatype: JSON,
      data: JSON.stringify({
        methodParam: checkid
      }),
      success: function(result) {
        //your request will return the json object for use in your callback function
        //something like below, though I dont know what your JSON result looks like
        $('body').append(result.id);
      },
      error: function(result) {
        alert("error " + result);
  });
});


问:
Globally installed keyboard hook prevents keyboard input to other applications
I am setting a global hook for keyboard. When I give keyboard inputs to other applications, the application does not receive the input and it hangs. When the console is stopped, the application recovers and the keyboard inputs are posted together.

DLL source:

```<code>#include <iostream>
#include <Windows.h>
#include <string>
using namespace std;
#define DLLEXPORT __declspec(dllexport)

DLLEXPORT bool installhook();
DLLEXPORT void unhook();
DLLEXPORT string TestLoaded();
DLLEXPORT LRESULT CALLBACK KeyboardProc ( int code, WPARAM wParam, LPARAM lParam );

static HHOOK kb_hook;
string test = "not loaded";
HINSTANCE hDLL;

DLLEXPORT LRESULT CALLBACK KeyboardProc ( int code, WPARAM wParam, LPARAM lParam )
{
    if(code == HC_ACTION)   // if there is an incoming action and a key was pressed
    {
        switch(wParam)
        {
        case VK_SPACE:
            printf("Space was pressed\n"); //tried without this also
            MessageBoxA(NULL, "Hi", "Space", MB_OK);
            break;
        }
    }
    return CallNextHookEx(NULL, code, wParam, lParam);
}

BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
    test = "loaded";
    switch(ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        hDLL = hModule;
        break;
    }
    printf("test str = %s \n", test.c_str());
    return TRUE;
}

bool installhook()
{
    kb_hook = SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, hDLL, NULL);
    if(!kb_hook)
    {
        return false;
    }
    return true;
}

void unhook()
{
    if(kb_hook)
    {
        UnhookWindowsHookEx(kb_hook);
    }
}

string TestLoaded()
{
    return test;
}
</code>```

Console applicatioon source:

```<code>#include <iostream>
#include <Windows.h>
#include <string>
#define DLLIMPORT __declspec(dllimport)
using namespace std;

DLLIMPORT void unhook();
DLLIMPORT bool installhook();
DLLIMPORT string TestLoaded();

int main()
{
    cout << TestLoaded() <<endl;
    installhook();
    for(int i = 1; i<=10 ; i++)
    {
        //Do some keyboard activities in this 10 secs
        Sleep(1000);
        cout << i<<endl;
    }

    unhook();
    cin.get();
    return 1;
}
</code>```

My suspicion was that since the dll will be loaded into each process in the process's own address space and console would not be present in other applications, it gets void and crashed. So I removed the console outputs and replaced with messagebox. Then also no difference.

What could be the problem?

Update:

I tried to do a local hook to a specific thread before trying it global. But I get Parameter is incorrect error 87 at setwindowshookex. Below are the updated code:

dll:

```<code>bool installhook(DWORD ThreadId) //exporting this function
{
    kb_hook = SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, NULL, ThreadId); //tried with the dll module's handle also instead of NULL
    if(!kb_hook)
    {
        printf("SetWindowsHookEx failed : %d\n", GetLastError());
        return false;
    }
    return true;
}
</code>```

Console application source:

```<code>DWORD myThread()
{
    cout<< "Thread started\n";
    char str[250];
    cin>>str;
    return 0;
}

int main()
{
    cout << TestLoaded() <<endl;
    DWORD myThreadID;
    HANDLE myHandle = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)myThread, NULL, 0, &myThreadID);
    installhook(myThreadID);
    for(int i = 0; i<100 ; i++)
    {
        Sleep(100);
        if(i%10 == 0)
        {
            cout << i<<endl;
        }
    }
    unhook();
}
</code>```

答:
I had the same issue, working with QT, the GUI would be blocked (as planned) but whenever it came back online, it would process my keyboard and mouse clicks.

I am not sure if this is the most efficient way of handling it, but to solve this, I handled all the keyboard and mouse events separately. If, some task was in progress, I would just ignore the key event.

Otherwise I guess it just queues up and waits for its' turn!

Body:
I am setting a global hook for keyboard. When I give keyboard inputs to other applications, the application does not receive the input and it hangs. When the console is stopped, the application recovers and the keyboard inputs are posted together.

DLL source:

#include <iostream>
#include <Windows.h>
#include <string>
using namespace std;
#define DLLEXPORT __declspec(dllexport)

DLLEXPORT bool installhook();
DLLEXPORT void unhook();
DLLEXPORT string TestLoaded();
DLLEXPORT LRESULT CALLBACK KeyboardProc ( int code, WPARAM wParam, LPARAM lParam );

static HHOOK kb_hook;
string test = "not loaded";
HINSTANCE hDLL;

DLLEXPORT LRESULT CALLBACK KeyboardProc ( int code, WPARAM wParam, LPARAM lParam )
{
    if(code == HC_ACTION)   // if there is an incoming action and a key was pressed
    {
        switch(wParam)
        {
        case VK_SPACE:
            printf("Space was pressed\n"); //tried without this also
            MessageBoxA(NULL, "Hi", "Space", MB_OK);
            break;
        }
    }
    return CallNextHookEx(NULL, code, wParam, lParam);
}

BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
    test = "loaded";
    switch(ul_reason_for_call)
    {
    case DLL_PROCESS_ATTACH:
        hDLL = hModule;
        break;
    }
    printf("test str = %s \n", test.c_str());
    return TRUE;
}

bool installhook()
{
    kb_hook = SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, hDLL, NULL);
    if(!kb_hook)
    {
        return false;
    }
    return true;
}

void unhook()
{
    if(kb_hook)
    {
        UnhookWindowsHookEx(kb_hook);
    }
}

string TestLoaded()
{
    return test;
}

Console applicatioon source:

#include <iostream>
#include <Windows.h>
#include <string>
#define DLLIMPORT __declspec(dllimport)
using namespace std;

DLLIMPORT void unhook();
DLLIMPORT bool installhook();
DLLIMPORT string TestLoaded();

int main()
{
    cout << TestLoaded() <<endl;
    installhook();
    for(int i = 1; i<=10 ; i++)
    {
        //Do some keyboard activities in this 10 secs
        Sleep(1000);
        cout << i<<endl;
    }

    unhook();
    cin.get();
    return 1;
}

My suspicion was that since the dll will be loaded into each process in the process's own address space and console would not be present in other applications, it gets void and crashed. So I removed the console outputs and replaced with messagebox. Then also no difference.

What could be the problem?

Update:

I tried to do a local hook to a specific thread before trying it global. But I get Parameter is incorrect error 87 at setwindowshookex. Below are the updated code:

dll:

bool installhook(DWORD ThreadId) //exporting this function
{
    kb_hook = SetWindowsHookEx(WH_KEYBOARD, KeyboardProc, NULL, ThreadId); //tried with the dll module's handle also instead of NULL
    if(!kb_hook)
    {
        printf("SetWindowsHookEx failed : %d\n", GetLastError());
        return false;
    }
    return true;
}

Console application source:

DWORD myThread()
{
    cout<< "Thread started\n";
    char str[250];
    cin>>str;
    return 0;
}

int main()
{
    cout << TestLoaded() <<endl;
    DWORD myThreadID;
    HANDLE myHandle = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)myThread, NULL, 0, &myThreadID);
    installhook(myThreadID);
    for(int i = 0; i<100 ; i++)
    {
        Sleep(100);
        if(i%10 == 0)
        {
            cout << i<<endl;
        }
    }
    unhook();
}