答:
Here is a simple working code for you. What you are doing is exactly right, except that you need to assign a class to the ul and have a check for that too. Try the below code:

var $indexSelect = $('#index__filter');
var $indexEntry = $('.index__entry');
var $tag = $('.tag');

$indexSelect.change(function() {
  $indexEntry.removeClass('selected');
  var selectedValue = $(this).val();
  if (selectedValue == 'ALL') {
    $indexEntry.css('color', 'black');
    return;
  }

  $tag.each(function(i, option) {
    if (!$(this).closest('ul').hasClass('selected')) {
      $(this).closest('ul').css('color', 'lightgray');
      if ($(this).html() == selectedValue) {
        $(this).closest('ul').css('color', 'black').addClass('selected');
        //console.log($(this).text());
      }
    }
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
  <div class="index__container">
    <section class="index">
      <ul class="index__header">
        <li>Project</li>
        <li>Filter: <select id="index__filter">
                <option selected="selected" value='ALL'>All</option>
                <option value="Pedagogical Explorations">Pedagogical Explorations</option>
                <option value="Research Production">Research Production</option>
                <option value="Spatial Practice">Spatial Practice</option>
                <option value="Exhibition">Exhibition</option>
            </select></li>
        <li>Year</li>
      </ul>

        <ul class="index__entry">
          <li>Multiscale Strategies to Reactivate Transhumance in Spain</li>
          <li>
            <span class="tag">Spatial Practice</span>
          </li>
          <li>2017</li>
        </ul>

        <ul class="index__entry">
          <li>Architecture after Speculation</li>
          <li>
            <span class="tag">Research Production</span>
          </li>
          <li>2017</li>
        </ul>

        <ul class="index__entry">
          <li>Polyester Merino Chair</li>
          <li>
            <span class="tag">Spatial Practice</span>
          </li>
          <li>2017</li>
        </ul>

        <ul class="index__entry">
          <li>1500 caracteres</li>
          <li>
            <span class="tag">Spatial Practice</span>
            <span class="tag">Research Production</span>
          </li>
          <li>2017</li>
        </ul>

        <ul class="index__entry">
          <li>Europan 13: Die Arbeitersiedlung</li>
          <li>
            <span class="tag">Spatial Practice</span>
          </li>
          <li>2015</li>
        </ul>

        <ul class="index__entry">
          <li>Asymmetric Meta-Mapping</li>
          <li>
            <span class="tag">Pedagogical Explorations</span>
          </li>
          <li>2017</li>
        </ul>

        <ul class="index__entry">
          <li>Chicago Architecture Biennial</li>
          <li>
            <span class="tag">Spatial Practice</span>
            <span class="tag">Research Production</span>
            <span class="tag">Exhibition</span></li>
          <li>2015</li>
        </ul>

    </section>
  </div></code>```

Title: Filter list results with <select/> drop-down list value

Body:
I am trying to filter a 'Project Index' by tags using jQuery and CSS.

I am currently taking the .val() of the selected option in a <select> dropdown list and checking if it's equal to the inner .html() of a .tag. If they match it will make the project entry black, if else it will make it light gray.

My current code works when the project has one tag, but once there are multiple tags it breaks. My guess is that because although there is one .tag equal to the selected dropdown value, the other .tag are not,  therefore using the else condition?

What am I missing? Is there a better/more efficient way to do this?

HTML

Project

Filter: <select id="index__filter">
                <option selected="selected" value='ALL'>All</option>
                <option value="Pedagogical Explorations">Pedagogical Explorations</option>
                <option value="Research Production">Research Production</option>
                <option value="Spatial Practice">Spatial Practice</option>
                <option value="Exhibition">Exhibition</option>
            </select>

Year

Multiscale Strategies to Reactivate Transhumance in Spain

                    Spatial Practice

2017

Architecture after Speculation

                    Research Production

2017

Polyester Merino Chair

                    Spatial Practice

2017

1500 caracteres

                    Spatial Practice
                    Research Production

2017

Europan 13: Die Arbeitersiedlung

                    Spatial Practice

2015

Asymmetric Meta-Mapping

                    Pedagogical Explorations

2017

Chicago Architecture Biennial

                    Spatial Practice
                    Research Production
                    Exhibition

2015

JS

  // Filter Project Index
  var $indexSelect = $('#index__filter');
  var $indexEntry = $('.index__entry');
  var $tag = $('.tag');

  $indexSelect.change(function(){
    var selectedValue = $(this).val();
    if(selectedValue == 'ALL'){
       $indexEntry.css('color', 'black');
     return;
    }

    $tag.each(function(i,option){
     if ($(this).html() == selectedValue) {
        $(this).closest('ul').css('color', 'black');
        console.log($(this).text());
      } else {
       $(this).closest('ul').css('color', 'lightgray');
      }
    });
  });

Body:
Here is a simple working code for you. What you are doing is exactly right, except that you need to assign a class to the ul and have a check for that too. Try the below code:

var $indexSelect = $('#index__filter');
var $indexEntry = $('.index__entry');
var $tag = $('.tag');

$indexSelect.change(function() {
  $indexEntry.removeClass('selected');
  var selectedValue = $(this).val();
  if (selectedValue == 'ALL') {
    $indexEntry.css('color', 'black');
    return;
  }

  $tag.each(function(i, option) {
    if (!$(this).closest('ul').hasClass('selected')) {
      $(this).closest('ul').css('color', 'lightgray');
      if ($(this).html() == selectedValue) {
        $(this).closest('ul').css('color', 'black').addClass('selected');
        //console.log($(this).text());
      }
    }
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
  <div class="index__container">
    <section class="index">
      <ul class="index__header">
        <li>Project</li>
        <li>Filter: <select id="index__filter">
                <option selected="selected" value='ALL'>All</option>
                <option value="Pedagogical Explorations">Pedagogical Explorations</option>
                <option value="Research Production">Research Production</option>
                <option value="Spatial Practice">Spatial Practice</option>
                <option value="Exhibition">Exhibition</option>
            </select></li>
        <li>Year</li>
      </ul>
      <a href="">
        <ul class="index__entry">
          <li>Multiscale Strategies to Reactivate Transhumance in Spain</li>
          <li>
            <span class="tag">Spatial Practice</span>
          </li>
          <li>2017</li>
        </ul>
      </a>
      <a href="">
        <ul class="index__entry">
          <li>Architecture after Speculation</li>
          <li>
            <span class="tag">Research Production</span>
          </li>
          <li>2017</li>
        </ul>
      </a>
      <a href="">
        <ul class="index__entry">
          <li>Polyester Merino Chair</li>
          <li>
            <span class="tag">Spatial Practice</span>
          </li>
          <li>2017</li>
        </ul>
      </a>
      <a href="">
        <ul class="index__entry">
          <li>1500 caracteres</li>
          <li>
            <span class="tag">Spatial Practice</span>
            <span class="tag">Research Production</span>
          </li>
          <li>2017</li>
        </ul>
      </a>
      <a href="">
        <ul class="index__entry">
          <li>Europan 13: Die Arbeitersiedlung</li>
          <li>
            <span class="tag">Spatial Practice</span>
          </li>
          <li>2015</li>
        </ul>
      </a>
      <a href="">
        <ul class="index__entry">
          <li>Asymmetric Meta-Mapping</li>
          <li>
            <span class="tag">Pedagogical Explorations</span>
          </li>
          <li>2017</li>
        </ul>
      </a>
      <a href="">
        <ul class="index__entry">
          <li>Chicago Architecture Biennial</li>
          <li>
            <span class="tag">Spatial Practice</span>
            <span class="tag">Research Production</span>
            <span class="tag">Exhibition</span></li>
          <li>2015</li>
        </ul>
      </a>
    </section>
  </div>


来源: stackexchange

问:
how to use signal frameChanged(int) to play the QMovie once in QT
how to use frameChanged(int) to decide the frame is the last frame, i want to use the signal to stop the Qmovie to play it once instead of forever.

```<code>QMovie *movie = new QMovie();
movie->setFileName("C:/Qt/qtcreator-2.2.1/game/test/pikaqiu.gif");
QSize size = this->getLabelPointer()->size();
movie->setScaledSize(size);
this->getLabelPointer()->setMovie(movie);
QObject::connect(movie,SIGNAL(finished()),movie,SLOT(deleteLater()));
movie->start();
enter code here
delete this;
movie->stop();
</code>```

`

答:
You must use the frameCount() function to get the number of frames of QMovie.

```<code>QMovie *movie = new QMovie();
movie->setFileName("download.gif");
ui->label->setMovie(movie);

connect(movie, &QMovie::frameChanged, [=](int frameNumber){
    if(frameNumber == movie->frameCount()-1){
        movie->stop();
        movie->deleteLater();
    }
});
movie->start();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
how to use frameChanged(int) to decide the frame is the last frame, i want to use the signal to stop the Qmovie to play it once instead of forever.

QMovie *movie = new QMovie();
movie->setFileName("C:/Qt/qtcreator-2.2.1/game/test/pikaqiu.gif");
QSize size = this->getLabelPointer()->size();
movie->setScaledSize(size);
this->getLabelPointer()->setMovie(movie);
QObject::connect(movie,SIGNAL(finished()),movie,SLOT(deleteLater()));
movie->start();
enter code here
delete this;
movie->stop();

`

Body:
You must use the frameCount() function to get the number of frames of QMovie.

QMovie *movie = new QMovie();
movie->setFileName("download.gif");
ui->label->setMovie(movie);

connect(movie, &QMovie::frameChanged, [=](int frameNumber){
    if(frameNumber == movie->frameCount()-1){
        movie->stop();
        movie->deleteLater();
    }
});
movie->start();


问:
Loop list while adding to it
I've built my system in c-sharp (winforms) and I've run into a problem. In my view - my graphical interface - I'm starting a pretty heavy algorithm, which in each loop adds a result to a list in my view. The algorithm runs in a presenter (MVP pattern), using a backgroundworker - enabling the view not to freeze. As I said before, the algorithm runs in a loop, and since it's so heavy, I want to process the results of the algorithm as they come in.

View:

```<code>...
public List<string> Results { get; }
...
_presenter.RunAlgorithmAsync();
//Start processing results
...
</code>```

Backgroundworker in presenter:

```<code>...
_view.Results.Add(result);
...
</code>```

To sum it up, how can I start processing the list while the backgroundworker adds to it? Of course, the backgroundworker can work faster than the processing of the list, and vice versa - the processing may have to wait for results to arrive to the list, and the list need to be able up build up a stack of results.

I realize this question may be blurry, but if you ask me questions, I'm sure I can define the problem better.

答: Make the BackgroundWorker call a method in the view which adds the item to the list and processes it.</p>

ContentLicense: CC BY-SA 2.5

Title: Loop list while adding to it

Body:
I've built my system in c-sharp (winforms) and I've run into a problem. In my view - my graphical interface - I'm starting a pretty heavy algorithm, which in each loop adds a result to a list in my view. The algorithm runs in a presenter (MVP pattern), using a backgroundworker - enabling the view not to freeze. As I said before, the algorithm runs in a loop, and since it's so heavy, I want to process the results of the algorithm as they come in.

View:

...
public List<string> Results { get; }
...
_presenter.RunAlgorithmAsync();
//Start processing results
...

Backgroundworker in presenter:

...
_view.Results.Add(result);
...

To sum it up, how can I start processing the list while the backgroundworker adds to it? Of course, the backgroundworker can work faster than the processing of the list, and vice versa - the processing may have to wait for results to arrive to the list, and the list need to be able up build up a stack of results.

I realize this question may be blurry, but if you ask me questions, I'm sure I can define the problem better.


问:
Firebase query get today's bookings pass back into array
I am trying to get all the bookings returned from firebase that match todays date.

I am using an *ngFor order of orders in my html to print out all returned orders.

In the firebase database I have 7 bookings saved. 2 out of the 7 are todays date. so all 7 are printing out on screen ok. However when I click my button to run the following function I want to display only bookings for todays date.

```<code>todayBookings() {

    this.ordersData = this.af.list('/orders', {

        query: {
            orderByChild: 'start',
            // equalTo: today
        }
    });
    this.ordersData.subscribe((res) => {
        this.orders = res;
    });

    this.orders.forEach(order => {

        var d = new Date();
        var curr_date = ("0" + (d.getDate() + 0)).slice(-2);
        var curr_month = ("0" + (d.getMonth() + 1)).slice(-2)
        var curr_year = d.getFullYear();
        // get today's date
        var today = curr_year + "-" + curr_month + "-" + curr_date;
        // get date of booking
        var dateOfBooking = order.start.substr(0, 10);

        if (dateOfBooking == today) {
            this.todaysOrders = order;
            var index = this.orders.indexOf(order, 0);
            if (index > -1) {
                this.orders.splice(index, 1);
            }
            // console.log(this.orders);
            // console.log(this.todaysOrders);

        }

    });

    this.orders = this.todaysOrders
    console.log(this.orders);
}
</code>```

When I console log the following: console.log(this.todaysOrders);

I see in the console the 2 bookings for today:

Unfortunately I don't know how to now take this.todaysOrders and pass them back into this.orders.

I tried the following:

this.orders.push(this.todaysOrders);

But it brought back all entries and appended the todays bookings to the list so instead of 7 entries returned it brought 9. (all bookings + the 2 bookings with todays date).

Orders in database

```<code>orders
 -Ko2a0zwYPQc-ocfJ1cF
   createdAt: 1499003887000
   orderId: 34681
   partySize: "1"
   requirements: "none"
   start: "2017-07-02T15:00:44+01:00"
   status: "Accepted"
   type: "tablebooking"
   + userDetails
   userId: "CQbDG6H8ENStlZiaNOGNsvbw2GL2"

   -Ko2ay19E7b17UhZ9HAf
   -Ko2pmavUZNTKdsr0pv6
   -Ko2t6cm35uOtiROeghG
   -Ko2tn6iRmkG7Y-OfAcJ
   -Ko2u5FrD5ZnIphL9Vno
   -KoBtilv2-dj-XmQSQBf
</code>```

Here is the whole class. I have stripped out other functions I am using for other things on the page.

```<code>import { Component, OnInit, AfterViewInit, ElementRef, ViewChild, OnDestroy, OnChanges } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';
import { Router, ActivatedRoute } from "@angular/router";
import { NgForm } from '@angular/forms';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase';
import { ToastrService } from 'toastr-ng2';
import * as moment from 'moment';

@Component({
    selector: 'app-calendar',
    templateUrl: './calendar.component.html',
    styleUrls: ['./calendar.component.scss']
})

export class CalendarComponent implements OnInit, AfterViewInit, OnChanges {

    order: Array<any>;
    orders: Array<any>;
    ordersData: FirebaseListObservable<any>;

    todaysOrders: Array<any>;

    color: any;
    orderId: any;

    @ViewChild('fullcalendar') fullcalendar: ElementRef;

    constructor(public af: AngularFireDatabase, public toastr: ToastrService, public router: Router, public authentication: AngularFireAuth) {

        this.ordersData = af.list('/orders', {
            query: {
                orderByChild: 'start',
            }
        });
        this.ordersData.subscribe((res) => {
            this.orders = res;
        });

    }

    //Get Todays Bookings
    todayBookings() {

        this.ordersData = this.af.list('/orders', {

            query: {
                orderByChild: 'start',
                // equalTo: today
            }
        });
        this.ordersData.subscribe((res) => {
            this.orders = res;
        });

        this.orders.forEach(order => {

            var d = new Date();
            var curr_date = ("0" + (d.getDate() + 0)).slice(-2);
            var curr_month = ("0" + (d.getMonth() + 1)).slice(-2)
            var curr_year = d.getFullYear();
            // get today's date
            var today = curr_year + "-" + curr_month + "-" + curr_date;
            // get date of booking
            var dateOfBooking = order.start.substr(0, 10);

            if (dateOfBooking == today) {
                this.todaysOrders = order;
                var index = this.orders.indexOf(order, 0);
                if (index > -1) {
                    this.orders.splice(index, 1);
                }
                // console.log(this.orders);
                console.log(this.todaysOrders);

            }

        });

        // this.orders = this.todaysOrders
        // console.log(this.orders);
    }

}
</code>```

答:
You can delete each order of today from the orders array.

something like :

```<code>if (dateOfBooking == today) {
  this.todaysOrders = order;
  var index = this.orders.indexOf(order, 0);
  if (index > -1) {
    this.orders.splice(index, 1);
  }
  console.log(this.todaysOrders);
  console.log(this.orders);
}
</code>```

Body:
I am trying to get all the bookings returned from firebase that match todays date.

I am using an *ngFor order of orders in my html to print out all returned orders.

In the firebase database I have 7 bookings saved. 2 out of the 7 are todays date. so all 7 are printing out on screen ok. However when I click my button to run the following function I want to display only bookings for todays date.

todayBookings() {

    this.ordersData = this.af.list('/orders', {

        query: {
            orderByChild: 'start',
            // equalTo: today
        }
    });
    this.ordersData.subscribe((res) => {
        this.orders = res;
    });

    this.orders.forEach(order => {

        var d = new Date();
        var curr_date = ("0" + (d.getDate() + 0)).slice(-2);
        var curr_month = ("0" + (d.getMonth() + 1)).slice(-2)
        var curr_year = d.getFullYear();
        // get today's date
        var today = curr_year + "-" + curr_month + "-" + curr_date;
        // get date of booking
        var dateOfBooking = order.start.substr(0, 10);

        if (dateOfBooking == today) {
            this.todaysOrders = order;
            var index = this.orders.indexOf(order, 0);
            if (index > -1) {
                this.orders.splice(index, 1);
            }
            // console.log(this.orders);
            // console.log(this.todaysOrders);

        }

    });

    this.orders = this.todaysOrders
    console.log(this.orders);
}

When I console log the following: console.log(this.todaysOrders);

I see in the console the 2 bookings for today:

Unfortunately I don't know how to now take this.todaysOrders and pass them back into this.orders.

I tried the following:

this.orders.push(this.todaysOrders);

But it brought back all entries and appended the todays bookings to the list so instead of 7 entries returned it brought 9. (all bookings + the 2 bookings with todays date).

Orders in database

orders
 -Ko2a0zwYPQc-ocfJ1cF
   createdAt: 1499003887000
   orderId: 34681
   partySize: "1"
   requirements: "none"
   start: "2017-07-02T15:00:44+01:00"
   status: "Accepted"
   type: "tablebooking"
   + userDetails
   userId: "CQbDG6H8ENStlZiaNOGNsvbw2GL2"

   -Ko2ay19E7b17UhZ9HAf
   -Ko2pmavUZNTKdsr0pv6
   -Ko2t6cm35uOtiROeghG
   -Ko2tn6iRmkG7Y-OfAcJ
   -Ko2u5FrD5ZnIphL9Vno
   -KoBtilv2-dj-XmQSQBf

Here is the whole class. I have stripped out other functions I am using for other things on the page.

import { Component, OnInit, AfterViewInit, ElementRef, ViewChild, OnDestroy, OnChanges } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';
import { Router, ActivatedRoute } from "@angular/router";
import { NgForm } from '@angular/forms';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase';
import { ToastrService } from 'toastr-ng2';
import * as moment from 'moment';

@Component({
    selector: 'app-calendar',
    templateUrl: './calendar.component.html',
    styleUrls: ['./calendar.component.scss']
})

export class CalendarComponent implements OnInit, AfterViewInit, OnChanges {

    order: Array<any>;
    orders: Array<any>;
    ordersData: FirebaseListObservable<any>;

    todaysOrders: Array<any>;

    color: any;
    orderId: any;

    @ViewChild('fullcalendar') fullcalendar: ElementRef;

    constructor(public af: AngularFireDatabase, public toastr: ToastrService, public router: Router, public authentication: AngularFireAuth) {

        this.ordersData = af.list('/orders', {
            query: {
                orderByChild: 'start',
            }
        });
        this.ordersData.subscribe((res) => {
            this.orders = res;
        });

    }

    //Get Todays Bookings
    todayBookings() {

        this.ordersData = this.af.list('/orders', {

            query: {
                orderByChild: 'start',
                // equalTo: today
            }
        });
        this.ordersData.subscribe((res) => {
            this.orders = res;
        });

        this.orders.forEach(order => {

            var d = new Date();
            var curr_date = ("0" + (d.getDate() + 0)).slice(-2);
            var curr_month = ("0" + (d.getMonth() + 1)).slice(-2)
            var curr_year = d.getFullYear();
            // get today's date
            var today = curr_year + "-" + curr_month + "-" + curr_date;
            // get date of booking
            var dateOfBooking = order.start.substr(0, 10);

            if (dateOfBooking == today) {
                this.todaysOrders = order;
                var index = this.orders.indexOf(order, 0);
                if (index > -1) {
                    this.orders.splice(index, 1);
                }
                // console.log(this.orders);
                console.log(this.todaysOrders);

            }

        });

        // this.orders = this.todaysOrders
        // console.log(this.orders);
    }

}

Body:
You can delete each order of today from the orders array.

something like :

if (dateOfBooking == today) {
  this.todaysOrders = order;
  var index = this.orders.indexOf(order, 0);
  if (index > -1) {
    this.orders.splice(index, 1);
  }
  console.log(this.todaysOrders);
  console.log(this.orders);
}


问:
Can we do peer to peer chat using Firebase Chat application in web?
I am using firebase chat application with angularJs. My requirement is message send user to user only not send to all users. So, is there any way to do user to user chat?</p>

答:
For example - you could create a global chats collection. When you want two users A & B to chat you can create a UID under chats and store it under each user A & B.

Then whenever you have a send messages, you just get the chat id from under the user and add the message in the global chat collection.

```<code>Firebase
  -Users
    -A
      -Chats
        -Id of User B
          -chatid1
    -B
      -Chats
        -Id of user A
          -chatid
    -..
    -..
  -Chats
    -chatid1
      -message1
      -message2
      -..
    -chatid2
    -..
</code>```

Body:
For example - you could create a global chats collection. When you want two users A & B to chat you can create a UID under chats and store it under each user A & B.

Then whenever you have a send messages, you just get the chat id from under the user and add the message in the global chat collection.

Firebase
  -Users
    -A
      -Chats
        -Id of User B
          -chatid1
    -B
      -Chats
        -Id of user A
          -chatid
    -..
    -..
  -Chats
    -chatid1
      -message1
      -message2
      -..
    -chatid2
    -..


问:
Dividing a float and an Integer in SQL and getting a Integer result
I am dividing a float value (such as 87.34234) by a Integer value (2) in SQL and I would like the resulting answer to be an integer with no decimal places.

Thanks

答:
This is very basic answer, check if you are happy with this:

```<code>select cast(87.34234/2 as int)
</code>```

or second option:

```<code>select cast(round(87.34234/2,0) as int)
</code>```

Body:
This is very basic answer, check if you are happy with this:

select cast(87.34234/2 as int)

or second option:

select cast(round(87.34234/2,0) as int)


问:
What is the best way to have custom css styles to theme a layout?
Let's say we have a massive CSS file that is used to style the layout of an application. Now, we want to let users change the colours of the layout to personalize it. What is the best way to do this customization, like in terms of design and architecture? I'm looking for a solution that is pretty easy to implement and isn't very intrusive.

I also don't want to make the whole css file templated on the server if I don't have to. I'd like to keep it in my /css file if it's possible, without any server dependencies.

Ideally, I'd like to just override the styles in the default, but I don't think that's possible as it will probably erase the existing styles. Which means I'll have duplicate style information as I overwrite them... which is also bad. Duplication = bad.

I guess we can assume that there's some server object related their account that has several properties for various colours, like backgrounds, menu tabs, link colours, hovered versions, etc.

```<code>public class Theme {

    private String headerBackground = "#172636";
    private String displayName = "#ffffff";

    private String tabBackground = "#284767";
    private String tabText = displayName;
    private String hoverTabBackground = tabBackground;
    private String hoverTabText = tabText;
    private String selectedTabBackground = "#f5f5f5";
    private String selectedTabText = "#172636";

    private String tableHeaderBackground = headerBackground;
    private String tableHeaderText = displayName;
    private String tableSubHeaderBackground = tabBackground;
    private String tableSubHeaderText = displayName;
    private String hoverTableRowBackground = "#c0d2e4";

    private String link = "#4e6c92";
</code>```

My best guess is to just serve the entire css file and have my MVC framework merge the Theme with the css text and than serve it out. Is this the best way? Will that force the browser to never cache it?

My application is using Spring/Hibernate, but I'm pretty sure any recommendations even if you don't use Java/Spring will be doable with these technologies.

Thanks for the help.

答: Oh, nice take. But it's very important to apply some filtering to the strings that the user supplies, otherwise you are exposing your application to some serious code injection attacks!</p>

Body:
Let's say we have a massive CSS file that is used to style the layout of an application. Now, we want to let users change the colours of the layout to personalize it. What is the best way to do this customization, like in terms of design and architecture? I'm looking for a solution that is pretty easy to implement and isn't very intrusive.

I also don't want to make the whole css file templated on the server if I don't have to. I'd like to keep it in my /css file if it's possible, without any server dependencies.

Ideally, I'd like to just override the styles in the default, but I don't think that's possible as it will probably erase the existing styles. Which means I'll have duplicate style information as I overwrite them... which is also bad. Duplication = bad.

I guess we can assume that there's some server object related their account that has several properties for various colours, like backgrounds, menu tabs, link colours, hovered versions, etc.

public class Theme {

    private String headerBackground = "#172636";
    private String displayName = "#ffffff";

    private String tabBackground = "#284767";
    private String tabText = displayName;
    private String hoverTabBackground = tabBackground;
    private String hoverTabText = tabText;
    private String selectedTabBackground = "#f5f5f5";
    private String selectedTabText = "#172636";

    private String tableHeaderBackground = headerBackground;
    private String tableHeaderText = displayName;
    private String tableSubHeaderBackground = tabBackground;
    private String tableSubHeaderText = displayName;
    private String hoverTableRowBackground = "#c0d2e4";

    private String link = "#4e6c92";

My best guess is to just serve the entire css file and have my MVC framework merge the Theme with the css text and than serve it out. Is this the best way? Will that force the browser to never cache it?

My application is using Spring/Hibernate, but I'm pretty sure any recommendations even if you don't use Java/Spring will be doable with these technologies.

Thanks for the help.


问:
How to execute javascript in Neutronium library?
I'm a hybrid app WPF + Neutronium (html, css, javascript),

When occurs SelectionChanged event in the ListBox WPF component, the csharp calls codebehind like:

```<code>private void searchList_SelectionChanged(object sender, SelectionChangedEventArgs e)
</code>```

Inside this method I need to send a javascript command to Neutronium (WPF:HTMLViewControl).

But I don't found anyone javascript execute command in neutronium HTMLViewControl component.

How I make it?

Neutronium: https://github.com/David-Desmaisons/Neutronium

答:
Neutronium philosophy is to use MVVVM pattern as a communication between JS and C#.

As such, the best way to react to searchList_SelectionChanged is to update a view model property that will trigger changes in the HTML side.

Pseudo code using Vue:
C#:

```<code>private void searchList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
   vm.Selected = selected;
}
</code>```

Vm:

```<code>public class MainVm
{
    private SelectedObject _Selected ;
    public SelectedObject Selected
    {
        get { return _Selected ; }
        set
        {
           _Selected = value;
           PropertyChanged(this, new PropertyChangedEventArgs("Selected"));
        }
    }
//...
}
</code>```

Vue template:

```<code><component :element:="viewModel.Selected ">
</component >
</code>```

Neutronium will take care of all the communication here.

If you need something more specific you can even use a Vue.js watch on the selected element.

I will recomend you to take a look at: https://github.com/NeutroniumCore/Neutronium.SPA.Demo, https://github.com/NeutroniumCore/CodeDependencyScanner
and https://github.com/David-Desmaisons/Music.Cover.Finder that are good example of Neutronium usage.

Body:
I'm a hybrid app WPF + Neutronium (html, css, javascript),

When occurs SelectionChanged event in the ListBox WPF component, the csharp calls codebehind like:

private void searchList_SelectionChanged(object sender, SelectionChangedEventArgs e)

Inside this method I need to send a javascript command to Neutronium (WPF:HTMLViewControl).

But I don't found anyone javascript execute command in neutronium HTMLViewControl component.

How I make it?

Neutronium: https://github.com/David-Desmaisons/Neutronium

Body:
Neutronium philosophy is to use MVVVM pattern as a communication between JS and C#.

As such, the best way to react to searchList_SelectionChanged is to update a view model property that will trigger changes in the HTML side.

Pseudo code using Vue:
C#:

private void searchList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
   vm.Selected = selected;
}

Vm:

public class MainVm
{
    private SelectedObject _Selected ;
    public SelectedObject Selected
    {
        get { return _Selected ; }
        set
        {
           _Selected = value;
           PropertyChanged(this, new PropertyChangedEventArgs("Selected"));
        }
    }
//...
}

Vue template:

<component :element:="viewModel.Selected ">
</component >

Neutronium will take care of all the communication here.

If you need something more specific you can even use a Vue.js watch on the selected element.

I will recomend you to take a look at: https://github.com/NeutroniumCore/Neutronium.SPA.Demo, https://github.com/NeutroniumCore/CodeDependencyScanner
and https://github.com/David-Desmaisons/Music.Cover.Finder that are good example of Neutronium usage.

ContentLicense: CC BY-SA 4.0


问:
Is it possible to execute many stored procedures in a single operation?
I am coding to read xml files to update the database. I get about 500 xml files and I want to process them as fast I can.

All database operations are done using stored procedures.

There are about 35 different stored procedures called for each xml file.

Initially I had written the code like this

```<code>var cmd = new SqlCommand("EXEC UpdateTeamStats("+teamId+","+points+")");
cmd.CommandType = CommandType.Text;
</code>```

but after going through some best practices I changed it to

```<code>var cmd = new SqlCommand("UpdateTeamStats");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("teamId", 21);
cmd.Parameters.Add("points", 2);
</code>```

because of the high number of stored procedures being called from the program I realized I have to make lesser number of calls in order to optimize.

So I want to collect all the 35 stored procedures together and execute them in one go.

The stored procedures are different with different parameters and I dont know a way to collect and execute them together after the parameter changes I did above.

I was thinking of calling one giant stored procedure and inside that stored procedure calling the other 35 , but I am not very good at SQL and it will lead to unnecessary complexity.

Is it Possible to do this entirely in C#?

Or is there some other better method to queue up the storedprocedures and run them quickly

答:
Personally, and in my experience using ADO.NET, I think you will have no issue whatsoever executing these as separate statements using a single SqlConnection.

This has the benefit of leveraging .NET's amazing connection pooling, enables you to work/customize/interact with each command individually and rides a shared connection (reducing the amount of connection brokering to a trivial amount).

I'd also like to emphasize the important of the using clauses here that facilitate the proper disposal of the various resources.

For example:

```<code>using (var conn = new SqlConnection("connection string"))
{
    using (var cmd = new SqlCommand())
    {
        cmd.Connection = conn;
        cmd.CommandType = CommandType.StoredProcedure;

        //ready to query
        conn.Open();

        cmd.CommandText = "UpdateTeamStats";
        var teamIdParam = new SqlParameter("teamId", 21);
        var pointsParam = new SqlParameter("points", 2);

        cmd.Parameters.Add(teamIdParam);
        cmd.Parameters.Add(pointsParam);

        cmd.ExecuteNonQuery(); //OR if you're async cmd.ExecuteNonQueryAsync();

        //the rest of your executions

        conn.Close();
    }
}
</code>```

And if I'm being solicitous for a moment, you can use a library, like mine DbConnect, which reduces the above to:

```<code>using (var db = new DbConnect("connection string"))
{
    db.SetSqlCommand("UpdateTeamStats");
    db.AddParameter("teamId", 21);
    db.AddParameter("points", 2);

    db.ExecuteNonQuery().Wait(); //OR if youre async await db.ExecuteNonQuery();

    db.ClearParameters();
    db.SetSqlCommand("some other proc");

    //rest of executions
}
</code>```

Body:
I am coding to read xml files to update the database. I get about 500 xml files and I want to process them as fast I can.

All database operations are done using stored procedures.

There are about 35 different stored procedures called for each xml file.

Initially I had written the code like this

var cmd = new SqlCommand("EXEC UpdateTeamStats("+teamId+","+points+")");
cmd.CommandType = CommandType.Text;

but after going through some best practices I changed it to

var cmd = new SqlCommand("UpdateTeamStats");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("teamId", 21);
cmd.Parameters.Add("points", 2);

because of the high number of stored procedures being called from the program I realized I have to make lesser number of calls in order to optimize.

So I want to collect all the 35 stored procedures together and execute them in one go.

The stored procedures are different with different parameters and I dont know a way to collect and execute them together after the parameter changes I did above.

I was thinking of calling one giant stored procedure and inside that stored procedure calling the other 35 , but I am not very good at SQL and it will lead to unnecessary complexity.

Is it Possible to do this entirely in C#?

Or is there some other better method to queue up the storedprocedures and run them quickly

Body:
Personally, and in my experience using ADO.NET, I think you will have no issue whatsoever executing these as separate statements using a single SqlConnection.

This has the benefit of leveraging .NET's amazing connection pooling, enables you to work/customize/interact with each command individually and rides a shared connection (reducing the amount of connection brokering to a trivial amount).

I'd also like to emphasize the important of the using clauses here that facilitate the proper disposal of the various resources.

For example:

using (var conn = new SqlConnection("connection string"))
{
    using (var cmd = new SqlCommand())
    {
        cmd.Connection = conn;
        cmd.CommandType = CommandType.StoredProcedure;

        //ready to query
        conn.Open();

        cmd.CommandText = "UpdateTeamStats";
        var teamIdParam = new SqlParameter("teamId", 21);
        var pointsParam = new SqlParameter("points", 2);

        cmd.Parameters.Add(teamIdParam);
        cmd.Parameters.Add(pointsParam);

        cmd.ExecuteNonQuery(); //OR if you're async cmd.ExecuteNonQueryAsync();

        //the rest of your executions

        conn.Close();
    }
}

And if I'm being solicitous for a moment, you can use a library, like mine DbConnect, which reduces the above to:

using (var db = new DbConnect("connection string"))
{
    db.SetSqlCommand("UpdateTeamStats");
    db.AddParameter("teamId", 21);
    db.AddParameter("points", 2);

    db.ExecuteNonQuery().Wait(); //OR if youre async await db.ExecuteNonQuery();

    db.ClearParameters();
    db.SetSqlCommand("some other proc");

    //rest of executions
}


问:
Named pipe, read fail with bad file descriptor
I'm beginning with pipes under Linux and I have a problem with my code.
I wanted to test sending an integer through the fifo so I code a small program to test it.

First I open the read only descriptor and then the write only one as precised in the documentation.
I send the number to the pipe and close the write descriptor.

However, when I'm trying to read from the pipe, it says that I have a bad file descriptor, I don't understand why it's not working because as the descriptor is the good one and is oppened with good option (O_RDONLY | O_NONBLOCK).

Here is my code :

```<code>void main(void)
{
    int modePipeWrite, modePipeRead;

    if(mkfifo("test.fifo", 0777) == -1)
    {
        perror("mkfifo");
        exit(EXIT_FAILURE);
    }
    if(modePipeRead = open("test.fifo", O_RDONLY | O_NONBLOCK) == -1)
    {
        perror("openRead");
        exit(EXIT_FAILURE);
    }
    if(modePipeWrite = open("test.fifo", O_WRONLY | O_NONBLOCK) == -1)
    {
        perror("openWrite");
        exit(EXIT_FAILURE);
    }

    int n = 0;

    if(write(modePipeWrite, &n, sizeof(n)) == -1)
    {
        perror("write");
    }
    printf("Send value: %d\n", n);

    close(modePipeWrite);

    int mode;

    while(1)
    {
        if(read(modePipeRead, &mode, sizeof(mode)) == -1)
        {
            perror("read");
        }
        printf("Received value: %d\n", getpid(), mode);
        sleep(1);
    }
}
</code>```

And the output :

```<code>./a.out
Send value: 0

read: Bad file descriptor
Received value: -1877110288

read: Bad file descriptor
Received value: -1877110288

read: Bad file descriptor
Received value: -1877110288
</code>```

I don't understand what could be wrong here. If someone have some advices I would be glad to hear it.

答:
Your code has a couple of issues, which you would've found if you compiled it with all warnings enabled. If you use gcc, the following options are nice/mandatory:
     -Wall -Wextra -Werror -pedantic

One issue is that you don't assign the return value of open() to the file descriptors. You need to add braces around the assignment, or move it out of the if-statements.

Here's a working example, using a thread to read:

```<code>#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>

#include <pthread.h>

static void *reader(void *arg)
{
    int fd, val;

    if ((fd = open("test.fifo", O_RDONLY)) == -1) {
        perror("openRead");
        exit(EXIT_FAILURE);
    }

    if (read(fd, &val, sizeof val) == -1)
        perror("read");
    else
        printf("Received value: %d\n", val);

    close(fd);
    return NULL;
}

int main(void)
{
    int modePipeWrite, modePipeRead;
    pthread_t readerid;

    if (mkfifo("test.fifo", 0777) == -1) {
        perror("mkfifo");
        exit(EXIT_FAILURE);
    }
    pthread_create(&readerid, NULL, reader, NULL);
    sleep(1);

    if ((modePipeWrite = open("test.fifo", O_WRONLY)) == -1) {
        perror("openWrite");
        exit(EXIT_FAILURE);
    }

    int n = 1234;

    if (write(modePipeWrite, &n, sizeof n) == -1)
        perror("write");
    else
        printf("Sent value: %d\n", n);

    sleep(1);
    close(modePipeWrite);

    return 0;
}
</code>```

Body:
I'm beginning with pipes under Linux and I have a problem with my code.
I wanted to test sending an integer through the fifo so I code a small program to test it.

First I open the read only descriptor and then the write only one as precised in the documentation.
I send the number to the pipe and close the write descriptor.

However, when I'm trying to read from the pipe, it says that I have a bad file descriptor, I don't understand why it's not working because as the descriptor is the good one and is oppened with good option (O_RDONLY | O_NONBLOCK).

Here is my code :

void main(void)
{
    int modePipeWrite, modePipeRead;

    if(mkfifo("test.fifo", 0777) == -1)
    {
        perror("mkfifo");
        exit(EXIT_FAILURE);
    }
    if(modePipeRead = open("test.fifo", O_RDONLY | O_NONBLOCK) == -1)
    {
        perror("openRead");
        exit(EXIT_FAILURE);
    }
    if(modePipeWrite = open("test.fifo", O_WRONLY | O_NONBLOCK) == -1)
    {
        perror("openWrite");
        exit(EXIT_FAILURE);
    }

    int n = 0;

    if(write(modePipeWrite, &n, sizeof(n)) == -1)
    {
        perror("write");
    }
    printf("Send value: %d\n", n);

    close(modePipeWrite);

    int mode;

    while(1)
    {
        if(read(modePipeRead, &mode, sizeof(mode)) == -1)
        {
            perror("read");
        }
        printf("Received value: %d\n", getpid(), mode);
        sleep(1);
    }
}

And the output :

./a.out
Send value: 0

read: Bad file descriptor
Received value: -1877110288

read: Bad file descriptor
Received value: -1877110288

read: Bad file descriptor
Received value: -1877110288

I don't understand what could be wrong here. If someone have some advices I would be glad to hear it.

Body:
Your code has a couple of issues, which you would've found if you compiled it with all warnings enabled. If you use gcc, the following options are nice/mandatory:
     -Wall -Wextra -Werror -pedantic

One issue is that you don't assign the return value of open() to the file descriptors. You need to add braces around the assignment, or move it out of the if-statements.

Here's a working example, using a thread to read:

#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>

#include <pthread.h>

static void *reader(void *arg)
{
    int fd, val;

    if ((fd = open("test.fifo", O_RDONLY)) == -1) {
        perror("openRead");
        exit(EXIT_FAILURE);
    }

    if (read(fd, &val, sizeof val) == -1)
        perror("read");
    else
        printf("Received value: %d\n", val);

    close(fd);
    return NULL;
}

int main(void)
{
    int modePipeWrite, modePipeRead;
    pthread_t readerid;

    if (mkfifo("test.fifo", 0777) == -1) {
        perror("mkfifo");
        exit(EXIT_FAILURE);
    }
    pthread_create(&readerid, NULL, reader, NULL);
    sleep(1);

    if ((modePipeWrite = open("test.fifo", O_WRONLY)) == -1) {
        perror("openWrite");
        exit(EXIT_FAILURE);
    }

    int n = 1234;

    if (write(modePipeWrite, &n, sizeof n) == -1)
        perror("write");
    else
        printf("Sent value: %d\n", n);

    sleep(1);
    close(modePipeWrite);

    return 0;
}


问:
php running calendar within two weeks
I have a calendar that shows the current month, which we use for scheduling. A request was made to have today's date in the middle, with two weeks of dates on either side.

Current code:

```<code><!DOCTYPE html>
<html>
<head>
<title>Running calendar</title>
</head>
<body>
<?php
date_default_timezone_set('America/New_York');

//Get today's date
$date = time();

//Break date into separate values
$day = date('d',$date);
$month = date('m',$date);
$year = date('Y',$date);

//Generate first day of the month
$first_day = mktime(0,0,0,$month,1,$year);

//Grab month name
$title = date('F',$first_day);

//Here you find out what day of the week the first day of the month falls on
$day_of_week = date('D', $first_day) ;

//We then determine how many days are in the current month
$days_in_month = cal_days_in_month(0, $month, $year) ;

switch($GLOBALS['day_of_week'])
{
case "Sun": $blank = 0; break;
case "Mon": $blank = 1; break;
case "Tue": $blank = 2; break;
case "Wed": $blank = 3; break;
case "Thu": $blank = 4; break;
case "Fri": $blank = 5; break;
case "Sat": $blank = 6; break;
}

$currHour = date("H");

echo "<div id=container>";
echo "<table width=100% class=calendar>";
echo "<tr><th colspan=32 id=title>$title $year</th></tr>";
echo "<tr><th>Employee</th>";
$day_num=1;
while($day_num <= $days_in_month){
echo "<th align=center ";
if($day == $day_num){echo "id=day";}
echo ">$day_num</th>";
$day_num++;
}
echo "</tr>";
echo "</table>";
echo "</div>";
?>
</body>
</html>
</code>```

What they would like to see:

21 22 23 24 25 26 27 28 29 30 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

I haven't had any luck getting the code figured out to display the past two weeks properly.

答:
The cleanest option is probably the following:

```<code>    $period = new \DatePeriod(
                             new \DateTime('-14 days'),
                             \DateInterval::createFromDateString('1 day'),
                             new \DateTime('+14 days')
                             );
    foreach ($period as $day) {
        print $day->format("d") . " | ";
    }
</code>```

Output is:

21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 01 | 02 | 03 | 04 |
  05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |

And if you had to do something to today while looping simply grab it with an equality check:

```<code>if($day == new \DateTime()){
   print "<span style='background-color:red;'>".$day->format("d") . "</span> | ";
}else{
   print $day->format("d") . " | ";
}
</code>```

Title: php running calendar within two weeks

Body:
I have a calendar that shows the current month, which we use for scheduling. A request was made to have today's date in the middle, with two weeks of dates on either side.

Current code:

<!DOCTYPE html>

<title>Running calendar</title>

<?php
date_default_timezone_set('America/New_York');

//Get today's date
$date = time();

//Break date into separate values
$day = date('d',$date);
$month = date('m',$date);
$year = date('Y',$date);

//Generate first day of the month
$first_day = mktime(0,0,0,$month,1,$year);

//Grab month name
$title = date('F',$first_day);

//Here you find out what day of the week the first day of the month falls on
$day_of_week = date('D', $first_day) ;

//We then determine how many days are in the current month
$days_in_month = cal_days_in_month(0, $month, $year) ;

switch($GLOBALS['day_of_week'])
{
case "Sun": $blank = 0; break;
case "Mon": $blank = 1; break;
case "Tue": $blank = 2; break;
case "Wed": $blank = 3; break;
case "Thu": $blank = 4; break;
case "Fri": $blank = 5; break;
case "Sat": $blank = 6; break;
}

$currHour = date("H");

echo "
";
echo "
";
echo "
$title $year
";
echo "
Employee	";
$day_num=1;
while($day_num <= $days_in_month){
echo "$day_num	";
$day_num++;
}
echo "
";
echo "
";
echo "
";
?>

What they would like to see:

21 22 23 24 25 26 27 28 29 30 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

I haven't had any luck getting the code figured out to display the past two weeks properly.

Body:
The cleanest option is probably the following:

    $period = new \DatePeriod(
                             new \DateTime('-14 days'),
                             \DateInterval::createFromDateString('1 day'),
                             new \DateTime('+14 days')
                             );
    foreach ($period as $day) {
        print $day->format("d") . " | ";
    }

Output is:

21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 01 | 02 | 03 | 04 |
  05 | 06 | 07 | 08 | 09 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |

And if you had to do something to today while looping simply grab it with an equality check:

if($day == new \DateTime()){
   print "<span style='background-color:red;'>".$day->format("d") . "</span> | ";
}else{
   print $day->format("d") . " | ";
}


问:
C/C++ function using float or double or int
I have seperate functions for reading from a text file (depending on whether its an int,  float or double). I would like just one function with an additional argument (without using a subsequent IF statement). Does anyone have ideas?

Below is the form of my current functions.

```<code>float * read_column_f (char * file, int size_of_col){
...
col = (float*) malloc (height_row * sizeof(float));
...  return(col);}

double *    read_column_d (char * file, int size_of_col){
...
col = (double*) malloc (height_row * sizeof(double));
...  return(col);}

int *   read_column_i (char * file, int size_of_col){
...
col = (int*) malloc (height_row * sizeof(int));
...  return(col);}
</code>```

EDIT: I want to implement this in C++, the C-style syntax used is due to memory preference.

答:
Use a template, like:

```<code>template<typename Type>
Type * read_column(char * file, int size_of_col)
{
    Type* col = (Type*) malloc(size_of_col * sizeof(Type));
    ...
    return(col);
}
</code>```

Then call as so:

```<code>int    * col_int    = read_column<int>   ("blah", 123);
float  * col_float  = read_column<float> ("blah", 123);
double * col_double = read_column<double>("blah", 123);
etc.
</code>```

Body:
I have seperate functions for reading from a text file (depending on whether its an int,  float or double). I would like just one function with an additional argument (without using a subsequent IF statement). Does anyone have ideas?

Below is the form of my current functions.

float * read_column_f (char * file, int size_of_col){
...
col = (float*) malloc (height_row * sizeof(float));
...  return(col);}

double *    read_column_d (char * file, int size_of_col){
...
col = (double*) malloc (height_row * sizeof(double));
...  return(col);}

int *   read_column_i (char * file, int size_of_col){
...
col = (int*) malloc (height_row * sizeof(int));
...  return(col);}

EDIT: I want to implement this in C++, the C-style syntax used is due to memory preference.

Body:
Use a template, like:

template<typename Type>
Type * read_column(char * file, int size_of_col)
{
    Type* col = (Type*) malloc(size_of_col * sizeof(Type));
    ...
    return(col);
}

Then call as so:

int    * col_int    = read_column<int>   ("blah", 123);
float  * col_float  = read_column<float> ("blah", 123);
double * col_double = read_column<double>("blah", 123);
etc.


问:
How is the comma-separated initializer of OpenCV Mat implemented with C++?
```<code>#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

int main() {
    Mat a = (Mat_<double>(3, 3) << 0, 1, 2, 3, 4, 5, 6, 7, 8);

    cout << a << endl;

    return 0;
}
</code>```

How is the comma-separated initializer of OpenCV Mat implemented with C++?

How does the "1" get into the Mat after the "0"?

答:
To allow an initialization like

```<code>Mat a = (Mat_<double>(3, 3) << 0, 1, 2, 3, 4, 5, 6, 7, 8);
</code>```

OpenCV first uses

```<code>template <typename T>
MatCommaInitializer_<T> operator<<(Mat_<T>&, T);
</code>```

to return an intermediate object MatCommaInitializer_<T>. This object has an overloaded operator,, namely

```<code>template <typename T2>
MatCommaInitializer_<T>& operator,(T2 v);
</code>```

which adds the value to the initializer. Then there is a constructor

```<code>template <typename T>
explicit Mat(MatCommaInitializer_<T> const&);
</code>```

to create a Mat object from a MatCommaInitializer.

Note: You can find such information in the OpenCV documentation http://docs.opencv.org/master/ (http://docs.opencv.org/master/d6/d9e/classcv_1_1MatCommaInitializer__.html).

Body:
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

int main() {
    Mat a = (Mat_<double>(3, 3) << 0, 1, 2, 3, 4, 5, 6, 7, 8);

    cout << a << endl;

    return 0;
}

How is the comma-separated initializer of OpenCV Mat implemented with C++?

How does the "1" get into the Mat after the "0"?

Body:
To allow an initialization like

Mat a = (Mat_<double>(3, 3) << 0, 1, 2, 3, 4, 5, 6, 7, 8);

OpenCV first uses

template <typename T>
MatCommaInitializer_<T> operator<<(Mat_<T>&, T);

to return an intermediate object MatCommaInitializer_<T>. This object has an overloaded operator,, namely

template <typename T2>
MatCommaInitializer_<T>& operator,(T2 v);

which adds the value to the initializer. Then there is a constructor

template <typename T>
explicit Mat(MatCommaInitializer_<T> const&);

to create a Mat object from a MatCommaInitializer.

Note: You can find such information in the OpenCV documentation http://docs.opencv.org/master/ (http://docs.opencv.org/master/d6/d9e/classcv_1_1MatCommaInitializer__.html).


问:
How do you disable a CComboBox in C++?
I've searched this extensively, and the answer I came up with about 20 times is to use CWnd::EnableWindow(FALSE). Currently, I have:

```<code>GetDlgItem(myComboBox)->EnableWindow(FALSE);
</code>```

Instead of disabling the ComboBox, now the entire Dialog doesn't show up, and since it's a modal dialog (or at least I'm guessing that's the reason), the entire program gets locked up because I can't close the dialog if it's not there.

Is there a way to disable editing to this box without making it disappear entirely; similar to what SetReadOnly() does for a CEdit?

Edit:
Suddenly, the syntax above started working the next morning. I'm still not entirely sure why it didn't work in the first place.

答:
It seems you are trying to call EnableWindow() from a different thread than the dialog's

You could try this, and see if it works for you:

```<code>GetDlgItem(myComboBox)->PostMessage(WM_ENABLE, (WPARAM)FALSE);
</code>```

Title: How do you disable a CComboBox in C++?

Body:
I've searched this extensively, and the answer I came up with about 20 times is to use CWnd::EnableWindow(FALSE). Currently, I have:

GetDlgItem(myComboBox)->EnableWindow(FALSE);

Instead of disabling the ComboBox, now the entire Dialog doesn't show up, and since it's a modal dialog (or at least I'm guessing that's the reason), the entire program gets locked up because I can't close the dialog if it's not there.

Is there a way to disable editing to this box without making it disappear entirely; similar to what SetReadOnly() does for a CEdit?

Edit:
Suddenly, the syntax above started working the next morning. I'm still not entirely sure why it didn't work in the first place.

Body:
It seems you are trying to call EnableWindow() from a different thread than the dialog's

You could try this, and see if it works for you:

GetDlgItem(myComboBox)->PostMessage(WM_ENABLE, (WPARAM)FALSE);


问:
SVG to android vector drawable
I'm looking for a tool that would translate my svg images to android vector drawable assets. Right now I have to convert my assets one by one by clicking new vector asset -> searching in the folder -> selecting correct svg.
Is there a tool that I could use in a script that would translate all my svg's to android vector drawables(xml)?</p>

答:
Android Studio by default provides tool to convert svg image to vector drawables.
Here are the steps:
File -> New -> Vector Asset
After that, lot of there will be option from where you can select your local svg and it will be converted to vector drawable.</p>

Title: SVG to android vector drawable


问:
SQL: No Sub-Query but only Joins
I am trying to find an alternative to this query where no sub-select is present but only joins (left, right, inner etc).

```<code>select count(SC.NUMBER_C)
from FNQP2PORTAL.SA.SEC_CAS SC
where SC.NUMBER_C not in (
select E.Reference from
FNQP2HQ.dbo.Entities E
join FNQP2HQ.dbo.Classes C on C.ID = E.ClassID
where C.Reference =  'Assembly case')
</code>```

So, it should be something like...

```<code>select count(SC.NUMBER_C)
from FNQP2PORTAL.SA.SEC_CAS SC
left join  FNQP2HQ.dbo.Entities E on E.Reference = SC.NUMBER_C and E.Reference IS NULL
inner join FNQP2HQ.dbo.Classes C on C.ID = E.ClassID and C.Reference =  'Assembly case'
</code>```

Can somebody help me here?

答:
```<code>select count(SC.NUMBER_C)
from FNQP2PORTAL.SA.SEC_CAS SC
INNER JOIN FNQP2HQ.dbo.Entities E on SC.NUMBER_C = E.Reference
INNER JOIN FNQP2HQ.dbo.Classes C on C.ID = E.ClassID
where C.Reference =  'Assembly case'
</code>```

Title: SQL: No Sub-Query but only Joins

Body:
I am trying to find an alternative to this query where no sub-select is present but only joins (left, right, inner etc).

select count(SC.NUMBER_C)
from FNQP2PORTAL.SA.SEC_CAS SC
where SC.NUMBER_C not in (
select E.Reference from
FNQP2HQ.dbo.Entities E
join FNQP2HQ.dbo.Classes C on C.ID = E.ClassID
where C.Reference =  'Assembly case')

So, it should be something like...

select count(SC.NUMBER_C)
from FNQP2PORTAL.SA.SEC_CAS SC
left join  FNQP2HQ.dbo.Entities E on E.Reference = SC.NUMBER_C and E.Reference IS NULL
inner join FNQP2HQ.dbo.Classes C on C.ID = E.ClassID and C.Reference =  'Assembly case'

Can somebody help me here?


问:
javascript help me fix my first hands on code
help me fix this, simple convert to roman numerals code. with two input box, first where i input a number, 2nd box where the result will be shown. and a submit button

result wont show up on 2nd box after hitting convert/submit button

js code:

    function toRoman(){
 var num = document.getElementById('num').value;
 var result = "";
 var db = { 'M':1000, 'CM':900,'D':500,'CD':400, 'C':100, 'XC':90, 'L':50, 'XL':40, 'X':10, 'IX':9, 'V':5, 'IV':4, 'I':1 };
 for(var i in db){
  var m = parseInt(num/db[i]);
  result = i.repeat(m);
  num = num%db[i];
 }
 return result;
 document.getElementById('result').value = result;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>
    <body>

    <label for="num">Number</label><br/>
    <input type="Number" name="num" id="num"><br/><br/>
    <label for="result">Result</label><br/>
    <textarea id="result" name="result"></textarea><br/><br/>
    <input type="submit" id="submit" value="Convert!" onclick="toRoman()">

    <script src="toRoman.js"></script>
    </body>
    </code>```

答:
Only after going through the comments I realized what your problem was, which isn't a good practise to ask questions on Stack Overflow.

Anyway, your code has no reference to the element with the id 'result'. The last statement that you have will never get fired because it is after the return statement, so it will probably give an error saying 'code unreachable' in the debugger.

Instead of return result; you should have something like:

document.getElementById('result').value = result;

Or, you can keep your return statement but move this line move above it. So the final structure will be something like

```<code>document.getElementById('result').value = result;
return result;
</code>```

Body:
help me fix this, simple convert to roman numerals code. with two input box, first where i input a number, 2nd box where the result will be shown. and a submit button

result wont show up on 2nd box after hitting convert/submit button

js code:

    function toRoman(){
 var num = document.getElementById('num').value;
 var result = "";
 var db = { 'M':1000, 'CM':900,'D':500,'CD':400, 'C':100, 'XC':90, 'L':50, 'XL':40, 'X':10, 'IX':9, 'V':5, 'IV':4, 'I':1 };
 for(var i in db){
  var m = parseInt(num/db[i]);
  result = i.repeat(m);
  num = num%db[i];
 }
 return result;
 document.getElementById('result').value = result;
    }

    Number

    <input type="Number" name="num" id="num">

    Result

    <textarea id="result" name="result"></textarea>

    <input type="submit" id="submit" value="Convert!" onclick="toRoman()">

Body:
Only after going through the comments I realized what your problem was, which isn't a good practise to ask questions on Stack Overflow.

Anyway, your code has no reference to the element with the id 'result'. The last statement that you have will never get fired because it is after the return statement, so it will probably give an error saying 'code unreachable' in the debugger.

Instead of return result; you should have something like:

document.getElementById('result').value = result;

Or, you can keep your return statement but move this line move above it. So the final structure will be something like

document.getElementById('result').value = result;
return result;


问:
How to bring back removed spaces from a string
I have windows form application that encrypt the string and decrypt
it back using Caesar Algorithm. When encrypting a string I have to remove spaces from it ,but when I'll decrypt it again I should bring back the removed spaces into their actual places.

The problem I faced in this case is in bringing the removed spaces from the encrypted string and also when decrypting there are some letters are changed into special characters like this pattern where the encryption key is 3:

Plain text: My name is Shafaq Zahir

Encrypted text: PbqdphlvVkdidtCdklu

Decrypted text: M_nameisShafaq@ahir

This is my code

```<code>class CaesarAlgorithm
    {
        public string Encrypt(string pt,int key)
        {
            char[] buffer = pt.Replace(" ",string.Empty).ToCharArray();
            //char[] buffer = pt.ToCharArray();
            for(int i=0;i<buffer.Length;i++)
            {
                if (buffer[i] >= 'a' && buffer[i] <= 'z')
                {
                    buffer[i] = (char)(buffer[i] + key);
                    if (buffer[i] > 'z')
                    {
                        buffer[i] = (char)(buffer[i] - 26);
                    }
                }
                else if (buffer[i] >= 'A' && buffer[i] <= 'Z')
                {
                    buffer[i] = (char)(buffer[i] + key);
                    if (buffer[i] > 'Z')
                    {
                        buffer[i] = (char)(buffer[i] - 26);
                    }
                }
            }

            return new string (buffer);

        }

        public string Decrypt(string pt,int key)
        {
            char[] buffer = pt.ToCharArray();
            for (int i = 0; i < buffer.Length; i++)
            {
                if (buffer[i] >= 'a' && buffer[i] <= 'z')
                {
                    buffer[i] = (char)(buffer[i] - key);
                    if (buffer[i] > 'z')
                    {
                        buffer[i] = (char)(buffer[i] - 26);
                    }
                }
                else if (buffer[i] >= 'A' && buffer[i] <= 'Z')
                {
                    buffer[i] = (char)(buffer[i] - key);
                    if (buffer[i] > 'Z')
                    {
                        buffer[i] = (char)(buffer[i] - 26);
                    }
                }
            }

            return new string(buffer);
        }
    }
}
</code>```

答: The only thing I can think of right would be to loop through the original char array and save the index of each space then add it back the end, kinda just woke up so there's probably a better solution. Also just wondering why you can't have spaces </p>

Body:
I have windows form application that encrypt the string and decrypt
it back using Caesar Algorithm. When encrypting a string I have to remove spaces from it ,but when I'll decrypt it again I should bring back the removed spaces into their actual places.

The problem I faced in this case is in bringing the removed spaces from the encrypted string and also when decrypting there are some letters are changed into special characters like this pattern where the encryption key is 3:

Plain text: My name is Shafaq Zahir

Encrypted text: PbqdphlvVkdidtCdklu

Decrypted text: M_nameisShafaq@ahir

This is my code

class CaesarAlgorithm
    {
        public string Encrypt(string pt,int key)
        {
            char[] buffer = pt.Replace(" ",string.Empty).ToCharArray();
            //char[] buffer = pt.ToCharArray();
            for(int i=0;i<buffer.Length;i++)
            {
                if (buffer[i] >= 'a' && buffer[i] <= 'z')
                {
                    buffer[i] = (char)(buffer[i] + key);
                    if (buffer[i] > 'z')
                    {
                        buffer[i] = (char)(buffer[i] - 26);
                    }
                }
                else if (buffer[i] >= 'A' && buffer[i] <= 'Z')
                {
                    buffer[i] = (char)(buffer[i] + key);
                    if (buffer[i] > 'Z')
                    {
                        buffer[i] = (char)(buffer[i] - 26);
                    }
                }
            }

            return new string (buffer);

        }

        public string Decrypt(string pt,int key)
        {
            char[] buffer = pt.ToCharArray();
            for (int i = 0; i < buffer.Length; i++)
            {
                if (buffer[i] >= 'a' && buffer[i] <= 'z')
                {
                    buffer[i] = (char)(buffer[i] - key);
                    if (buffer[i] > 'z')
                    {
                        buffer[i] = (char)(buffer[i] - 26);
                    }
                }
                else if (buffer[i] >= 'A' && buffer[i] <= 'Z')
                {
                    buffer[i] = (char)(buffer[i] - key);
                    if (buffer[i] > 'Z')
                    {
                        buffer[i] = (char)(buffer[i] - 26);
                    }
                }
            }

            return new string(buffer);
        }
    }
}


问:
Ensuring Express App is running before each Mocha Test
I am working on developing a REST API using ExpressJS, NodeJS, Mongoose and Mocha.

The thing is that I have an app.coffee file, thats responsible for setting up ExpressJS and connecting to Mongoose. The way I have set this up is that Mongoose is connected first and if that gets through, then, the ExpressJS App is started.

The issue is that when setting up Mocha, I need to make sure that ExpressJS App existing in app.coffee is completely started successfully including all asynchronous code before any testcase is executed.

For that, I have created a test_helper.coffee and placed the following code in it, but, the testcases start their execution even if the code in app.coffee hasn't completed its execution completely which actually makes sense:

```<code>before (done) ->
  require(__dirname + '/../src/app')
  done()
</code>```

In a nutshell, I want to make sure that the ExpressJS app has fully completed its setup before any testcase is executed.

How I can do that?

答:
The app.listen method takes a callback that runs when everything is ready. So, you need to be able to pass the done callback there. Something like</p>

```<code>before (done) ->
  var app = require(__dirname + '/../src/app')
  app.listen(3000, done)
</code>```

Body:
I am working on developing a REST API using ExpressJS, NodeJS, Mongoose and Mocha.

The thing is that I have an app.coffee file, thats responsible for setting up ExpressJS and connecting to Mongoose. The way I have set this up is that Mongoose is connected first and if that gets through, then, the ExpressJS App is started.

The issue is that when setting up Mocha, I need to make sure that ExpressJS App existing in app.coffee is completely started successfully including all asynchronous code before any testcase is executed.

For that, I have created a test_helper.coffee and placed the following code in it, but, the testcases start their execution even if the code in app.coffee hasn't completed its execution completely which actually makes sense:

before (done) ->
  require(__dirname + '/../src/app')
  done()

In a nutshell, I want to make sure that the ExpressJS app has fully completed its setup before any testcase is executed.

How I can do that?

Body:
The app.listen method takes a callback that runs when everything is ready. So, you need to be able to pass the done callback there. Something like

before (done) ->
  var app = require(__dirname + '/../src/app')
  app.listen(3000, done)


问:
Permutations with repetition without two consecutive equal elements
I need a function that generates all the permutation with repetition of an iterable with the clause that two consecutive elements must be different; for example

```<code>f([0,1],3).sort()==[(0,1,0),(1,0,1)]
#or
f([0,1],3).sort()==[[0,1,0],[1,0,1]]
#I don't need the elements in the list to be sorted.
#the elements of the return can be tuples or lists, it doesn't change anything
</code>```

Unfortunatly itertools.permutation doesn't work for what I need (each element in the iterable is present once or no times in the return)

I've tried a bunch of definitions; first, filterting elements from itertools.product(iterable,repeat=r) input, but is too slow for what I need.

```<code>from itertools import product
def crp0(iterable,r):
l=[]
for f in product(iterable,repeat=r):
    #print(f)
    b=True
    last=None #supposing no element of the iterable is None, which is fine for me
    for element in f:
        if element==last:
            b=False
            break
        last=element
    if b: l.append(f)
return l
</code>```

Second, I tried to build r for cycle, one inside the other (where r is the class of the permutation, represented as k in math).

```<code>def crp2(iterable,r):
    a=list(range(0,r))
    s="\n"
    tab="    " #4 spaces
    l=[]
    for i in a:
        s+=(2*i*tab+"for a["+str(i)+"] in iterable:\n"+
        (2*i+1)*tab+"if "+str(i)+"==0 or a["+str(i)+"]!=a["+str(i-1)+"]:\n")
    s+=(2*i+2)*tab+"l.append(a.copy())"
    exec(s)
    return l
</code>```

I know, there's no need you remember me: exec is ugly, exec can be dangerous, exec isn't easy-readable... I know.
To understand better the function I suggest you to replace exec(s) with print(s).

I give you an example of what string is inside the exec for crp([0,1],2):

```<code>for a[0] in iterable:
    if 0==0 or a[0]!=a[-1]:
        for a[1] in iterable:
            if 1==0 or a[1]!=a[0]:
                l.append(a.copy())
</code>```

But, apart from using exec, I need a better functions because crp2 is still too slow (even if faster than crp0); there's any way to recreate the code with r for without using exec? There's any other way to do what I need?

答:
I agree with @EricDuminil's comment that you do not want "Permutations with repetition." You want a significant subset of the product of the iterable with itself multiple times. I don't know what name is best: I'll just call them products.

Here is an approach that builds each product line without building all the products then filtering out the ones you want. My approach is to work primarily with the indices of the iterable rather than the iterable itself--and not all the indices, but ignoring the last one. So instead of working directly with [2, 3, 5, 7] I work with [0, 1, 2]. Then I work with the products of those indices. I can transform a product such as [1, 2, 2] where r=3 by comparing each index with the previous one. If an index is greater than or equal to the previous one I increment the current index by one. This prevents two indices from being equal, and this also gets be back to using all the indices. So [1, 2, 2] is transformed to [1, 2, 3] where the final 2 was changed to a 3. I now use those indices to select the appropriate items from the iterable, so the iterable [2, 3, 5, 7] with r=3 gets the line [3, 5, 7]. The first index is treated differently, since it has no previous index. My code is:

```<code>from itertools import product

def crp3(iterable, r):
    L = []
    for k in range(len(iterable)):
        for f in product(range(len(iterable)-1), repeat=r-1):
            ndx = k
            a = [iterable[ndx]]
            for j in range(r-1):
                ndx = f[j] if f[j] < ndx else f[j] + 1
                a.append(iterable[ndx])
            L.append(a)
    return L
</code>```

Using %timeit in my Spyder/IPython configuration on crp3([0,1], 3) shows 8.54 µs per loop while your crp2([0,1], 3) shows 133 µs per loop. That shows a sizeable speed improvement! My routine works best where iterable is short and r is large--your routine finds len ** r lines (where len is the length of the iterable) and filters them while mine finds len * (len-1) ** (r-1) lines without filtering.

By the way, your crp2() does do filtering, as shown by the if lines in your code that is execed. The sole if in my code does not filter a line, it modifies an item in the line. My code does return surprising results if the items in the iterable are not unique: if that is a problem, just change the iterable to a set to remove the duplicates. Note that I replaced your l name with L: I think l is too easy to confuse with 1 or I and should be avoided. My code could easily be changed to a generator: replace L.append(a) with yield a and remove the lines L = [] and return L.

Body:
I need a function that generates all the permutation with repetition of an iterable with the clause that two consecutive elements must be different; for example

f([0,1],3).sort()==[(0,1,0),(1,0,1)]
#or
f([0,1],3).sort()==[[0,1,0],[1,0,1]]
#I don't need the elements in the list to be sorted.
#the elements of the return can be tuples or lists, it doesn't change anything

Unfortunatly itertools.permutation doesn't work for what I need (each element in the iterable is present once or no times in the return)

I've tried a bunch of definitions; first, filterting elements from itertools.product(iterable,repeat=r) input, but is too slow for what I need.

from itertools import product
def crp0(iterable,r):
l=[]
for f in product(iterable,repeat=r):
    #print(f)
    b=True
    last=None #supposing no element of the iterable is None, which is fine for me
    for element in f:
        if element==last:
            b=False
            break
        last=element
    if b: l.append(f)
return l

Second, I tried to build r for cycle, one inside the other (where r is the class of the permutation, represented as k in math).

def crp2(iterable,r):
    a=list(range(0,r))
    s="\n"
    tab="    " #4 spaces
    l=[]
    for i in a:
        s+=(2*i*tab+"for a["+str(i)+"] in iterable:\n"+
        (2*i+1)*tab+"if "+str(i)+"==0 or a["+str(i)+"]!=a["+str(i-1)+"]:\n")
    s+=(2*i+2)*tab+"l.append(a.copy())"
    exec(s)
    return l

I know, there's no need you remember me: exec is ugly, exec can be dangerous, exec isn't easy-readable... I know.
To understand better the function I suggest you to replace exec(s) with print(s).

I give you an example of what string is inside the exec for crp([0,1],2):

for a[0] in iterable:
    if 0==0 or a[0]!=a[-1]:
        for a[1] in iterable:
            if 1==0 or a[1]!=a[0]:
                l.append(a.copy())

But, apart from using exec, I need a better functions because crp2 is still too slow (even if faster than crp0); there's any way to recreate the code with r for without using exec? There's any other way to do what I need?

Body:
I agree with @EricDuminil's comment that you do not want "Permutations with repetition." You want a significant subset of the product of the iterable with itself multiple times. I don't know what name is best: I'll just call them products.

Here is an approach that builds each product line without building all the products then filtering out the ones you want. My approach is to work primarily with the indices of the iterable rather than the iterable itself--and not all the indices, but ignoring the last one. So instead of working directly with [2, 3, 5, 7] I work with [0, 1, 2]. Then I work with the products of those indices. I can transform a product such as [1, 2, 2] where r=3 by comparing each index with the previous one. If an index is greater than or equal to the previous one I increment the current index by one. This prevents two indices from being equal, and this also gets be back to using all the indices. So [1, 2, 2] is transformed to [1, 2, 3] where the final 2 was changed to a 3. I now use those indices to select the appropriate items from the iterable, so the iterable [2, 3, 5, 7] with r=3 gets the line [3, 5, 7]. The first index is treated differently, since it has no previous index. My code is:

from itertools import product

def crp3(iterable, r):
    L = []
    for k in range(len(iterable)):
        for f in product(range(len(iterable)-1), repeat=r-1):
            ndx = k
            a = [iterable[ndx]]
            for j in range(r-1):
                ndx = f[j] if f[j] < ndx else f[j] + 1
                a.append(iterable[ndx])
            L.append(a)
    return L

Using %timeit in my Spyder/IPython configuration on crp3([0,1], 3) shows 8.54 µs per loop while your crp2([0,1], 3) shows 133 µs per loop. That shows a sizeable speed improvement! My routine works best where iterable is short and r is large--your routine finds len ** r lines (where len is the length of the iterable) and filters them while mine finds len * (len-1) ** (r-1) lines without filtering.

By the way, your crp2() does do filtering, as shown by the if lines in your code that is execed. The sole if in my code does not filter a line, it modifies an item in the line. My code does return surprising results if the items in the iterable are not unique: if that is a problem, just change the iterable to a set to remove the duplicates. Note that I replaced your l name with L: I think l is too easy to confuse with 1 or I and should be avoided. My code could easily be changed to a generator: replace L.append(a) with yield a and remove the lines L = [] and return L.


问:
Centering an image within a slick slider
I have set my images so that they overflow the div that contains them which is exactly what I want, but I want the images to be centered vertically on all browsers at the moment them just overflow at the bottom. I have tried to use transform to do this with no luck. Any ideas? Sorry but I can't attach the full code as it is too long, so I will just post a small part so that I can add my codepen link. Please go to my codepen demo. https://codepen.io/Reece_Dev/pen/OgZGvJ

Head

```

答:
you can give a try at the flex display properties:
https://css-tricks.com/snippets/css/a-guide-to-flexbox/

```<code>.carousel{
  display:flex!important;/* overrides previous values or set via js */
  align-items:center;/* that's where centering happens and overflows on both sides */
}
</code>```

https://codepen.io/gc-nomade/pen/MoXZve

$(document).ready(function() {
    $('.carousel').slick({
        slidesToShow: 1,
    });
  }); ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body,
p {
  padding: 0;
  margin: 0;
}

#head {
  width: 100%;
  background-color: blue;
}

p {
  font-size: 40px;
  color: white;
}

.carousel {
  width: 100vw;
  overflow: hidden;
  max-width: 1000px;
  max-height: 400px;
  margin: 0 auto;
  display: flex!important;
  align-items: center;
}

.carousel div img {
  width: 100%;
}

/* Slick Slider */

.slick-slider {
  position: relative;
  display: block;
  box-sizing: border-box;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  -webkit-touch-callout: none;
  -khtml-user-select: none;
  -ms-touch-action: pan-y;
  touch-action: pan-y;
  -webkit-tap-highlight-color: transparent;
}

.slick-list {
  position: relative;
  display: block;
  overflow: hidden;
  margin: 0;
  padding: 0;
}

.slick-list:focus {
  outline: none;
}

.slick-list.dragging {
  cursor: pointer;
  cursor: hand;
}

.slick-slider .slick-track,
.slick-slider .slick-list {
  -webkit-transform: translate3d(0, 0, 0);
  -moz-transform: translate3d(0, 0, 0);
  -ms-transform: translate3d(0, 0, 0);
  -o-transform: translate3d(0, 0, 0);
  transform: translate3d(0, 0, 0);
}

.slick-track {
  position: relative;
  top: 0;
  left: 0;
  display: block;
}

.slick-track:before,
.slick-track:after {
  display: table;
  content: '';
}

.slick-track:after {
  clear: both;
}

.slick-loading .slick-track {
  visibility: hidden;
}

.slick-slide {
  display: none;
  float: left;
  height: 100%;
  min-height: 1px;
}

[dir='rtl'] .slick-slide {
  float: right;
}

.slick-slide img {
  display: block;
}

.slick-slide.slick-loading img {
  display: none;
}

.slick-slide.dragging img {
  pointer-events: none;
}

.slick-initialized .slick-slide {
  display: block;
}

.slick-loading .slick-slide {
  visibility: hidden;
}

.slick-vertical .slick-slide {
  display: block;
  height: auto;
  border: 1px solid transparent;
}

.slick-arrow.slick-hidden {
  display: none;
}

@charset 'UTF-8';

/* Slider */

.slick-loading .slick-list {
  background: #fff url('./ajax-loader.gif') center center no-repeat;
}

/* Icons */

@font-face {
  font-family: 'slick';
  font-weight: normal;
  font-style: normal;
  src: url('./fonts/slick.eot');
  src: url('./fonts/slick.eot?#iefix') format('embedded-opentype'), url('./fonts/slick.woff') format('woff'), url('./fonts/slick.ttf') format('truetype'), url('./fonts/slick.svg#slick') format('svg');
}

/* Arrows */

.slick-prev,
.slick-next {
  font-size: 0;
  line-height: 0;
  position: absolute;
  top: 50%;
  display: block;
  width: 20px;
  height: 20px;
  padding: 0;
  -webkit-transform: translate(0, -50%);
  -ms-transform: translate(0, -50%);
  transform: translate(0, -50%);
  cursor: pointer;
  color: transparent;
  border: none;
  outline: none;
  background: transparent;
}

.slick-prev:hover,
.slick-prev:focus,
.slick-next:hover,
.slick-next:focus {
  color: transparent;
  outline: none;
  background: transparent;
}

.slick-prev:hover:before,
.slick-prev:focus:before,
.slick-next:hover:before,
.slick-next:focus:before {
  opacity: 1;
}

.slick-prev.slick-disabled:before,
.slick-next.slick-disabled:before {
  opacity: .25;
}

.slick-prev:before,
.slick-next:before {
  font-family: 'slick';
  font-size: 20px;
  line-height: 1;
  opacity: .75;
  color: white;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.slick-prev {
  left: -25px;
}

[dir='rtl'] .slick-prev {
  right: -25px;
  left: auto;
}

.slick-prev:before {
  content: '←';
}

[dir='rtl'] .slick-prev:before {
  content: '→';
}

.slick-next {
  right: -25px;
}

[dir='rtl'] .slick-next {
  right: auto;
  left: -25px;
}

.slick-next:before {
  content: '→';
}

[dir='rtl'] .slick-next:before {
  content: '←';
}

/* Dots */

.slick-dotted.slick-slider {
  margin-bottom: 30px;
}

.slick-dots {
  position: absolute;
  bottom: -25px;
  display: block;
  width: 100%;
  padding: 0;
  margin: 0;
  list-style: none;
  text-align: center;
}

.slick-dots li {
  position: relative;
  display: inline-block;
  width: 20px;
  height: 20px;
  margin: 0 5px;
  padding: 0;
  cursor: pointer;
}

.slick-dots li button {
  font-size: 0;
  line-height: 0;
  display: block;
  width: 20px;
  height: 20px;
  padding: 5px;
  cursor: pointer;
  color: transparent;
  border: 0;
  outline: none;
  background: transparent;
}

.slick-dots li button:hover,
.slick-dots li button:focus {
  outline: none;
}

.slick-dots li button:hover:before,
.slick-dots li button:focus:before {
  opacity: 1;
}

.slick-dots li button:before {
  font-family: 'slick';
  font-size: 6px;
  line-height: 20px;
  position: absolute;
  top: 0;
  left: 0;
  width: 20px;
  height: 20px;
  content: '•';
  text-align: center;
  opacity: .25;
  color: black;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.slick-dots li.slick-active button:before {
  opacity: .75;
  color: black;
}</code>```

Head

```

Body:
you can give a try at the flex display properties:
https://css-tricks.com/snippets/css/a-guide-to-flexbox/

.carousel{
  display:flex!important;/* overrides previous values or set via js */
  align-items:center;/* that's where centering happens and overflows on both sides */
}

https://codepen.io/gc-nomade/pen/MoXZve

$(document).ready(function() {
    $('.carousel').slick({
        slidesToShow: 1,
    });
  });

html,
body,
p {
  padding: 0;
  margin: 0;
}

#head {
  width: 100%;
  background-color: blue;
}

p {
  font-size: 40px;
  color: white;
}

.carousel {
  width: 100vw;
  overflow: hidden;
  max-width: 1000px;
  max-height: 400px;
  margin: 0 auto;
  display: flex!important;
  align-items: center;
}

.carousel div img {
  width: 100%;
}

/* Slick Slider */

.slick-slider {
  position: relative;
  display: block;
  box-sizing: border-box;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  -webkit-touch-callout: none;
  -khtml-user-select: none;
  -ms-touch-action: pan-y;
  touch-action: pan-y;
  -webkit-tap-highlight-color: transparent;
}

.slick-list {
  position: relative;
  display: block;
  overflow: hidden;
  margin: 0;
  padding: 0;
}

.slick-list:focus {
  outline: none;
}

.slick-list.dragging {
  cursor: pointer;
  cursor: hand;
}

.slick-slider .slick-track,
.slick-slider .slick-list {
  -webkit-transform: translate3d(0, 0, 0);
  -moz-transform: translate3d(0, 0, 0);
  -ms-transform: translate3d(0, 0, 0);
  -o-transform: translate3d(0, 0, 0);
  transform: translate3d(0, 0, 0);
}

.slick-track {
  position: relative;
  top: 0;
  left: 0;
  display: block;
}

.slick-track:before,
.slick-track:after {
  display: table;
  content: '';
}

.slick-track:after {
  clear: both;
}

.slick-loading .slick-track {
  visibility: hidden;
}

.slick-slide {
  display: none;
  float: left;
  height: 100%;
  min-height: 1px;
}

[dir='rtl'] .slick-slide {
  float: right;
}

.slick-slide img {
  display: block;
}

.slick-slide.slick-loading img {
  display: none;
}

.slick-slide.dragging img {
  pointer-events: none;
}

.slick-initialized .slick-slide {
  display: block;
}

.slick-loading .slick-slide {
  visibility: hidden;
}

.slick-vertical .slick-slide {
  display: block;
  height: auto;
  border: 1px solid transparent;
}

.slick-arrow.slick-hidden {
  display: none;
}

@charset 'UTF-8';

/* Slider */

.slick-loading .slick-list {
  background: #fff url('./ajax-loader.gif') center center no-repeat;
}

/* Icons */

@font-face {
  font-family: 'slick';
  font-weight: normal;
  font-style: normal;
  src: url('./fonts/slick.eot');
  src: url('./fonts/slick.eot?#iefix') format('embedded-opentype'), url('./fonts/slick.woff') format('woff'), url('./fonts/slick.ttf') format('truetype'), url('./fonts/slick.svg#slick') format('svg');
}

/* Arrows */

.slick-prev,
.slick-next {
  font-size: 0;
  line-height: 0;
  position: absolute;
  top: 50%;
  display: block;
  width: 20px;
  height: 20px;
  padding: 0;
  -webkit-transform: translate(0, -50%);
  -ms-transform: translate(0, -50%);
  transform: translate(0, -50%);
  cursor: pointer;
  color: transparent;
  border: none;
  outline: none;
  background: transparent;
}

.slick-prev:hover,
.slick-prev:focus,
.slick-next:hover,
.slick-next:focus {
  color: transparent;
  outline: none;
  background: transparent;
}

.slick-prev:hover:before,
.slick-prev:focus:before,
.slick-next:hover:before,
.slick-next:focus:before {
  opacity: 1;
}

.slick-prev.slick-disabled:before,
.slick-next.slick-disabled:before {
  opacity: .25;
}

.slick-prev:before,
.slick-next:before {
  font-family: 'slick';
  font-size: 20px;
  line-height: 1;
  opacity: .75;
  color: white;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.slick-prev {
  left: -25px;
}

[dir='rtl'] .slick-prev {
  right: -25px;
  left: auto;
}

.slick-prev:before {
  content: '←';
}

[dir='rtl'] .slick-prev:before {
  content: '→';
}

.slick-next {
  right: -25px;
}

[dir='rtl'] .slick-next {
  right: auto;
  left: -25px;
}

.slick-next:before {
  content: '→';
}

[dir='rtl'] .slick-next:before {
  content: '←';
}

/* Dots */

.slick-dotted.slick-slider {
  margin-bottom: 30px;
}

.slick-dots {
  position: absolute;
  bottom: -25px;
  display: block;
  width: 100%;
  padding: 0;
  margin: 0;
  list-style: none;
  text-align: center;
}

.slick-dots li {
  position: relative;
  display: inline-block;
  width: 20px;
  height: 20px;
  margin: 0 5px;
  padding: 0;
  cursor: pointer;
}

.slick-dots li button {
  font-size: 0;
  line-height: 0;
  display: block;
  width: 20px;
  height: 20px;
  padding: 5px;
  cursor: pointer;
  color: transparent;
  border: 0;
  outline: none;
  background: transparent;
}

.slick-dots li button:hover,
.slick-dots li button:focus {
  outline: none;
}

.slick-dots li button:hover:before,
.slick-dots li button:focus:before {
  opacity: 1;
}

.slick-dots li button:before {
  font-family: 'slick';
  font-size: 6px;
  line-height: 20px;
  position: absolute;
  top: 0;
  left: 0;
  width: 20px;
  height: 20px;
  content: '•';
  text-align: center;
  opacity: .25;
  color: black;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.slick-dots li.slick-active button:before {
  opacity: .75;
  color: black;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://kenwheeler.github.io/slick/slick/slick.js"></script>
<div id="head">
  <p>Head</p>
</div>

<div class="carousel">
  <div><img src="http://fyberproperty.co.uk/wp-content/uploads/2017/07/stairs_one1200-1-1024x512.png" /></div>
  <div><img src="http://fyberproperty.co.uk/wp-content/uploads/2017/07/stairs_two1200-1024x512.png" /></div>
</div>


问:
How to delete duplicates, but aggregating sums of repeated rows (Python or Excel)
For example, I have a Symbol and Quantity columns.

```<code>AAA 1000000
AAA 1000000
AAA 1000000
BBB 5000000
CCC 1000000
CCC 1000000
</code>```

To essentially look like

```<code>AAA 3000000
BBB 5500000
CCC 2000000
</code>```

Attempt after Rayhane's suggestion:

```<code>import pandas as pd
a = pd.read_csv("file.csv")
df = pd.DataFrame(a)
df['Quantity'] = df.groupby(['Symbol']).transform('sum')
df.drop_duplicates(inplace=True)
</code>```

What's weird is that it looks like the code worked, but the number of rows remain the same. (5000 lines, I would've expected it to drop to something like 2000). Can someone verify my code?

答:
here you can do this:

```<code>df['Quantity'] = df.groupby(['Symbol']).transform('sum')
df.drop_duplicates(inplace=True)
</code>```

documentation:

transform

groupby

drop_duplicates

input:

```<code>  Symbol  Quantity
0    AAA   1000000
1    AAA   1000000
2    AAA   1000000
3    BBB   5000000
4    CCC   1000000
5    CCC   1000000
</code>```

now if you print(df):

```<code>  Symbol  Quantity
0    AAA   3000000
3    BBB   5000000
4    CCC   2000000
</code>```

you can even reset the index if you want:

```<code>df.reset_index(drop=True,inplace=True)
</code>```

output becomes:

```<code>  Symbol  Quantity
0    AAA   3000000
1    BBB   5000000
2    CCC   2000000
</code>```

Body:
For example, I have a Symbol and Quantity columns.

AAA 1000000
AAA 1000000
AAA 1000000
BBB 5000000
CCC 1000000
CCC 1000000

To essentially look like

AAA 3000000
BBB 5500000
CCC 2000000

Attempt after Rayhane's suggestion:

import pandas as pd
a = pd.read_csv("file.csv")
df = pd.DataFrame(a)
df['Quantity'] = df.groupby(['Symbol']).transform('sum')
df.drop_duplicates(inplace=True)

What's weird is that it looks like the code worked, but the number of rows remain the same. (5000 lines, I would've expected it to drop to something like 2000). Can someone verify my code?

Body:
here you can do this:

df['Quantity'] = df.groupby(['Symbol']).transform('sum')
df.drop_duplicates(inplace=True)

documentation:

transform

groupby

drop_duplicates

input:

  Symbol  Quantity
0    AAA   1000000
1    AAA   1000000
2    AAA   1000000
3    BBB   5000000
4    CCC   1000000
5    CCC   1000000

now if you print(df):

  Symbol  Quantity
0    AAA   3000000
3    BBB   5000000
4    CCC   2000000

you can even reset the index if you want:

df.reset_index(drop=True,inplace=True)

output becomes:

  Symbol  Quantity
0    AAA   3000000
1    BBB   5000000
2    CCC   2000000


问:
Loop list while adding to it
I've built my system in c-sharp (winforms) and I've run into a problem. In my view - my graphical interface - I'm starting a pretty heavy algorithm, which in each loop adds a result to a list in my view. The algorithm runs in a presenter (MVP pattern), using a backgroundworker - enabling the view not to freeze. As I said before, the algorithm runs in a loop, and since it's so heavy, I want to process the results of the algorithm as they come in.

View:

```<code>...
public List<string> Results { get; }
...
_presenter.RunAlgorithmAsync();
//Start processing results
...
</code>```

Backgroundworker in presenter:

```<code>...
_view.Results.Add(result);
...
</code>```

To sum it up, how can I start processing the list while the backgroundworker adds to it? Of course, the backgroundworker can work faster than the processing of the list, and vice versa - the processing may have to wait for results to arrive to the list, and the list need to be able up build up a stack of results.

I realize this question may be blurry, but if you ask me questions, I'm sure I can define the problem better.

答: Use a queue and have the two threads treat it as a producer and consumer.</p>

Title: Loop list while adding to it

Body:
I've built my system in c-sharp (winforms) and I've run into a problem. In my view - my graphical interface - I'm starting a pretty heavy algorithm, which in each loop adds a result to a list in my view. The algorithm runs in a presenter (MVP pattern), using a backgroundworker - enabling the view not to freeze. As I said before, the algorithm runs in a loop, and since it's so heavy, I want to process the results of the algorithm as they come in.

View:

...
public List<string> Results { get; }
...
_presenter.RunAlgorithmAsync();
//Start processing results
...

Backgroundworker in presenter:

...
_view.Results.Add(result);
...

To sum it up, how can I start processing the list while the backgroundworker adds to it? Of course, the backgroundworker can work faster than the processing of the list, and vice versa - the processing may have to wait for results to arrive to the list, and the list need to be able up build up a stack of results.

I realize this question may be blurry, but if you ask me questions, I'm sure I can define the problem better.


问:
Azure Web App deploy: Web Deploy cannot modify the file on the destination because it is locked by an external process
I am using the "Azure Web App Deployment" build step in VSTS to publish an ASP.NET Core API to an Azure Web App:

Occasionally, this step breaks with the following error:

[error]Microsoft.Web.Deployment.DeploymentDetailedClientServerException:
  Web Deploy cannot modify the file 'MyProject.Api.exe' on the
  destination because it is locked by an external process.  In order to
  allow the publish operation to succeed, you may need to either restart
  your application to release the lock, or use the AppOffline rule
  handler for .Net applications on your next publish attempt.  Learn
  more at:
  http://go.microsoft.com/fwlink/?LinkId=221672#ERROR_FILE_IN_USE.

This GitHub issue raises the same issue, but there is no suggested solution using the Azure Web App Deployment build step.

答:
I was struggling with the same locking issue.

There are now a new Tasks (in Preview) that you can add for starting and stopping the App Service:

Add a stop task before deployment and a start task after the deployment.

This did the trick for me.