问:
C++ Concatenate containers of polymorphic objects
Assume I have a virtual base class and some derived concrete classes:

```<code>class Base { ... }
class DerivedA : public Base { ... }
class DerivedB : public Base { ... }
class DerivedC : public Base { ... }
</code>```

And somewhere I have vectors of objects of each derived class:

```<code>std::vector<DerivedA> my_a;
std::vector<DerivedB> my_b;
std::vector<DerivedC> my_c;
</code>```

Now, quite often I need to iterate over all elements in all three vectors and exercise the base class interface. I could write three for-loops, doing exactly the same in each. But obviously that's a far from optimal solution.

Is there a clever way to concatenate the vectors into a common container with base-class pointers/references, such that I need to iterate only once? Or any other idea how to solve this elegantly?

答:
On the other hand, you can manufacture your own homemade view adapter:

```<code>#include <iostream>
#include <vector>
#include <functional>
#include <iterator>

struct Base {
    virtual int f() const = 0;
    virtual ~Base() {}
};

struct D1: Base {
    int f() const { return 42; }
};

struct D2: Base {
    int f() const { return 314; }
};

template<typename T, typename... Left, typename... Right>
inline std::vector<T, Left...> operator+(std::vector<T, Left...> &&left, std::vector<T, Right...> &&right) {
    std::vector<T, Left...> retVal(std::move(left));
    using mi = std::move_iterator<typename std::vector<T, Right...>::iterator>;
    retVal.insert(retVal.end(), mi(right.begin()), mi(right.end()));
    return retVal;
}

int main() {
    std::vector<D1> v1(3);
    std::vector<D2> v2(4);
    using View = std::vector<std::reference_wrapper<const Base>>;
    View b(View(v1.cbegin(), v1.cend()) + View(v2.cbegin(), v2.cend()));
    for(Base const &item: b) std::cout << item.f() << std::endl;
}
</code>```

(Note that the underlying viewed containers can be any, vectors are but for instance, but their element types should be conformant.)

Body:
Assume I have a virtual base class and some derived concrete classes:

class Base { ... }
class DerivedA : public Base { ... }
class DerivedB : public Base { ... }
class DerivedC : public Base { ... }

And somewhere I have vectors of objects of each derived class:

std::vector<DerivedA> my_a;
std::vector<DerivedB> my_b;
std::vector<DerivedC> my_c;

Now, quite often I need to iterate over all elements in all three vectors and exercise the base class interface. I could write three for-loops, doing exactly the same in each. But obviously that's a far from optimal solution.

Is there a clever way to concatenate the vectors into a common container with base-class pointers/references, such that I need to iterate only once? Or any other idea how to solve this elegantly?

Body:
On the other hand, you can manufacture your own homemade view adapter:

#include <iostream>
#include <vector>
#include <functional>
#include <iterator>

struct Base {
    virtual int f() const = 0;
    virtual ~Base() {}
};

struct D1: Base {
    int f() const { return 42; }
};

struct D2: Base {
    int f() const { return 314; }
};

template<typename T, typename... Left, typename... Right>
inline std::vector<T, Left...> operator+(std::vector<T, Left...> &&left, std::vector<T, Right...> &&right) {
    std::vector<T, Left...> retVal(std::move(left));
    using mi = std::move_iterator<typename std::vector<T, Right...>::iterator>;
    retVal.insert(retVal.end(), mi(right.begin()), mi(right.end()));
    return retVal;
}

int main() {
    std::vector<D1> v1(3);
    std::vector<D2> v2(4);
    using View = std::vector<std::reference_wrapper<const Base>>;
    View b(View(v1.cbegin(), v1.cend()) + View(v2.cbegin(), v2.cend()));
    for(Base const &item: b) std::cout << item.f() << std::endl;
}

(Note that the underlying viewed containers can be any, vectors are but for instance, but their element types should be conformant.)


来源: stackexchange

问:
C++ Can't change Element in Char Array
I'm new to C coming from Java. Just explain me why this:

text[0] = 'a';```
</div>
</div>
</p>

<p>is not possible, my program just crashes.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#include "caesarHead.h"
#include <limits.h>

int main(void) {

 caesar("Hello this is a sample text", 12);

 printf("\n\n");
}

void caesar(char text[], char offset) {
 int i = 0;
 text[0] = 'a';
 char *p = text;

 for (p; *p != '\0'; p++) {

  printf("String: %c \n", text[i]);
  printf("Ascii: %i \n", (int)text[i]);
  i++;
 }
}</code>```

答:
You cannot modify string literal. In fact, you can try but this is undefined behavior and it may or may not work.

Instead, put your string to variable first and then use it. In this case, you string is initialized when main is called and it is put on stack therefore you are able to modify it later.

```<code>int main(void) {
    char str[] = "Hello this is a sample text";
    caesar(str, 12);
    printf("\n\n");
}
</code>```

String literal must be used as non-modifiable string. When trying to modify such a string, we have undefined behavior.

ContentLicense: CC BY-SA 3.0

Title: C++ Can't change Element in Char Array

Body:
I'm new to C coming from Java. Just explain me why this:

text[0] = 'a';

is not possible, my program just crashes.

#include "caesarHead.h"
#include <limits.h>

int main(void) {

 caesar("Hello this is a sample text", 12);

 printf("\n\n");
}

void caesar(char text[], char offset) {
 int i = 0;
 text[0] = 'a';
 char *p = text;

 for (p; *p != '\0'; p++) {

  printf("String: %c \n", text[i]);
  printf("Ascii: %i \n", (int)text[i]);
  i++;
 }
}

Body:
You cannot modify string literal. In fact, you can try but this is undefined behavior and it may or may not work.

Instead, put your string to variable first and then use it. In this case, you string is initialized when main is called and it is put on stack therefore you are able to modify it later.

int main(void) {
    char str[] = "Hello this is a sample text";
    caesar(str, 12);
    printf("\n\n");
}

String literal must be used as non-modifiable string. When trying to modify such a string, we have undefined behavior.


问:
Stored Procedure set parameter based on other parameters input
Trying to create a stored procedure in SQL 2008R2.
I have two Parameter inputs, that depending on their input, will ideally set another parameter's value to one of four values.  Trying to determine if this can done, and if so, where is the best place to put it in the SP.
Here is a slimmed down version of my code.

```<code>Declare @FWIdle as bYN, @NewComp as bYN

set @FW = 'Y'
set @NEW = 'Y'

select Case(
when w.WearRate <0.400 then round((- 50*w.WearRate+112.5),2
when w.WearRate <0.450 then round((-100*w.WearRate+132.5),2)
when w.WearRate <0.550 then round((- 50*w.WearRate+110.5),2)
else 52.5 END as Score

from EMWear w
</code>```

Hoping to replace all w.WearRate with @Wear and setting @Wear to one of four possible fields in the view, based on the combination of the two parameters.

So something like:

```<code>if @FW = 'Y' and @NEW = 'N' then @Wear = w.FWRate else
if @FW = 'N' and @NEW = 'Y' then @Wear = w.NewRate else
if @FW = 'Y' and @NEW = 'Y' then @Wear = w.FWNewRate else
@Wear = w.WearRate
</code>```

Since I have 150+ lines of code that deals with this rate, I would prefer not to have to write this code 4 times to get the desired Value. Any help on how I can write this and keep it clean/simple would be greatly appreciated.

答:
You can reduce all of your code to something like this.</p>

```<code>SELECT w.EMCo, w.Component,w.CompType, CASE
WHEN @FW = 'Y' AND @NEW = 'Y' THEN w.FwIdleWearRate
WHEN @FW = 'Y' AND @NEW = 'N' THEN w.FwWearRate
WHEN @FW = 'N' AND @NEW = 'Y' THEN w.IdleWearRate
ELSE w.StdWearRate
END AS WearRate
FROM bcvEMCompWearAdj w
</code>```

Body:
Trying to create a stored procedure in SQL 2008R2.
I have two Parameter inputs, that depending on their input, will ideally set another parameter's value to one of four values.  Trying to determine if this can done, and if so, where is the best place to put it in the SP.
Here is a slimmed down version of my code.

Declare @FWIdle as bYN, @NewComp as bYN

set @FW = 'Y'
set @NEW = 'Y'

select Case(
when w.WearRate <0.400 then round((- 50*w.WearRate+112.5),2
when w.WearRate <0.450 then round((-100*w.WearRate+132.5),2)
when w.WearRate <0.550 then round((- 50*w.WearRate+110.5),2)
else 52.5 END as Score

from EMWear w

Hoping to replace all w.WearRate with @Wear and setting @Wear to one of four possible fields in the view, based on the combination of the two parameters.

So something like:

if @FW = 'Y' and @NEW = 'N' then @Wear = w.FWRate else
if @FW = 'N' and @NEW = 'Y' then @Wear = w.NewRate else
if @FW = 'Y' and @NEW = 'Y' then @Wear = w.FWNewRate else
@Wear = w.WearRate

Since I have 150+ lines of code that deals with this rate, I would prefer not to have to write this code 4 times to get the desired Value. Any help on how I can write this and keep it clean/simple would be greatly appreciated.

Body:
You can reduce all of your code to something like this.

SELECT w.EMCo, w.Component,w.CompType, CASE
WHEN @FW = 'Y' AND @NEW = 'Y' THEN w.FwIdleWearRate
WHEN @FW = 'Y' AND @NEW = 'N' THEN w.FwWearRate
WHEN @FW = 'N' AND @NEW = 'Y' THEN w.IdleWearRate
ELSE w.StdWearRate
END AS WearRate
FROM bcvEMCompWearAdj w


问:
Typescript. How to get object's property name from its value?
I'm writing a typescript class for using with immutable map

```<code>class NavigableObject<T> {
    constructor(private obj: T, private path: string[] = []) { }

    To<R>(p: (x: T) => R): NavigableObject<R> {
        return new NavigableObject<R>(p(this.obj),
                       this.path.concat(this.getPropName(p(this.obj))));
    }

    getPath() {
        return this.path;
    }

    private getPropName(value) {
        for (var item in this.obj) {
            if (this.obj[item] === value) {
                return item;
            }
        }
    }
}

let test = {
    a: {
        a1: 1,
        a2: 1
    },
    b: {
        b1: 1,
        b2: 2
    }
}

let navigableTest = new NavigableObject(test);

navigableTest.To(m => m.b).To(m => m.b2).getPath(); // = ["b", "b2"]

navigableTest.To(m => m.a).To(m => m.a2).getPath(); // = ["a", "a1"] <-- I selected a2, tho
</code>```

There is a problem with getPropName method. When obj has two properties with same value, only the first property will be matched.

Does anyone know how to work around this?

答:
The future is here. As per Tim Perry's link, TypeScript has now added keyof, which is a great feature for getting the available properties of a class.

Usage, as per the TypeScript documentation:

```<code>interface Person {
    name: string;
    age: number;
    location: string;
}

type K1 = keyof Person; // "name" | "age" | "location"
type K2 = keyof Person[];  // "length" | "push" | "pop" | "concat" | ...
type K3 = keyof { [x: string]: Person };  // string
</code>```

Body:
I'm writing a typescript class for using with immutable map

class NavigableObject<T> {
    constructor(private obj: T, private path: string[] = []) { }

    To<R>(p: (x: T) => R): NavigableObject<R> {
        return new NavigableObject<R>(p(this.obj),
                       this.path.concat(this.getPropName(p(this.obj))));
    }

    getPath() {
        return this.path;
    }

    private getPropName(value) {
        for (var item in this.obj) {
            if (this.obj[item] === value) {
                return item;
            }
        }
    }
}

let test = {
    a: {
        a1: 1,
        a2: 1
    },
    b: {
        b1: 1,
        b2: 2
    }
}

let navigableTest = new NavigableObject(test);

navigableTest.To(m => m.b).To(m => m.b2).getPath(); // = ["b", "b2"]

navigableTest.To(m => m.a).To(m => m.a2).getPath(); // = ["a", "a1"] <-- I selected a2, tho

There is a problem with getPropName method. When obj has two properties with same value, only the first property will be matched.

Does anyone know how to work around this?

Body:
The future is here. As per Tim Perry's link, TypeScript has now added keyof, which is a great feature for getting the available properties of a class.

Usage, as per the TypeScript documentation:

interface Person {
    name: string;
    age: number;
    location: string;
}

type K1 = keyof Person; // "name" | "age" | "location"
type K2 = keyof Person[];  // "length" | "push" | "pop" | "concat" | ...
type K3 = keyof { [x: string]: Person };  // string


问:
Automatic Dataset in BigQuery?
I'm working in BigQuery with the DataSets from GA and I create some new tables for frequent analysis, and I have one question:
It's posible to create an automatic upgrade from the data at this tables?

The data from the tables comes from some queries about the GA Datasets, I need this to make a daily export from this data.

Thanks.

答:
This is not currently supported in BigQuery (although you could write your own scripts to do this on a periodic basis).

Scheduled queries are planned for a future version of the product. See:
https://issuetracker.google.com/issues/38173739

Title: Automatic Dataset in BigQuery?


问:
Convert Bouncy castle aes key to UTF-8 string
My program generate AES key, crypt it with rsa algorithm and send to server. But when I fetch it from server and decrypt some bytes become corrupted and replace with sequence 239 191 189
According to this question
UTF-8 Encoding and decoding issue I realized that the problem is that server (that also decrypt key) store it as UTF-8 string. Is there any way to create "UTF-8 friendly" keys? There how now generating keys:

```<code>        IBufferedCipher cipher = CipherUtilities.GetCipher("AES/CBC/PKCS7Padding");
        CipherKeyGenerator aesKeyGenerator = new CipherKeyGenerator();
        var rand = new SecureRandom();
        aesKeyGenerator.Init(new KeyGenerationParameters(rand, 256));
        byte[] key = aesKeyGenerator.GenerateKey();
        var aesKey = ParameterUtilities.CreateKeyParameter("AES", _key);
        var iv = new byte[32];
        rand.NextBytes(iv);
        ParametersWithIV aesKeyParam = new ParametersWithIV(aesKey, iv);
</code>```

答:
Your AES key consists of bits/bytes. IF you want to view it you could convert the bytes then you should probably use a hexadecimal encoding of those bytes. Generally you do not need to though: AES keys should be kept binary.

Only during debugging does it make sense to convert to hexadecimals. As this is key material it also makes sense to remove those lines after the code is functional - you can perform unit testing with test keys to verify correctness.

It does make sense to convert the RSA encrypted key to base 64 if you need to send the encrypted key over a text interface (SOAP, JSON, XML, whatever). Needless to say you should convert it back into binary upon receiving the wrapped (i.e. encrypted) key.

Body:
My program generate AES key, crypt it with rsa algorithm and send to server. But when I fetch it from server and decrypt some bytes become corrupted and replace with sequence 239 191 189
According to this question
UTF-8 Encoding and decoding issue I realized that the problem is that server (that also decrypt key) store it as UTF-8 string. Is there any way to create "UTF-8 friendly" keys? There how now generating keys:

        IBufferedCipher cipher = CipherUtilities.GetCipher("AES/CBC/PKCS7Padding");
        CipherKeyGenerator aesKeyGenerator = new CipherKeyGenerator();
        var rand = new SecureRandom();
        aesKeyGenerator.Init(new KeyGenerationParameters(rand, 256));
        byte[] key = aesKeyGenerator.GenerateKey();
        var aesKey = ParameterUtilities.CreateKeyParameter("AES", _key);
        var iv = new byte[32];
        rand.NextBytes(iv);
        ParametersWithIV aesKeyParam = new ParametersWithIV(aesKey, iv);


问:
Room - LiveData observer does not trigger when database is updated
I am trying to find out in the code below, why is it that Room's LiveData observable does not give me new shifts once I populate the database with new data.

This is put on my activity's onCreate method:

```<code>shiftsViewModel = ViewModelProviders.of(this).get(ShiftsViewModel.class);
shiftsViewModel
            .getShifts()
            .observe(this, this::populateAdapter);
</code>```

This is the populateAdapter method:

```<code>private void populateAdapter(@NonNull final List<Shift> shifts){

    recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(shifts));
}
</code>```

I also have the following code that populates the database (I use RxJava to do the work on an IO thread since Room needs its code to be called outside the main thread):

```<code>@Override
public Observable<List<Shift>> persistShifts(@NonNull final List<Shift> shifts){

    return Observable.fromCallable(() -> {

        appDatabase.getShiftDao().insertAll(shifts);
        return shifts;
    })
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread());
}
</code>```

The problem I have occurs when I call persistShifts after I start observing my shiftsViewModel. I would expect that my observer (LiveData) would be triggered with all the newly added shifts. It turns out the observer is triggered, but an empty list of shifts is returned instead. The only way to make it "work" is if I leave the activity (therefore destroying the current ViewModel) and enter again. This time the viewModel's LiveData gives me all the shifts previously persisted, as expected.

Here is the rest of the code:

```<code>@Entity
public class Shift{

   @PrimaryKey
   private long id;

   private String start;
   private String end;
   private String startLatitude;
   private String startLongitude;
   private String endLatitude;
   private String endLongitude;
   private String image;
   ...
</code>```

DAO:

```<code>@Dao
public interface ShiftDAO {

   @Query("SELECT * FROM shift")
   LiveData<List<Shift>> getAll();

   @Query("SELECT * FROM shift WHERE id = :id")
   LiveData<Shift> getShiftById(long id);

   @Insert(onConflict = OnConflictStrategy.REPLACE)
   void insertAll(List<Shift> shifts);
}
</code>```

ViewModel:

```<code>public class ShiftsViewModel extends AndroidViewModel{

   private final ISQLDatabase sqlDatabase;

   private MutableLiveData<Shift> currentShift;
   private LiveData<List<Shift>> shifts;
   private boolean firstTimeCreated;

   public ShiftsViewModel(final Application application){

      super(application);

      this.sqlDatabase = ((ThisApplication) application).getSQLDatabase();
      this.firstTimeCreated = true;
   }

   public MutableLiveData<Shift> getCurrentlySelectedShift(){

      if(currentShift == null){
         currentShift = new MutableLiveData<>();
      }

      return currentShift;
   }

   public LiveData<List<Shift>> getShifts() {

      if(shifts == null){
         shifts = sqlDatabase.queryAllShifts();
      }

     return shifts;
   }

   public void setCurrentlySelectedShift(final Shift shift){

      currentShift = getCurrentlySelectedShift();

      currentShift.setValue(shift);
   }

   public boolean isFirstTimeCreated(){
      return firstTimeCreated;
   }

   public void alreadyUsed(){
      firstTimeCreated = false;
   }
}
</code>```

Why am I not getting the list of shifts I persist in the observe() callback straightaway?

答:
I had a similar problem using Dagger 2 that was caused by having different instances of the Dao, one for updating/inserting data, and a different instance providing the LiveData for observing. Once I configured Dagger to manage a singleton instance of the Dao, then I could insert data in the background (in my case in a Service) while observing LiveData in my Activity - and the onChange() callback would be called.

It comes down to the instance of the Dao must be the same instance that is inserting/updating data and providing LiveData for observation.

Body:
I am trying to find out in the code below, why is it that Room's LiveData observable does not give me new shifts once I populate the database with new data.

This is put on my activity's onCreate method:

shiftsViewModel = ViewModelProviders.of(this).get(ShiftsViewModel.class);
shiftsViewModel
            .getShifts()
            .observe(this, this::populateAdapter);

This is the populateAdapter method:

private void populateAdapter(@NonNull final List<Shift> shifts){

    recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(shifts));
}

I also have the following code that populates the database (I use RxJava to do the work on an IO thread since Room needs its code to be called outside the main thread):

@Override
public Observable<List<Shift>> persistShifts(@NonNull final List<Shift> shifts){

    return Observable.fromCallable(() -> {

        appDatabase.getShiftDao().insertAll(shifts);
        return shifts;
    })
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread());
}

The problem I have occurs when I call persistShifts after I start observing my shiftsViewModel. I would expect that my observer (LiveData) would be triggered with all the newly added shifts. It turns out the observer is triggered, but an empty list of shifts is returned instead. The only way to make it "work" is if I leave the activity (therefore destroying the current ViewModel) and enter again. This time the viewModel's LiveData gives me all the shifts previously persisted, as expected.

Here is the rest of the code:

@Entity
public class Shift{

   @PrimaryKey
   private long id;

   private String start;
   private String end;
   private String startLatitude;
   private String startLongitude;
   private String endLatitude;
   private String endLongitude;
   private String image;
   ...

DAO:

@Dao
public interface ShiftDAO {

   @Query("SELECT * FROM shift")
   LiveData<List<Shift>> getAll();

   @Query("SELECT * FROM shift WHERE id = :id")
   LiveData<Shift> getShiftById(long id);

   @Insert(onConflict = OnConflictStrategy.REPLACE)
   void insertAll(List<Shift> shifts);
}

ViewModel:

public class ShiftsViewModel extends AndroidViewModel{

   private final ISQLDatabase sqlDatabase;

   private MutableLiveData<Shift> currentShift;
   private LiveData<List<Shift>> shifts;
   private boolean firstTimeCreated;

   public ShiftsViewModel(final Application application){

      super(application);

      this.sqlDatabase = ((ThisApplication) application).getSQLDatabase();
      this.firstTimeCreated = true;
   }

   public MutableLiveData<Shift> getCurrentlySelectedShift(){

      if(currentShift == null){
         currentShift = new MutableLiveData<>();
      }

      return currentShift;
   }

   public LiveData<List<Shift>> getShifts() {

      if(shifts == null){
         shifts = sqlDatabase.queryAllShifts();
      }

     return shifts;
   }

   public void setCurrentlySelectedShift(final Shift shift){

      currentShift = getCurrentlySelectedShift();

      currentShift.setValue(shift);
   }

   public boolean isFirstTimeCreated(){
      return firstTimeCreated;
   }

   public void alreadyUsed(){
      firstTimeCreated = false;
   }
}

Why am I not getting the list of shifts I persist in the observe() callback straightaway?


问:
PrimeNg datatable doesn't refresh
Using Angular v2.4.8 and PrimeNg v1.1.4

I have a page with two components:

Dropzone, for uploading files

p-datatable to show the uploaded files

I configured Dropzone to send 5 files at a time and when it is finished with 5 files the event onDropZoneSendingMultiple is raised. When all files are uploaded onDropZoneQueueComplete is raised.

In both listeners I want to refresh the datatable which is in the second component. This is not working. I need to refresh the page to see the new files.

My HTML of the main page:

```<code><div class="row" id="dropzoneContainer">
    <dropzone class="dropzone" #dz [config]="dropZoneConfig"
              (error)="onDropZoneUploadError($event)"
              (sendingmultiple)="onDropZoneSendingMultiple($event)"
              (queuecomplete)="onDropZoneQueueComplete($event, dz);"
              (maxfilesreached)="onDropZoneMaxfilesReached($event)"
              (maxfilesexceeded)="onDropZoneMaxfilesExceeded"></dropzone>
</div>

<div class="row">
    <div class="col-md-12">
        <FilesList></FilesList>
    </div>
</div>
</code>```

The Dropzone-component shows the dropzone. The FilesList shows the datatable.
Part of the HTML:

```<code><p-dataTable [hidden]="loading" [value]="files" selectionMode="single" (onRowSelect)="details($event)">
</code>```

In my main ts-file I have:

```<code>@ViewChild(FilesListComponent)
public filesListComponent: FilesListComponent;

private reloadFileList() {
  this.filesListComponent.reload();
}
</code>```

In my filelist ts I have

```<code>public files: File[];
public reload() {
    this.getFiles();
}
public getFiles() {
    this.fileService.getAll()
        .then(
        data => {
            this.files = data;
        });
}
</code>```

getFiles is also called at page load.
When I add console.log() statements I can see getFiles() is called and this.files is updated, but the table doesn't refresh.

答:
For anyone still looking for the new syntax of adding records to an array that is bound to a primeng table

this.arrayRecords= [...this.arrayRecords, newObject];

Title: PrimeNg datatable doesn't refresh

Body:
Using Angular v2.4.8 and PrimeNg v1.1.4

I have a page with two components:

Dropzone, for uploading files

p-datatable to show the uploaded files

I configured Dropzone to send 5 files at a time and when it is finished with 5 files the event onDropZoneSendingMultiple is raised. When all files are uploaded onDropZoneQueueComplete is raised.

In both listeners I want to refresh the datatable which is in the second component. This is not working. I need to refresh the page to see the new files.

My HTML of the main page:

    <dropzone class="dropzone" #dz [config]="dropZoneConfig"
              (error)="onDropZoneUploadError($event)"
              (sendingmultiple)="onDropZoneSendingMultiple($event)"
              (queuecomplete)="onDropZoneQueueComplete($event, dz);"
              (maxfilesreached)="onDropZoneMaxfilesReached($event)"
              (maxfilesexceeded)="onDropZoneMaxfilesExceeded"></dropzone>

        <FilesList></FilesList>

The Dropzone-component shows the dropzone. The FilesList shows the datatable.
Part of the HTML:

In my main ts-file I have:

@ViewChild(FilesListComponent)
public filesListComponent: FilesListComponent;

private reloadFileList() {
  this.filesListComponent.reload();
}

In my filelist ts I have

public files: File[];
public reload() {
    this.getFiles();
}
public getFiles() {
    this.fileService.getAll()
        .then(
        data => {
            this.files = data;
        });
}

getFiles is also called at page load.
When I add console.log() statements I can see getFiles() is called and this.files is updated, but the table doesn't refresh.


问:
How to use single function to multiple classes?
I've got this following code:

```<code><script type="text/javascript">
    $(document).ready(function(){
        $('.sample1').click(function(){
            $('.dropdown-content').toggleClass('visible-dropdown');
        })
    })
</script>
</code>```

It adds class so I can get some animations with mouse click event.
I have some more classes in HTML like 'sample2', 'sample3', etc. and would like to add exactly the same animations (classes of course has different content).

I know one solution, namely just add in same code n-times, but change class for each block of code. Is there a shorter way? I thought maybe something with arrays, not sure. I'm not really good in JS, it's like my first time ;)

答:
Simply use multiple selectors:

```<code>$('.sample1, .sample2 , .sample3').click(function(){
   $('.dropdown-content').toggleClass('visible-dropdown');
})
</code>```

You could try

```<code>$('*[class*="sample"]')
</code>```

This is the source

ContentLicense: CC BY-SA 4.0

Body:
I've got this following code:

It adds class so I can get some animations with mouse click event.
I have some more classes in HTML like 'sample2', 'sample3', etc. and would like to add exactly the same animations (classes of course has different content).

I know one solution, namely just add in same code n-times, but change class for each block of code. Is there a shorter way? I thought maybe something with arrays, not sure. I'm not really good in JS, it's like my first time ;)

Body:
Simply use multiple selectors:

$('.sample1, .sample2 , .sample3').click(function(){
   $('.dropdown-content').toggleClass('visible-dropdown');
})

You could try

$('*[class*="sample"]')

This is the source


问:
#EMERGENCY!!! Run-Time Check Failure #2 - Stack around the variable 'b' was corrupted
I know this seems like an old question, but none answered questions I searched work.
I have kept receiving "Run-Time Check Failure #2 - Stack around the variable 'b' was corrupted." when I was trying to do a [4][2]*[2][3] matrix multiplication.

Does anyone spot the problem?

```<code>#include <stdio.h>
int main() {
    int a[4][2] = {0};
    int b[2][3] = {0};
    int c[3][3] = {0};
    int i, j;
    printf("Please enter first matrix value\n");
    for (i = 0; i < 4; i++) {
        for (j = 0; j < 2; j++) {
            printf("%d row, %d column:", i + 1, j + 1);
            scanf("%d", &a[i][j]);
        }
    }
    printf("Please enter second matrix value\n");
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 3; j++) {
            printf("%d row, %d column:", i + 1, j + 1);
            scanf("%d", &b[i][j]);
        }
    }
    printf("\n the result is :\n");//
    for (i = 0; i < 4; i++) {
        printf("[");
        for (j = 0; j < 3; j++) {
            c[i][j] = (a[i][0] * b[0][j]) + (a[i][1] * b[1][j]);
            printf(" %4d ", c[i][j]);
        }
        printf("]\n");
    }
    return 0;
}
</code>```

答:
I haven't checked your code thoroughly, but you define c as 3x3, and here

```<code>for (i = 0; i < 4; i++) {
    printf("[");
    for (j = 0; j < 3; j++) {
        c[i][j] = (a[i][0] * b[0][j]) + (a[i][1] * b[1][j]);
</code>```

...you access c[3], which is c's fourth element, and does not exist. This is bound to write somewhere else.

So check your indexes (as @ptb observed, c's should actually be four rows deep).

Body:
I know this seems like an old question, but none answered questions I searched work.
I have kept receiving "Run-Time Check Failure #2 - Stack around the variable 'b' was corrupted." when I was trying to do a [4][2]*[2][3] matrix multiplication.

Does anyone spot the problem?

#include <stdio.h>
int main() {
    int a[4][2] = {0};
    int b[2][3] = {0};
    int c[3][3] = {0};
    int i, j;
    printf("Please enter first matrix value\n");
    for (i = 0; i < 4; i++) {
        for (j = 0; j < 2; j++) {
            printf("%d row, %d column:", i + 1, j + 1);
            scanf("%d", &a[i][j]);
        }
    }
    printf("Please enter second matrix value\n");
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 3; j++) {
            printf("%d row, %d column:", i + 1, j + 1);
            scanf("%d", &b[i][j]);
        }
    }
    printf("\n the result is :\n");//
    for (i = 0; i < 4; i++) {
        printf("[");
        for (j = 0; j < 3; j++) {
            c[i][j] = (a[i][0] * b[0][j]) + (a[i][1] * b[1][j]);
            printf(" %4d ", c[i][j]);
        }
        printf("]\n");
    }
    return 0;
}

Body:
I haven't checked your code thoroughly, but you define c as 3x3, and here

for (i = 0; i < 4; i++) {
    printf("[");
    for (j = 0; j < 3; j++) {
        c[i][j] = (a[i][0] * b[0][j]) + (a[i][1] * b[1][j]);

...you access c[3], which is c's fourth element, and does not exist. This is bound to write somewhere else.

So check your indexes (as @ptb observed, c's should actually be four rows deep).


问:
How to remove only the update button on sonata admin edit?
I need to remove only the edit button (Atualizar) on the edit of a Sonata Admin:

```<code><button type="submit" class="btn btn-success" name="btn_update_and_edit"><i class="fa fa-save"
aria-hidden="true"></i> Atualizar</button>
</code>```

But I need to keep the update and list (Atualizar e sair) option:

```<code><button type="submit" class="btn btn-success" name="btn_update_and_list"><i class="fa fa-save"
></i> <i class="fa fa-list" aria-hidden="true"></i> Atualizar e sair</button>
</code>```

I could probably remove it with JavaScript by subscribing the template, but it does not seen to be the best approach.

答:
If you need hide this "Update" button for all edit pages then, a solution would be override the base_edit_form.html.twig template and its sonata_form_actions block, which contains this part.

Make sure to create a new template with the same name of the origin template file in this path:

```<code>- app/
  - Resources/
    - SonataAdminBundle/
      - views/
        - CRUD/
            base_edit_form.html.twig
</code>```

and overrides this block with the needed changes:

```<code>{% use '@SonataAdmin/CRUD/base_edit_form.html.twig' %}

{% block sonata_form_actions %}
    ...
{% endblock %}
</code>```

Note: Use formactions block name for oldest version if sonata_form_actions is not defined.

More about "How to Override Templates from Third-Party Bundles" here.

Body:
I need to remove only the edit button (Atualizar) on the edit of a Sonata Admin:

<button type="submit" class="btn btn-success" name="btn_update_and_edit"> Atualizar</button>

But I need to keep the update and list (Atualizar e sair) option:

<button type="submit" class="btn btn-success" name="btn_update_and_list">  Atualizar e sair</button>

I could probably remove it with JavaScript by subscribing the template, but it does not seen to be the best approach.

Body:
If you need hide this "Update" button for all edit pages then, a solution would be override the base_edit_form.html.twig template and its sonata_form_actions block, which contains this part.

Make sure to create a new template with the same name of the origin template file in this path:

- app/
  - Resources/
    - SonataAdminBundle/
      - views/
        - CRUD/
            base_edit_form.html.twig

and overrides this block with the needed changes:

{% use '@SonataAdmin/CRUD/base_edit_form.html.twig' %}

{% block sonata_form_actions %}
    ...
{% endblock %}

Note: Use formactions block name for oldest version if sonata_form_actions is not defined.

More about "How to Override Templates from Third-Party Bundles" here.


问:
Angular 4 - How to add a material design HTML element into a file with Angular 4
I'm attempting to insert a md-button-toggle into a button toggle group programatically with Angular but Create Element doesn't seem to work well with non standard HTML tags.

HTML snippet i'm attempting to append:

```<code>        <md-button-toggle-group class="toggle-box" [vertical]="true" id="button-toggle-group">
            <dash-theme (onSelected)="setTheme($event);sidenav.close()"></dash-theme>
            <md-button-toggle routerLink="/admin/dashboard" (click)=sidenav.close()>
                Admin Dashboard
            </md-button-toggle>
        </md-button-toggle-group>
</code>```

Angular attempt:

```<code>// adds a View Dashboard button to the side nav bar when
addViewDashboard(): void {
    var node = document.createElement('<md-button-toggle routerLink="/' + this.dashboardName
        + '" (click)=sidenav.close() id="view-dashboard-button"> View Dashboard </md-button-toggle>');
    document.getElementById("button-toggle-group").appendChild(node);
    }
</code>```

(this.dashboardName is just a string which will be passed into the router)

I realize CreateElement isn't supposed to work like this and can't really think of how else I can manage to do this.

The end product should be something like:

```<code>        <md-button-toggle-group class="toggle-box" [vertical]="true" id="button-toggle-group">
            <dash-theme (onSelected)="setTheme($event);sidenav.close()"></dash-theme>
            <md-button-toggle routerLink="/admin/dashboard" (click)=sidenav.close()>
                Admin Dashboard
            </md-button-toggle>
            <md-button-toggle routerLink="/[this.dashboardName Value]" (click)=sidenav.close() id="view-dashboard-button">
                View Dashboard
            </md-button-toggle>
        </md-button-toggle-group>
</code>```

答:
I would just use an array to represent the button toggle info...

```<code><md-button-toggle-group class="toggle-box" [vertical]="true" id="button-toggle-group">
    <dash-theme (onSelected)="setTheme($event);sidenav.close()"></dash-theme>
    <md-button-toggle *ngFor="let b of buttons" routerLink="b.route" (click)="b.clickAction()">{{b.title}}</md-button-toggle>
</md-button-toggle-group>
</code>```

Here's an example of the component property you can use to drive the template.

```<code>buttons: any = [
    { title: 'button 1', route: '/admin/dashboard', clickAction: () => { alert('action 1'); } },
    { title: 'button 2', route: '/[this.dashboardName Value]', clickAction: () => { alert('action 2'); } }
]
</code>```

Body:
I'm attempting to insert a md-button-toggle into a button toggle group programatically with Angular but Create Element doesn't seem to work well with non standard HTML tags.

HTML snippet i'm attempting to append:

        <md-button-toggle-group class="toggle-box" [vertical]="true" id="button-toggle-group">
            <dash-theme (onSelected)="setTheme($event);sidenav.close()"></dash-theme>
            <md-button-toggle routerLink="/admin/dashboard" (click)=sidenav.close()>
                Admin Dashboard
            </md-button-toggle>
        </md-button-toggle-group>

Angular attempt:

// adds a View Dashboard button to the side nav bar when
addViewDashboard(): void {
    var node = document.createElement('<md-button-toggle routerLink="/' + this.dashboardName
        + '" (click)=sidenav.close() id="view-dashboard-button"> View Dashboard </md-button-toggle>');
    document.getElementById("button-toggle-group").appendChild(node);
    }

(this.dashboardName is just a string which will be passed into the router)

I realize CreateElement isn't supposed to work like this and can't really think of how else I can manage to do this.

The end product should be something like:

        <md-button-toggle-group class="toggle-box" [vertical]="true" id="button-toggle-group">
            <dash-theme (onSelected)="setTheme($event);sidenav.close()"></dash-theme>
            <md-button-toggle routerLink="/admin/dashboard" (click)=sidenav.close()>
                Admin Dashboard
            </md-button-toggle>
            <md-button-toggle routerLink="/[this.dashboardName Value]" (click)=sidenav.close() id="view-dashboard-button">
                View Dashboard
            </md-button-toggle>
        </md-button-toggle-group>

Body:
I would just use an array to represent the button toggle info...

<md-button-toggle-group class="toggle-box" [vertical]="true" id="button-toggle-group">
    <dash-theme (onSelected)="setTheme($event);sidenav.close()"></dash-theme>
    <md-button-toggle *ngFor="let b of buttons" routerLink="b.route" (click)="b.clickAction()">{{b.title}}</md-button-toggle>
</md-button-toggle-group>

Here's an example of the component property you can use to drive the template.

buttons: any = [
    { title: 'button 1', route: '/admin/dashboard', clickAction: () => { alert('action 1'); } },
    { title: 'button 2', route: '/[this.dashboardName Value]', clickAction: () => { alert('action 2'); } }
]


问:
Express routes & Same Object needed in several files
I made an web application where all my server side was in the same file.
To be clear, in my "app.js" i had :

Express routes

Socket.io events and more...

Differents objects reacting with pages events

I want to rework that project to do things properly and i started to do that. I have put my routes in different js files like login.js,subscribe.js, ...  in a routes directory.

In my app.js I have added the line : require('./routes')(app);

I have a index.js file in /routes where i had placed my "Express router" which is managing all my routes.

index.js

```<code>module.exports = function (app) {
app.get('/signup', require('./subscribe').get);
app.post('/signup', require('./subscribe').post);
app.get('/', require('./login').get);
app.post('/', require('./login').post);
...
}
</code>```

Is that the correct way to do with routes ?

The problem i meet is that i have an object named usersConnected {} that I fill with some properties when a member is logged in, etc...
This object is in my app.js file and I can't reach it from the other files like login.js...

app.js

```<code>// Express routing defined in ./routes/index.js
require('./routes')(app);

// Globals variables
var usersConnected = {};
var rooms = {};
...
</code>```

login.js

An example of the usage of usersConnected

```<code>// If login and password matches with couple in database
            usersConnected[login] = {
                games: rows[0].games,
                kills: rows[0].kills,
                deaths: rows[0].deaths,
                statut: "ACCUEIL",
                adversaire: "NULL",
                socket: "NULL",
                wsId: "NULL",
                room: "NULL",
                lsid: funcs.computeRandomLsId(64)
            };
</code>```

And how i export my "route managing"

```<code>exports.get = (req, res) => {
  if (!req.session.login)
       ...
}
</code>```

I have some ideas but I think it's the bad way to proceed like exports my object where I need it or put my object alone in a .js file which will be imported, etc...

If you could give me some trails that would really help me.

Edit : I think my problem is the way i manage my sessions, because usersConnected contains all informations about all users connected... Maybe i should use express-session ?

答:
I recommend you take a look at express-generator: http://expressjs.com/en/starter/generator.html . It provides a quite nice file structure for you to start. Even though it's quite opinionated, I found it very useful when I started and still do.

In the app.js file you will find something like this:

```<code>...
var routes = require('./routes/index');
app.use('/', routes);
</code>```

This is a bit tedius if you have a lot of routes. Here you have a code snippet to do this dinamically. gist

Anyway, the point is that the express generator will help you evacuate your doubts and point you in the right direction.

Body:
I made an web application where all my server side was in the same file.
To be clear, in my "app.js" i had :

Express routes

Socket.io events and more...

Differents objects reacting with pages events

I want to rework that project to do things properly and i started to do that. I have put my routes in different js files like login.js,subscribe.js, ...  in a routes directory.

In my app.js I have added the line : require('./routes')(app);

I have a index.js file in /routes where i had placed my "Express router" which is managing all my routes.

index.js

module.exports = function (app) {
app.get('/signup', require('./subscribe').get);
app.post('/signup', require('./subscribe').post);
app.get('/', require('./login').get);
app.post('/', require('./login').post);
...
}

Is that the correct way to do with routes ?

The problem i meet is that i have an object named usersConnected {} that I fill with some properties when a member is logged in, etc...
This object is in my app.js file and I can't reach it from the other files like login.js...

app.js

// Express routing defined in ./routes/index.js
require('./routes')(app);

// Globals variables
var usersConnected = {};
var rooms = {};
...

login.js

An example of the usage of usersConnected

// If login and password matches with couple in database
            usersConnected[login] = {
                games: rows[0].games,
                kills: rows[0].kills,
                deaths: rows[0].deaths,
                statut: "ACCUEIL",
                adversaire: "NULL",
                socket: "NULL",
                wsId: "NULL",
                room: "NULL",
                lsid: funcs.computeRandomLsId(64)
            };

And how i export my "route managing"

exports.get = (req, res) => {
  if (!req.session.login)
       ...
}

I have some ideas but I think it's the bad way to proceed like exports my object where I need it or put my object alone in a .js file which will be imported, etc...

If you could give me some trails that would really help me.

Edit : I think my problem is the way i manage my sessions, because usersConnected contains all informations about all users connected... Maybe i should use express-session ?

Body:
I recommend you take a look at express-generator: http://expressjs.com/en/starter/generator.html . It provides a quite nice file structure for you to start. Even though it's quite opinionated, I found it very useful when I started and still do.

In the app.js file you will find something like this:

...
var routes = require('./routes/index');
app.use('/', routes);

This is a bit tedius if you have a lot of routes. Here you have a code snippet to do this dinamically. gist

Anyway, the point is that the express generator will help you evacuate your doubts and point you in the right direction.


问:
fastest way to export blobs from table into individual files
What is the fastest way to export files (blobs) stored in a SQL Server table into a file on the hard drive?  I have over 2.5 TB of files (90 kb avg) stored as varbinary and I need to extract each one to a local hard drive as quickly as possible.  BCP seems to work but it will take over 45 days with the speed I'm seeing, and I'm worried that my script will fail at some point because Management Studio will run out of memory.</p>

答:
I came here looking for exporting blob into file with least effort. CLR functions is not something what I'd call least effort. Here described lazier one, using OLE Automation:

```<code>declare @init int
declare @file varbinary(max) = CONVERT(varbinary(max), N'your blob here')
declare @filepath nvarchar(4000) = N'c:\temp\you file name here.txt'

EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @file; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @filepath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources
</code>```

You'll potentially need to allow to run OA stored procedures on server (and then turn it off, when you're done):

```<code>sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
</code>```

Body:
I came here looking for exporting blob into file with least effort. CLR functions is not something what I'd call least effort. Here described lazier one, using OLE Automation:

declare @init int
declare @file varbinary(max) = CONVERT(varbinary(max), N'your blob here')
declare @filepath nvarchar(4000) = N'c:\temp\you file name here.txt'

EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @file; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @filepath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources

You'll potentially need to allow to run OA stored procedures on server (and then turn it off, when you're done):

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO


问:
MySQL - illegal mix of collations (latin1_swedish_ci implicit) and (utf8_general_ci coercible for operation '='
When I execute the query below i get this error:

Error Code: 1267. Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='

If you need background behind this code, here is the explanation:

MySQL - How Can I Automate a View Query That Subtracts Metrics From the Most Recent Date To The Previous Day & Date Stamps The Most Recent Data

I set the 'facebook_insight' table collation to: 'utf8_general_ci,' but I still get the error. Can anyone help me?

MySQL Query:

```<code>CREATE VIEW `facebook_insights` AS
SELECT
  t1.id
, t1.timestamp
, t1.message
, t1.posted
, t1.permalink_url
, t1.caption
, t1.link
, t1.type
, t1.post_impressions - t2.post_impressions as Impressions
, t1.post_impressions_organic - t2.post_impressions_organic as Post_Impressions_Organic
, t1.post_impressions_paid - t2.post_impressions_paid as Post_Impressions_Paid
, t1.post_engaged_users - t2.post_engaged_users as Post_Engaged_Users
, t1.post_consumptions - t2.post_consumptions as Post_Consumptions
, t1.post_negative_feedback - t2.post_negative_feedback as
Post_Negative_Feedback
, t1.post_negative_feedback_unique - t2.Post_Negative_Feedback_Unique as
Post_Negative_Feedback_Unique
, t1.post_impressions_fan - t2.post_impressions_fan as Post_Impressions_Fan
, t1.post_impressions_fan_paid - t2.post_impressions_fan_paid as
Post_Impressions_Fan_Paid
, t1.post_engaged_fan - t2.Post_Engaged_Fan as Post_Engaged_Fan
, t1.post_video_complete_views_organic -
t2.post_video_complete_views_organic as Post_Video_Complete_Views_Organic
, t1.post_video_complete_views_paid - t2.post_video_complete_views_paid as
Post_Video_Complete_Views_Paid
, t1.post_video_views_10s - t2.post_video_views_10s as Post_Video_Views_10s
, t1.post_video_views_10s_unique - t2.post_video_views_10s_unique as
Post_Video_Views_10s_Unique
, t1.post_video_views_organic - t2.post_video_views_organic as
Post_Video_Views_Organic
, t1.post_video_views_paid - t2.post_video_views_paid as
Post_Video_Views_Paid
, t1.post_video_views_clicked_to_play - t2.post_video_views_clicked_to_play
as Post_Video_Views_Clicked_to_Play

FROM
unpaid_media.facebook_insight t1
JOIN unpaid_media.facebook_insight t2
ON t1.id = t2.id
and t1.timestamp  = t2.timestamp + INTERVAL 1 DAY
</code>```

答:
As I can guess from your related question, the type of your timestamp column is not any of date, datetime or timestamp. It's probably varchar or text.

So when you try to add INTERVAL 1 DAY to the value which is not time type you get the error.

You have to convert your timestamp column to any of date, datetime or timestamp data types.

As a quick fix you can use STR_TO_DATE() function in your query:

```<code>CREATE VIEW `facebook_insights` AS
...
and STR_TO_DATE(t1.timestamp,'%m/%d/%Y') = STR_TO_DATE(t2.timestamp,'%m/%d/%Y') + INTERVAL 1 DAY
</code>```

But better alter your table in  order to have correct datatypes.

Body:
When I execute the query below i get this error:

Error Code: 1267. Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation '='

If you need background behind this code, here is the explanation:

MySQL - How Can I Automate a View Query That Subtracts Metrics From the Most Recent Date To The Previous Day & Date Stamps The Most Recent Data

I set the 'facebook_insight' table collation to: 'utf8_general_ci,' but I still get the error. Can anyone help me?

MySQL Query:

CREATE VIEW `facebook_insights` AS
SELECT
  t1.id
, t1.timestamp
, t1.message
, t1.posted
, t1.permalink_url
, t1.caption
, t1.link
, t1.type
, t1.post_impressions - t2.post_impressions as Impressions
, t1.post_impressions_organic - t2.post_impressions_organic as Post_Impressions_Organic
, t1.post_impressions_paid - t2.post_impressions_paid as Post_Impressions_Paid
, t1.post_engaged_users - t2.post_engaged_users as Post_Engaged_Users
, t1.post_consumptions - t2.post_consumptions as Post_Consumptions
, t1.post_negative_feedback - t2.post_negative_feedback as
Post_Negative_Feedback
, t1.post_negative_feedback_unique - t2.Post_Negative_Feedback_Unique as
Post_Negative_Feedback_Unique
, t1.post_impressions_fan - t2.post_impressions_fan as Post_Impressions_Fan
, t1.post_impressions_fan_paid - t2.post_impressions_fan_paid as
Post_Impressions_Fan_Paid
, t1.post_engaged_fan - t2.Post_Engaged_Fan as Post_Engaged_Fan
, t1.post_video_complete_views_organic -
t2.post_video_complete_views_organic as Post_Video_Complete_Views_Organic
, t1.post_video_complete_views_paid - t2.post_video_complete_views_paid as
Post_Video_Complete_Views_Paid
, t1.post_video_views_10s - t2.post_video_views_10s as Post_Video_Views_10s
, t1.post_video_views_10s_unique - t2.post_video_views_10s_unique as
Post_Video_Views_10s_Unique
, t1.post_video_views_organic - t2.post_video_views_organic as
Post_Video_Views_Organic
, t1.post_video_views_paid - t2.post_video_views_paid as
Post_Video_Views_Paid
, t1.post_video_views_clicked_to_play - t2.post_video_views_clicked_to_play
as Post_Video_Views_Clicked_to_Play

FROM
unpaid_media.facebook_insight t1
JOIN unpaid_media.facebook_insight t2
ON t1.id = t2.id
and t1.timestamp  = t2.timestamp + INTERVAL 1 DAY

Body:
As I can guess from your related question, the type of your timestamp column is not any of date, datetime or timestamp. It's probably varchar or text.

So when you try to add INTERVAL 1 DAY to the value which is not time type you get the error.

You have to convert your timestamp column to any of date, datetime or timestamp data types.

As a quick fix you can use STR_TO_DATE() function in your query:

CREATE VIEW `facebook_insights` AS
...
and STR_TO_DATE(t1.timestamp,'%m/%d/%Y') = STR_TO_DATE(t2.timestamp,'%m/%d/%Y') + INTERVAL 1 DAY

But better alter your table in  order to have correct datatypes.


问:
How can I access items in a top level module from another top level module without changing main.rs?
I have following file structure:

main.rs
-- module_a
  -- mod.rs
output.rs
```

In output.rs, I have a function called log_info() and I'd like to call it from module_a/mod.rs.

I can place mod output; in main.rs and after that I can reference it from module_a/mod.rs, but I don't like having to place all my dependencies in main.rs in order to use them in my application.

Is there any way I can reference the output module in module_a/mod.rs without messing with main.rs?

答:
Is there any way I can reference the output module in module_a/mod.rs without messing with main.rs?

No. Each module (including the crate entry point of main.rs or lib.rs) has to explicitly define what modules are its children.

You could move the output module to be a child of module_a, however.

Body:
I have following file structure:

main.rs
-- module_a
  -- mod.rs
output.rs

In output.rs, I have a function called log_info() and I'd like to call it from module_a/mod.rs.

I can place mod output; in main.rs and after that I can reference it from module_a/mod.rs, but I don't like having to place all my dependencies in main.rs in order to use them in my application.

Is there any way I can reference the output module in module_a/mod.rs without messing with main.rs?


问:
what is the best approach to find duplicates in my Db table
In my app the user can select multiple filter options. I store this in a DB table.

For example

User 1 can select filters A^B

User 2 can select filters AORC^D
and so forth.

The way it is stored in Db is

```<code>user        filter_selected

user1       A^B
user2       AORC^D
</code>```

Now the criteria is no user can have the same filters selected. So if user 3 comes and select A^B or B^A it should throw a error.

I am trying to come up with a smart logic to validate this in javascript.
One approach is go through all the users in the DB (can be many) and sort alphabetically  and check if its the same. So in our example A^B and B^A will be the same AB^. This way I can check. Any other better approach may be using mysql command itself ?

答:
you can sort your filter rule based on character and then insert it to do
for example, B^A will convert to AB^ and when you want to check you can sort your filter and then search it

if you want to have an original filter you don't care about the size of your database and more you care about speed you can save original as another column too.if you are care about size of database you can just save the original filter and when you want to search select the rows that have the same length as your filter and then you need to sort alphabetically or you can save index of every filter chars for example when you change A^B to AB^ you can save this filter AB^|021 but this will need to some more space too like original column and I don't suggest this method. also if your filters are always in small length you can don't fetch all record and compare to all. you can just create all possible way of the filter(for example AB^ A^B B^A BA^ ^AB ^BA) but you must be careful because in this method you are creating n! string and this is not good at all, just for too small length string its ok and that's when you have too many records in your database this method can be good

Body:
In my app the user can select multiple filter options. I store this in a DB table.

For example

User 1 can select filters A^B

User 2 can select filters AORC^D
and so forth.

The way it is stored in Db is

user        filter_selected

user1       A^B
user2       AORC^D

Now the criteria is no user can have the same filters selected. So if user 3 comes and select A^B or B^A it should throw a error.

I am trying to come up with a smart logic to validate this in javascript.
One approach is go through all the users in the DB (can be many) and sort alphabetically  and check if its the same. So in our example A^B and B^A will be the same AB^. This way I can check. Any other better approach may be using mysql command itself ?


问:
MongoDb, NodeJs, Express and Angular 2, Data from two collections join, retreival and display
I have two mongo collections:

locations: (locationId, locationCity, locationState, locationZip etc}

carLocations: {carId, carType, carMake, locationId}

I would like to retrieve the data

```<code>carAvailability: {locationCity, locationState, locationZip, carMake, carType}
</code>```

In my nodejs layer, Here is what I am trying to do:

First, I am trying to retrieve the array of locationIds by locationCity, locationState or locationZip. Once I have array of locationIds, I am trying to retrieve the carLocations.

```<code>app.get("/api/carsbylocationids", function (req, res) {
  //console.log(" locationid:" + req.query.locationid);
  var locationIds  = JSON.parse(req.query.locationIds);
  console.log("locationIds: " + locationIds);
  console.log("carId: " + req.query.carId);
  db.collection(carsLocations).find(
    {
      'locationId': {$in:locationIds},
      'carId': req.query.carId
    }
  ).toArray(function (err, docs) {
    if (err) {
      handleError(res, err.message, "Failed to get items.");
    } else {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Methods', 'GET);
      res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
      res.status(200).json(docs);
    }
  });

});
</code>```

Either in this part or the angularJS 2 code (not provided here), I would like the carAvailability: {locationCity, locationState, locationZip, carMake, carType} so that I can iterate through and display on the screen.

I am unable to arrive on a best/efficient way to do it. Should I handle this join type of condition in nodeJS layer or Angular2 layer?

答:
I used the aggregation by $lookup and $match to get the data from mongoDb. For those of you who want specifics:

```<code>app.get("/api/locationsByitemid", function (req, res) {
  console.log(" itemid:" + req.query.itemid + " city:" + req.query.locationCity + " state:" + req.query.locationState);

  db.collection(LOCATIONS_COLLECTION).aggregate([
    { $lookup: { from: ITEMS_COLLECTION, localField: "locationId",foreignField: "locationId", as: "locationsbyLocationId"} },
    { $unwind:"$locationsbyLocationId"},
    { "$match": { 'locationsbyLocationId.itemid': req.query.itemid, 'locationCity': req.query.locationCity, 'locationState' : req.query.locationState} }
    ]
  ).toArray(function (err, docs) {
    if (err) {
      handleError(res, err.message, "Failed to get items.");
    } else {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Methods', 'GET');
      res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
      res.status(200).json(docs);
    }
  });

});
</code>```

This is working to my satisfaction but any suggestions are welcome....  Thanks to those who pointed out that this is best handled prior to RestFul Service call. Thats what I explored.

Body:
I have two mongo collections:

locations: (locationId, locationCity, locationState, locationZip etc}

carLocations: {carId, carType, carMake, locationId}

I would like to retrieve the data

carAvailability: {locationCity, locationState, locationZip, carMake, carType}

In my nodejs layer, Here is what I am trying to do:

First, I am trying to retrieve the array of locationIds by locationCity, locationState or locationZip. Once I have array of locationIds, I am trying to retrieve the carLocations.

app.get("/api/carsbylocationids", function (req, res) {
  //console.log(" locationid:" + req.query.locationid);
  var locationIds  = JSON.parse(req.query.locationIds);
  console.log("locationIds: " + locationIds);
  console.log("carId: " + req.query.carId);
  db.collection(carsLocations).find(
    {
      'locationId': {$in:locationIds},
      'carId': req.query.carId
    }
  ).toArray(function (err, docs) {
    if (err) {
      handleError(res, err.message, "Failed to get items.");
    } else {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Methods', 'GET);
      res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
      res.status(200).json(docs);
    }
  });

});

Either in this part or the angularJS 2 code (not provided here), I would like the carAvailability: {locationCity, locationState, locationZip, carMake, carType} so that I can iterate through and display on the screen.

I am unable to arrive on a best/efficient way to do it. Should I handle this join type of condition in nodeJS layer or Angular2 layer?

Body:
I used the aggregation by $lookup and $match to get the data from mongoDb. For those of you who want specifics:

app.get("/api/locationsByitemid", function (req, res) {
  console.log(" itemid:" + req.query.itemid + " city:" + req.query.locationCity + " state:" + req.query.locationState);

  db.collection(LOCATIONS_COLLECTION).aggregate([
    { $lookup: { from: ITEMS_COLLECTION, localField: "locationId",foreignField: "locationId", as: "locationsbyLocationId"} },
    { $unwind:"$locationsbyLocationId"},
    { "$match": { 'locationsbyLocationId.itemid': req.query.itemid, 'locationCity': req.query.locationCity, 'locationState' : req.query.locationState} }
    ]
  ).toArray(function (err, docs) {
    if (err) {
      handleError(res, err.message, "Failed to get items.");
    } else {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Methods', 'GET');
      res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
      res.status(200).json(docs);
    }
  });

});

This is working to my satisfaction but any suggestions are welcome....  Thanks to those who pointed out that this is best handled prior to RestFul Service call. Thats what I explored.


问:
Jenkins with Cleracase - Creating Automatic Baselines in CC and triggering Jenkins Job
I am new to Jenkins and need some help.

We have ClearCase and Jenkins running on same machine (windows).

I am trying to configure Jenkins with clearcase through basic CC or CC UCM plugin. But i am not sure which one i need to choose.

My Current Process :
Step 1: Once developer deliver the code to Integration region in clearcase, Devops team manually do the baseline for Int stream and also do the rebase.
Step 2: And with some batch script they build the process and move the ear or jar to particular region.

Now i need to automate this process through Jenkins, where i got stuck with automating baseline and rebase in clearcase which they are doing it manually now. i think once the baseline creation is done by developer or through command process only Jenkins will be triggered to start the job.

So please suggest me the exact steps which i need to start automating the whole process.

答:
basic CC or CC UCM plugin. But i am not sure which one i need to choose.

If your view is built from a Stream, you need UCM. If not (simple config spec with your custom rules), you need Base.

In your case, you will use the Jenkins ClearCase UCM Plugin

All you need to do is test that a job is triggered on a new baseline (even if that job does at first only a simple echo "It work!")

Like the Git and Mercurial plugins, ClearCase UCM Plugin also supports polling for the latest baseline. This means, when polling, a build is scheduled only if there's a new baseline on the stream.

To be able to poll for the latest baseline, the special promotion level ANY and self polling must must be selected in the setup.

Once that is working, you can add in that job a Windows shell build step which will execute the very same command you would have typed manually in order to do the rebase (cleartool rebase...).

If you can script it manually (outside Jenkins), you can add it to a Jenkins job trivially.


问:
Visual Studio 2015 Integration Services project does not pick up my custom SSIS component
My development environment: SQL Server 2014, Visual Studio 2015,  SQL Server Data Tools Preview (September) for Visual Studio 2015

I have a custom SSIS source component that I can successfully use on another SQL 2014 box with  VS 2013 and SQL Server Data Tools - Business Intelligence. However, this component does not show up in the toolbox in VS 2015 Integration Services project.

The component is located in c:\Program Files (x86)\Microsoft SQL Server\120\DTS\PipelineComponents. It is also registered in GAC.

Do I need to make changes to the component so that it will work with VS2015?
More general question: how to troubleshoot issues like this?

答: In VS2015 Solution Explorer, right click on the .dtproj file and select properties. On the General Tab choose the SQL Server version that matches the component version. If the component worked on VS2013, choose 'SQL SERVER 14' when opening the package in VS2015.</p>


问:
Replacing lib with newer one causes symbols to be missing
I'm using mobclix lib in an iPhone app, I tried to replace the old lib with a newer one, the old lib contained a class named MobclixAdViewiPhone_300x50, but it has been deprecated and replaced with MobclixAdViewiPhone_320x50, I changed my code to match the library changes, and removed the old library and its headers and added the new lib and its headers (with the copy files option unchecked), but when I try to build I get a message saying:

```<code>"_OBJC_CLASS_$_MobclixAdViewiPhone_320x50", referenced from:
__objc_classrefs_DATA@0 in AdManager.o
Symbol(s) not found
Collect2: ld returned 1 exit status
</code>```

I've cleaned all targets (including dependencies and precompiled headers), restarted xcode, and even the computer, I checked and the lib is added under my target-> Link Binary with Libraries, but no luck.

What can I do to make it detect the new class in the new lib?

答:
I found out that removing a lib from project doesn't remove the search path, so, it was looking for the previous version's directory and using the new headers.

To fix this I had to go to Build Settings > Library Search Paths and delete the old paths to the old libs.

ContentLicense: CC BY-SA 2.5

Body:
I'm using mobclix lib in an iPhone app, I tried to replace the old lib with a newer one, the old lib contained a class named MobclixAdViewiPhone_300x50, but it has been deprecated and replaced with MobclixAdViewiPhone_320x50, I changed my code to match the library changes, and removed the old library and its headers and added the new lib and its headers (with the copy files option unchecked), but when I try to build I get a message saying:

"_OBJC_CLASS_$_MobclixAdViewiPhone_320x50", referenced from:
__objc_classrefs_DATA@0 in AdManager.o
Symbol(s) not found
Collect2: ld returned 1 exit status

I've cleaned all targets (including dependencies and precompiled headers), restarted xcode, and even the computer, I checked and the lib is added under my target-> Link Binary with Libraries, but no luck.

What can I do to make it detect the new class in the new lib?


问:
After installing Teradata SQL Assistant v15.10.03 on Citrix (Windows 2012), some users are unable to launch the application via citrix
We have recently installed Teradata SQL assistant which was part of TTU v15.10.03 on Citrix server. Some users(not all) are facing the issue where it says path to ansiAF.mbr is denied. Any idea why this could be?

]1

答:
I had the same problem when I upgraded from v13 to v15. Installed on my computer (not Citrix), hope this gives some clue to resolve yours.

Went to this location,
"C:\Users*user-id*\AppData\Roaming\Teradata"
renamed the already present folder 'SQL Assistant' to 'SQL Assistant - Backup'.

Reran SQLA, the folder 'SQL Assistant' got created again. And error is resolved.

However all customizations and history from v13 will go!  To get back the history, copy SQLHistory.mdb file from backup folder and replace in the newly created one.


问:
Add items to cart in php using sessions
Am trying to update the quantity in add to cart session, but the below code only increases the quantity of the first item added twice and then perfoms a merge whenever any other item is added twice, kidly help

$('.add-to-cart-mt').on('click', function(e){
        e.preventDefault();
        var id =$(this).attr('id');
        $('#add-to-cat-dialog').dialog({
            autoOpen:false,
            modal:true,
            hide:"pluff",
            show:"slide",
            height:200,
            open: function() { $(".ui-dialog-titlebar-close").hide(); },

            buttons:{
                "Add":function (){
                    $('#add-to-cat-dialog').dialog("close");
                    $.ajax({
                        url: 'add_to_cart.php',
                        data: {  productId : id },

                        success: function (data) {
                            $('.top-cart-contain').empty();
                            $('.top-cart-contain').load("header_cart_summary.php");
                        },

                        error :function (data, textStatus, jqXHR) {  }
                    });
                },

                "Cancel":function (){
                    $(this).dialog("close");
                }
            }
        });

        $('#add-to-cat-dialog').dialog("open");
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>session_start();
require './database.php';

      if(!empty($_GET["productId"])) {
          $id=$_GET["productId"];
            $productById = $connection->query("SELECT * FROM products WHERE productId='$id';");
            if($productById && (mysqli_num_rows($productById)>0)){
                echo 'query ok';
                $productDetail= mysqli_fetch_assoc($productById);
                $itemArray = array(
                    $productDetail["productId"]=>array(
                        'name'=>$productDetail["productName"],
                        'id'=>$productDetail["productId"],
                        'quantity'=>1,
                        'price'=>$productDetail["productPrice"],
                        'image'=>$productDetail["productsImage1"]
                        )
                    );

                if(!empty($_SESSION["cart_item"])) {
                    if(in_array($productDetail["productId"],array_keys($_SESSION["cart_item"]))) {
                        foreach($_SESSION["cart_item"] as $k => $v) {
                            if($productDetail["productId"] == $k) {
                                  if(empty($_SESSION["cart_item"][$k]["quantity"])) {
                                        $_SESSION["cart_item"][$k]["quantity"] = 0;
                                  }
                                  $_SESSION["cart_item"][$k]["quantity"] += 1;
                            }
                        }
                    } else {
                          $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
                    }
                } else {
                      $_SESSION["cart_item"] = $itemArray;
                }

                //set product count in the bag
                if(!empty($_SESSION['cart_volume'])){
                    $_SESSION['cart_volume'] += 1;
                } else {
                    $_SESSION['cart_volume'] = 1;
                }

            }else {echo ''. mysqli_error($connection);}

      } else {
          echo 'no item';
}</code>```

[enter image description here][1]

  <img class="first-img" src="./productImages/<?php echo $item['productsImage1']; ?>" style="height: 250px;"  alt="">

Quick view Wishlist Compare

<?php echo $item['productName']; ?>

 Special Price Ksh. <?php echo number_format($item['productPrice'], 2) ; ?>

                                              <button type="button" class="add-to-cart-mt" id="<?php echo $item['productId']; ?>">  Add to Cart </button>

```

答:
The code below works fine as i required. Thanks to -Saleiro for his inputs.

[

```<code>  if(!empty($_GET["productId"])) {
      $id=intval($_GET["productId"]);
        $productById = $connection->query("SELECT * FROM products WHERE productId='$id' ");
        if($productById && (mysqli_num_rows($productById)>0)){
            $productDetail= mysqli_fetch_assoc($productById);
            $itemArray = array(intval($productDetail["productId"])=>array('name'=>$productDetail["productName"], 'id'=>intval($productDetail["productId"]), 'quantity'=>1, 'price'=>$productDetail["productPrice"]));

            $found = false;
            if(!empty($_SESSION["cart_item"])) {
                    foreach($_SESSION["cart_item"] as $k => $v) {
                        if($productDetail["productId"] == $v['id']) {
                            $found= true;
                            if(empty($_SESSION["cart_item"][$k]["quantity"])) {
                                  $_SESSION["cart_item"][$k]["quantity"] = 0;
                            }
                            $_SESSION["cart_item"][$k]["quantity"] += 1;
                            break;
                        }
                    }
                if(!$found) {
                      $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
                }
            } else {
                  $_SESSION["cart_item"] = $itemArray;
            }
        }else {echo ''. mysqli_error($connection);}

         if(!empty($_SESSION['cart_volume'])){
                $_SESSION['cart_volume'] += 1;
            } else {
                $_SESSION['cart_volume'] = 1;
            }

  } else {
      echo 'no item';
</code>```

}

Title: Add items to cart in php using sessions

Body:
Am trying to update the quantity in add to cart session, but the below code only increases the quantity of the first item added twice and then perfoms a merge whenever any other item is added twice, kidly help

$('.add-to-cart-mt').on('click', function(e){
        e.preventDefault();
        var id =$(this).attr('id');
        $('#add-to-cat-dialog').dialog({
            autoOpen:false,
            modal:true,
            hide:"pluff",
            show:"slide",
            height:200,
            open: function() { $(".ui-dialog-titlebar-close").hide(); },

            buttons:{
                "Add":function (){
                    $('#add-to-cat-dialog').dialog("close");
                    $.ajax({
                        url: 'add_to_cart.php',
                        data: {  productId : id },

                        success: function (data) {
                            $('.top-cart-contain').empty();
                            $('.top-cart-contain').load("header_cart_summary.php");
                        },

                        error :function (data, textStatus, jqXHR) {  }
                    });
                },

                "Cancel":function (){
                    $(this).dialog("close");
                }
            }
        });

        $('#add-to-cat-dialog').dialog("open");
    });

session_start();
require './database.php';

      if(!empty($_GET["productId"])) {
          $id=$_GET["productId"];
            $productById = $connection->query("SELECT * FROM products WHERE productId='$id';");
            if($productById && (mysqli_num_rows($productById)>0)){
                echo 'query ok';
                $productDetail= mysqli_fetch_assoc($productById);
                $itemArray = array(
                    $productDetail["productId"]=>array(
                        'name'=>$productDetail["productName"],
                        'id'=>$productDetail["productId"],
                        'quantity'=>1,
                        'price'=>$productDetail["productPrice"],
                        'image'=>$productDetail["productsImage1"]
                        )
                    );

                if(!empty($_SESSION["cart_item"])) {
                    if(in_array($productDetail["productId"],array_keys($_SESSION["cart_item"]))) {
                        foreach($_SESSION["cart_item"] as $k => $v) {
                            if($productDetail["productId"] == $k) {
                                  if(empty($_SESSION["cart_item"][$k]["quantity"])) {
                                        $_SESSION["cart_item"][$k]["quantity"] = 0;
                                  }
                                  $_SESSION["cart_item"][$k]["quantity"] += 1;
                            }
                        }
                    } else {
                          $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
                    }
                } else {
                      $_SESSION["cart_item"] = $itemArray;
                }

                //set product count in the bag
                if(!empty($_SESSION['cart_volume'])){
                    $_SESSION['cart_volume'] += 1;
                } else {
                    $_SESSION['cart_volume'] = 1;
                }

            }else {echo ''. mysqli_error($connection);}

      } else {
          echo 'no item';
}

[enter image description here][1]

  <img class="first-img" src="./productImages/<?php echo $item['productsImage1']; ?>" style="height: 250px;"  alt="">

Quick view Wishlist Compare

<?php echo $item['productName']; ?>

 Special Price Ksh. <?php echo number_format($item['productPrice'], 2) ; ?>

                                              <button type="button" class="add-to-cart-mt" id="<?php echo $item['productId']; ?>">  Add to Cart </button>

Body:
The code below works fine as i required. Thanks to -Saleiro for his inputs.

[

  if(!empty($_GET["productId"])) {
      $id=intval($_GET["productId"]);
        $productById = $connection->query("SELECT * FROM products WHERE productId='$id' ");
        if($productById && (mysqli_num_rows($productById)>0)){
            $productDetail= mysqli_fetch_assoc($productById);
            $itemArray = array(intval($productDetail["productId"])=>array('name'=>$productDetail["productName"], 'id'=>intval($productDetail["productId"]), 'quantity'=>1, 'price'=>$productDetail["productPrice"]));

            $found = false;
            if(!empty($_SESSION["cart_item"])) {
                    foreach($_SESSION["cart_item"] as $k => $v) {
                        if($productDetail["productId"] == $v['id']) {
                            $found= true;
                            if(empty($_SESSION["cart_item"][$k]["quantity"])) {
                                  $_SESSION["cart_item"][$k]["quantity"] = 0;
                            }
                            $_SESSION["cart_item"][$k]["quantity"] += 1;
                            break;
                        }
                    }
                if(!$found) {
                      $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
                }
            } else {
                  $_SESSION["cart_item"] = $itemArray;
            }
        }else {echo ''. mysqli_error($connection);}

         if(!empty($_SESSION['cart_volume'])){
                $_SESSION['cart_volume'] += 1;
            } else {
                $_SESSION['cart_volume'] = 1;
            }

  } else {
      echo 'no item';

}


问:
Centering text links above three adjacent images
I have created a div containing three text links and I am placing them above three equal sized adjacent images. I need each piece of text to be centered above it's corresponding image.

Here is my div:

#catalogs ul {
  text-align: justify;
}

#catalogs ul:after {
  content: '';
  display: inline-block;
  width: 100%;
}

#catalogs ul:before {
  content: '';
  display: block;
  margin-top: -0.75em;
}

#catalogs li {
  display: inline-block;
  margin-right: 1.75em;
  position: relative;
  top: 1.25em;
  font-size: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="catalogs">
  <ul>
    <li><span style="text-decoration: underline; color: #0b5394;">Spring 2017</span></li>
    <li><span style="text-decoration: underline; color: #0b5394;">Summer 2017</span></li>
    <li><strong>Fall 2017 - available August 1st</strong></li>
  </ul>
</div></code>```

Here is what the page currently looks like using the above code:
page image

Can anyone help me modify the above css so that each text link is perfectly centered above its respective image?

答:
I would wrap each image and text in a separate DIV box - and then just use text-align: center to center the text. That should work!

I dunno if I would use list items for those though. Maybe a heading tag like h3 or a paragraph tag. Check out my pen below to see what I mean =D (I added inline style to my example here to add clarification I hope. I prefer my codepen example though, it's cleaner)

https://codepen.io/celtninja/pen/RgBzOZ

```<code><div id="one" style="float: left; margin: 5px;">
     <p style="text-align: center;">Image Heading</p>
     <img  style="text-align: center;"
     src="https://placeholdit.co//i/350x350?">
</div>
</code>```

Body:
I have created a div containing three text links and I am placing them above three equal sized adjacent images. I need each piece of text to be centered above it's corresponding image.

Here is my div:

#catalogs ul {
  text-align: justify;
}

#catalogs ul:after {
  content: '';
  display: inline-block;
  width: 100%;
}

#catalogs ul:before {
  content: '';
  display: block;
  margin-top: -0.75em;
}

#catalogs li {
  display: inline-block;
  margin-right: 1.75em;
  position: relative;
  top: 1.25em;
  font-size: 100%;
}

Spring 2017

Summer 2017

Fall 2017 - available August 1st

Here is what the page currently looks like using the above code:
page image

Can anyone help me modify the above css so that each text link is perfectly centered above its respective image?

Body:
I would wrap each image and text in a separate DIV box - and then just use text-align: center to center the text. That should work!

I dunno if I would use list items for those though. Maybe a heading tag like h3 or a paragraph tag. Check out my pen below to see what I mean =D (I added inline style to my example here to add clarification I hope. I prefer my codepen example though, it's cleaner)

https://codepen.io/celtninja/pen/RgBzOZ

<div id="one" style="float: left; margin: 5px;">
     <p style="text-align: center;">Image Heading</p>
     <img  style="text-align: center;"
     src="https://placeholdit.co//i/350x350?">
</div>


问:
How to automatically update a SQL database
So I'm working with a professor who wants me to create a SQL Database containing information from csv files (from the New York City Department of Transportation). I've written program that takes the csv file and converts it into the appropriate sql commands. So my question is, how do i automate the database so that every 5 minutes or so a program downloads the new csv file, runs it through my csv-to-SQL command program, and then enters the output from my csv-to-SQL command program into terminal (what I use to interface with my SQL database)? Is there a specific language I should look into, I've seen people talk about cron?</p>

答:
The simplest thing you could do is loop your script.

If you're running PHP you could do something like:

```<code>$running = true;
while ($running)
{
    // Your code that gets and converts CSV
    // and then saves it in SQL.

    $running = $some_error ? false : true;
    sleep(5000);
}
</code>```

I don't know what you're using but mind the logic, not the language.

Body:
The simplest thing you could do is loop your script.

If you're running PHP you could do something like:

$running = true;
while ($running)
{
    // Your code that gets and converts CSV
    // and then saves it in SQL.

    $running = $some_error ? false : true;
    sleep(5000);
}

I don't know what you're using but mind the logic, not the language.


问:
Populate subdocument in parent document Array Mongoose
I'm very new to JavaScript and Mongoose. I'm building a small project using express, mongoose and node.js.
I have a mongoose model - Client that has an Array of Transactions

```<code>    var Client = mongoose.model('Client', {
 name: {
   type: String,
   required: true,
   minlength: 1
 },
 email: {
   type: String
 },
 phone: {
   type: Number
 },
 createdAt: {
   type: Number,
   default: null
 },
 transactions: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Transaction' }],
 _creator: {
   type: mongoose.Schema.Types.ObjectId,
   required: true
 }
});

module.exports = {Client};
</code>```

This is Transaction model:

```<code>var Client = require('./client');

var Transaction = mongoose.model('Transaction',{
  _creator : { type: mongoose.Schema.Types.ObjectId, ref: 'Client' },
  amount : {type: Number, min: 0},
  date : {type: Number,default: null},
  total: {type: Number,default: null}
});

module.exports = {Transaction};
</code>```

When I POST a new Transaction it goes through and saves in db:

```<code> app.post('/clients/:id/transactions', authenticate, (req, res) => {
  var id = req.params.id;
  var transaction = new Transaction({
    amount: req.body.amount,
    date: new Date().getTime(),
    total: req.body.total,
    _creator: req.params.id
  })
  if (!ObjectID.isValid(id)) {
  return res.status(404).send();
  }

  transaction.save().then((doc) => {

    Client.findOneAndUpdate({
      _id: id,
      _creator: req.user._id,
      transactions: req.body.transaction
    });

    res.send(doc);
  }, (e) => {
    res.status(400).send(e);
  });

});
</code>```

I am also able to GET all the transactions associated with the client:

```<code>  app.get('/clients/:id/transactions', authenticate, (req, res) => {
  var id = req.params.id;
  if (!ObjectID.isValid(id)) {
  return res.status(404).send();
 }
 Transaction.find({
   _creator: id
 }).then((transactions) => {
  res.send({transactions});
 }).catch((e) => {
  res.status(400).send();
 });
});
</code>```

But when I make a GET call to '/clients' - Array of Transactions is empty:

```<code>    {
  "clients": [
    {
      "_id": "1095d6de3867001108b803",
      "name": "Peter",
      "email": "peter@gmail.com",
      "phone": 1232321,
      "_creator": "5321df6d57868ec7001108b801",
      "__v": 0,
      "transactions": [],
      "createdAt": null
    } ]
}
</code>```

And this is the GET call to /clients

```<code>    app.get('/clients', authenticate,  (req, res) => {
  Client.find({
    _creator: req.user._id,
  })
  .populate('transactions.transaction')
  .then((clients) => {
    res.send({clients});
  }, (e) => {
    res.status(400).send(e);
    console.log('Unable to get clients', e);
  })
});
</code>```

I know that I'm likely doing something completely wrong but I don't know where I need to look for my mistake. Please help!

答:
I would check if the client exist before adding a transaction. A transaction needs a client first.

Forewarn, I'm not a fan of then and catch so this answer does not use it. I normally use async.js when dealing with multiple asynchronous operations.

Anyways, I would do it like

```<code>app.post('/clients/:id/transactions', authenticate, (req, res) => {

    Client.findOne({ _id: req.params.id }, (err, client) => {
        if (err)
            return res.status(400).send(err);
        if (!client)
            return res.status(400).send(new Error('No client'));

        Transaction.create({
            amount: req.body.amount,
            date: new Date(), // I don't think you need .getTime()
            total: req.body.total,
            _creator: client._id
        }, (err, transaction) => {
            if (err)
                return res.status(400).send(err);

            client.transactions.push(transaction._id);
            client.save(err => {
                if (err)
                    return res.status(400).send(err);

                res.json(transaction);
            });
        });
    });

});
</code>```

Good idea to also turn on debugging mode to see your queries: mongoose.set('debug', true).

You might also find using timestamps option for Transaction schema more useful than explicitly using date field

To get clients with their transactions

```<code>app.get('/clients', authenticate,  (req, res) => {
    Client.find({ _creator: req.user._id }).populate('transactions').exec((err, clients) => {
        if (err)
            return res.status(400).send(err);
        res.json(clients);
    });
});
</code>```

Body:
I'm very new to JavaScript and Mongoose. I'm building a small project using express, mongoose and node.js.
I have a mongoose model - Client that has an Array of Transactions

    var Client = mongoose.model('Client', {
 name: {
   type: String,
   required: true,
   minlength: 1
 },
 email: {
   type: String
 },
 phone: {
   type: Number
 },
 createdAt: {
   type: Number,
   default: null
 },
 transactions: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Transaction' }],
 _creator: {
   type: mongoose.Schema.Types.ObjectId,
   required: true
 }
});

module.exports = {Client};

This is Transaction model:

var Client = require('./client');

var Transaction = mongoose.model('Transaction',{
  _creator : { type: mongoose.Schema.Types.ObjectId, ref: 'Client' },
  amount : {type: Number, min: 0},
  date : {type: Number,default: null},
  total: {type: Number,default: null}
});

module.exports = {Transaction};

When I POST a new Transaction it goes through and saves in db:

 app.post('/clients/:id/transactions', authenticate, (req, res) => {
  var id = req.params.id;
  var transaction = new Transaction({
    amount: req.body.amount,
    date: new Date().getTime(),
    total: req.body.total,
    _creator: req.params.id
  })
  if (!ObjectID.isValid(id)) {
  return res.status(404).send();
  }

  transaction.save().then((doc) => {

    Client.findOneAndUpdate({
      _id: id,
      _creator: req.user._id,
      transactions: req.body.transaction
    });

    res.send(doc);
  }, (e) => {
    res.status(400).send(e);
  });

});

I am also able to GET all the transactions associated with the client:

  app.get('/clients/:id/transactions', authenticate, (req, res) => {
  var id = req.params.id;
  if (!ObjectID.isValid(id)) {
  return res.status(404).send();
 }
 Transaction.find({
   _creator: id
 }).then((transactions) => {
  res.send({transactions});
 }).catch((e) => {
  res.status(400).send();
 });
});

But when I make a GET call to '/clients' - Array of Transactions is empty:

    {
  "clients": [
    {
      "_id": "1095d6de3867001108b803",
      "name": "Peter",
      "email": "peter@gmail.com",
      "phone": 1232321,
      "_creator": "5321df6d57868ec7001108b801",
      "__v": 0,
      "transactions": [],
      "createdAt": null
    } ]
}

And this is the GET call to /clients

    app.get('/clients', authenticate,  (req, res) => {
  Client.find({
    _creator: req.user._id,
  })
  .populate('transactions.transaction')
  .then((clients) => {
    res.send({clients});
  }, (e) => {
    res.status(400).send(e);
    console.log('Unable to get clients', e);
  })
});

I know that I'm likely doing something completely wrong but I don't know where I need to look for my mistake. Please help!

Body:
I would check if the client exist before adding a transaction. A transaction needs a client first.

Forewarn, I'm not a fan of then and catch so this answer does not use it. I normally use async.js when dealing with multiple asynchronous operations.

Anyways, I would do it like

app.post('/clients/:id/transactions', authenticate, (req, res) => {

    Client.findOne({ _id: req.params.id }, (err, client) => {
        if (err)
            return res.status(400).send(err);
        if (!client)
            return res.status(400).send(new Error('No client'));

        Transaction.create({
            amount: req.body.amount,
            date: new Date(), // I don't think you need .getTime()
            total: req.body.total,
            _creator: client._id
        }, (err, transaction) => {
            if (err)
                return res.status(400).send(err);

            client.transactions.push(transaction._id);
            client.save(err => {
                if (err)
                    return res.status(400).send(err);

                res.json(transaction);
            });
        });
    });

});

Good idea to also turn on debugging mode to see your queries: mongoose.set('debug', true).

You might also find using timestamps option for Transaction schema more useful than explicitly using date field

To get clients with their transactions

app.get('/clients', authenticate,  (req, res) => {
    Client.find({ _creator: req.user._id }).populate('transactions').exec((err, clients) => {
        if (err)
            return res.status(400).send(err);
        res.json(clients);
    });
});