问:
CLion debugger not working when using gcc
Im trying to configure CLion so that I can use openMP. When using the default settings on my Mac, the compiler is clang. Default Apple clang does not support openMP.

When I change my compiler to GCC, the debugger will not stop at breakpoints. The program just runs as it would when executing the compiled file.

The CMakeLists.txt file below works perfectly with CLion debugger. When I uncomment out the compiler flags, the debugger ignores the breakpoints.

```<code>cmake_minimum_required(VERSION 3.8)
project(CLionTest)

set(CMAKE_C_STANDARD 99)
#set(CMAKE_C_COMPILER /usr/local/bin/gcc-7)
#set(CMAKE_C_FLAGS -fopenmp)
#set(CMAKE_C_FLAGS_DEBUG "-D_DEBUG")

set(MAIN main.c)
add_executable(CLionTest ${MAIN})

add_custom_target(CLionTestMake COMMAND make all WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
</code>```

How do I fix this?

Toolchain settings:
CMake executable: Bundeled CMake 3.8.2
Debugger: Bundled LLDB 3.9.0

main.c:

```<code>#include <stdio.h>
#include <unistd.h>
#ifdef _OPENMP
  #include <omp.h>
#endif

int main() {
    printf("Hello, World!\n");

    #pragma omp parallel
    {
        #ifdef _OPENMP
          int size = omp_get_num_threads();
          int rank = omp_get_thread_num();
        #else
          int rank = 0;
          int size = 1;
        #endif
        printf("%d/%d\n", rank, size);
    };

    return 0;
}
</code>```

答:
```<code>set(CMAKE_C_FLAGS -fopenmp)
set(CMAKE_C_FLAGS_DEBUG "-D_DEBUG")
</code>```

You are replacing the C flags instead of appending them, so you are dropping the builtin -g option that generates debug symbols. Instead, do

```<code>set(CMAKE_C_FLAGS "${CMAKE_CFLAGS} -fopenmp")
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -D_DEBUG")
</code>```

Body:
Im trying to configure CLion so that I can use openMP. When using the default settings on my Mac, the compiler is clang. Default Apple clang does not support openMP.

When I change my compiler to GCC, the debugger will not stop at breakpoints. The program just runs as it would when executing the compiled file.

The CMakeLists.txt file below works perfectly with CLion debugger. When I uncomment out the compiler flags, the debugger ignores the breakpoints.

cmake_minimum_required(VERSION 3.8)
project(CLionTest)

set(CMAKE_C_STANDARD 99)
#set(CMAKE_C_COMPILER /usr/local/bin/gcc-7)
#set(CMAKE_C_FLAGS -fopenmp)
#set(CMAKE_C_FLAGS_DEBUG "-D_DEBUG")

set(MAIN main.c)
add_executable(CLionTest ${MAIN})

add_custom_target(CLionTestMake COMMAND make all WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})

How do I fix this?

Toolchain settings:
CMake executable: Bundeled CMake 3.8.2
Debugger: Bundled LLDB 3.9.0

main.c:

#include <stdio.h>
#include <unistd.h>
#ifdef _OPENMP
  #include <omp.h>
#endif

int main() {
    printf("Hello, World!\n");

    #pragma omp parallel
    {
        #ifdef _OPENMP
          int size = omp_get_num_threads();
          int rank = omp_get_thread_num();
        #else
          int rank = 0;
          int size = 1;
        #endif
        printf("%d/%d\n", rank, size);
    };

    return 0;
}

Body:
set(CMAKE_C_FLAGS -fopenmp)
set(CMAKE_C_FLAGS_DEBUG "-D_DEBUG")

You are replacing the C flags instead of appending them, so you are dropping the builtin -g option that generates debug symbols. Instead, do

set(CMAKE_C_FLAGS "${CMAKE_CFLAGS} -fopenmp")
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -D_DEBUG")


来源: stackexchange

问:
Deserialize bytes array in C++ which was serialized in C#
I have an array of CameraSpacePoint, which I have converted into bytes in C# programming language. The CameraSpacePoint is defined as follow:

```<code>namespace Microsoft.Kinect
{
    public struct CameraSpacePoint
    {
        public float X;
        public float Y;
        public float Z;
   }
}
</code>```

To convert the array of CameraSpacePoint into bytes, I used the following method in C#:

```<code>public static byte[] ObjectToByteArray(Object obj)
{
    BinaryFormatter bf = new BinaryFormatter();
    using (var ms = new MemoryStream())
    {
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }
}
</code>```

The bytes array is then transferred using TCP.  I am trying to receive this byte array on the other machine in the following manner:

```<code>#include <ros/ros.h>
#include <boost/asio.hpp>
constexpr size_t data_size = 512 * 424;
unsigned char data_buffer[data_size];
boost::asio::read(socket, boost::asio::buffer(data_buffer, data_size));
</code>```

I declared a similar class in C++ as follow:

```<code>class CameraSpacePoint
{
public:
    float X;
    float Y;
    float Z;
};
</code>```

I want to know that how to convert back byte array into my defined CameraSpacePoint object of array?

答:
Memory layout and serialization of objects in C# programming language has nothing to do with similar concepts in C/C++. Having different compilers/OSes, even in a C++ to C++ scenario you may get different memory layouts for same struct or class (according to memory layout, etc.).

What you really need is a common protocol for both languages to serialize and deserialize similar objects. There are some serialization libraries out there which support both languages:

Google's Protocol Buffers Supports both C# and C++, it's platform-neutral. (You can use it to serialize/deserialize between big-endian ARM and little-endian x86_64 for example)

Microsoft Bond Supports both C# and C++

ContentLicense: CC BY-SA 3.0

Body:
I have an array of CameraSpacePoint, which I have converted into bytes in C# programming language. The CameraSpacePoint is defined as follow:

namespace Microsoft.Kinect
{
    public struct CameraSpacePoint
    {
        public float X;
        public float Y;
        public float Z;
   }
}

To convert the array of CameraSpacePoint into bytes, I used the following method in C#:

public static byte[] ObjectToByteArray(Object obj)
{
    BinaryFormatter bf = new BinaryFormatter();
    using (var ms = new MemoryStream())
    {
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }
}

The bytes array is then transferred using TCP.  I am trying to receive this byte array on the other machine in the following manner:

#include <ros/ros.h>
#include <boost/asio.hpp>
constexpr size_t data_size = 512 * 424;
unsigned char data_buffer[data_size];
boost::asio::read(socket, boost::asio::buffer(data_buffer, data_size));

I declared a similar class in C++ as follow:

class CameraSpacePoint
{
public:
    float X;
    float Y;
    float Z;
};

I want to know that how to convert back byte array into my defined CameraSpacePoint object of array?


问:
MS Access - How to change the linked table path by amend the table
Below query allow me to show all linked table and its corresponding database path

```<code>SELECT DISTINCTROW msysobjects.Name, msysobjects.Database, msysobjects.Connect
FROM msysobjects WHERE (((msysobjects.Type)=6 Or (msysobjects.Type) Like "dsn*")) ORDER BY msysobjects.Database;
</code>```

Output

```<code>Name                    Database                             Connect
Account Transactions    C:\Users\Desktop\Database6_be.accdb
Categories              C:\Users\Desktop\Database6_be.accdb
Filters                 C:\Users\Desktop\Database6_be.accdb
tblAuditLog             C:\Users\Desktop\Database6_be.accdb
</code>```

As i renamed the database for particular 2 tables, while i unable to amend the path. Is there any way i can amend the linked table path by amend the table?

答:
Yes, you can either do it through VBA, or through the GUI

Through the GUI (Access 2010):

You can use the following VBA sub to change the connection strings on certain tables (you need to provide both the old and new connection string):

Public Sub ChangeConnection(OldStr As String, NewStr As String)
    Dim td As DAO.TableDef
    Dim db As DAO.Database
    Set db = CurrentDb()
    For Each td In db.TableDefs
        With td
            If .Connect = OldStr Then
                .Connect = NewStr
                .RefreshLink
            End If
        End With
    Next td
End Sub
```

<p>Or, you can use the following sub to change one specific table</p>

<pre class="lang-vb prettyprint-override"><code>Public Sub ChangeTableConnection(Tablename As String, NewStr As String)
    Dim td As DAO.TableDef
    Dim db As DAO.Database
    Set db = CurrentDb()
    Set td = db.TableDefs(Tablename)
    td.Connect = NewStr
    td.RefreshLink
End Sub
</code>```

Body:
Below query allow me to show all linked table and its corresponding database path

SELECT DISTINCTROW msysobjects.Name, msysobjects.Database, msysobjects.Connect
FROM msysobjects WHERE (((msysobjects.Type)=6 Or (msysobjects.Type) Like "dsn*")) ORDER BY msysobjects.Database;

Output

Name                    Database                             Connect
Account Transactions    C:\Users\Desktop\Database6_be.accdb
Categories              C:\Users\Desktop\Database6_be.accdb
Filters                 C:\Users\Desktop\Database6_be.accdb
tblAuditLog             C:\Users\Desktop\Database6_be.accdb

As i renamed the database for particular 2 tables, while i unable to amend the path. Is there any way i can amend the linked table path by amend the table?

Body:
Yes, you can either do it through VBA, or through the GUI

Through the GUI (Access 2010):

You can use the following VBA sub to change the connection strings on certain tables (you need to provide both the old and new connection string):

Public Sub ChangeConnection(OldStr As String, NewStr As String)
    Dim td As DAO.TableDef
    Dim db As DAO.Database
    Set db = CurrentDb()
    For Each td In db.TableDefs
        With td
            If .Connect = OldStr Then
                .Connect = NewStr
                .RefreshLink
            End If
        End With
    Next td
End Sub

Or, you can use the following sub to change one specific table

Public Sub ChangeTableConnection(Tablename As String, NewStr As String)
    Dim td As DAO.TableDef
    Dim db As DAO.Database
    Set db = CurrentDb()
    Set td = db.TableDefs(Tablename)
    td.Connect = NewStr
    td.RefreshLink
End Sub


问:
Temperature conversion in Python: How to convert int (0 - 255) which is a byte object to degrees Celsius in Python
We are currently working on an Arduino Uno project and getting stuck at the conversion of the integer data to degrees celcius. This code is working however it converts the binary packed data (\xd01) etc. to int (0-255). Our question is: how to convert the integer value to read out a certain degree of Celcius. For example: int 2 = 2 degrees celcius and 255 = 35 degrees Celcius

This is our Python code with the Pyserial module

```<code>import serial
import struct
ser = serial.Serial('COM3', 19200, timeout=5)
while True:
    tempdata = ser.read(2)
    x= struct.unpack('!BB', tempdata)
    print(x)
```

And this is the code of the temperature conversion on our Arduino Uno, it is written in C.

```<code>
    #define F_CPU 16E6</p>

// output on USB = PD1 = board pin 1
// datasheet p.190; F_OSC = 16 MHz & baud rate = 19.200
#define UBBRVAL 51

void uart_init()
{
    // set the baud rate
    UBRR0H = 0;
    UBRR0L = UBBRVAL;
    // disable U2X mode
    UCSR0A = 0;
    // enable transmitter
    UCSR0B = _BV(TXEN0);
    // set frame format : asynchronous, 8 data bits, 1 stop bit, no parity
    UCSR0C = _BV(UCSZ01) | _BV(UCSZ00);
}
void transmit(uint8_t data)
{
    // wait for an empty transmit buffer
    // UDRE is set when the transmit buffer is empty
    loop_until_bit_is_set(UCSR0A, UDRE0);
    // send the data
    UDR0 = data;
}

void init_adc()
{
    // ref=Vcc, left adjust the result (8 bit resolution),
    // select channel 0 (PC0 = input)
    ADMUX = (1<<REFS0);
    // enable the ADC & prescale = 128
    ADCSRA = (1<<ADEN)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);
}
uint8_t get_adc_value()
{

    //ADMUX |= 1
    ADCSRA |= (1<<ADSC); // start conversion
    loop_until_bit_is_clear(ADCSRA, ADSC);
    return ADC; // 8-bit resolution, left adjusted
}

/*
((value / 1024 * 5) - 0. 5) * 100
*/

int main(void) {
    init_adc();
    uart_init();
    //int x;
    while(1)
    {

        int x = get_adc_value();
        int temp = ((((float) x / 1024) * 5) - 0.5) * 100;
        transmit(temp);
        _delay_ms(200);
    }
}
</code>```

答:
The conversion from ADC value to temp will most likely depend on what type of temperature sensor you are using. I recommend looking a the datasheet of your temp sensor.
If you are using a 'TMP36', you can convert using this formula:

Centigrade temperature = [(analog voltage in mV) - 500] / 10

Source: https://learn.adafruit.com/tmp36-temperature-sensor/using-a-temp-sensor

If you a using a thermocouple, you'll need to look at the table of correspondance for the type you are using (e.g. type K: https://www.omega.fr/temperature/Z/pdf/z204-206.pdf)

Body:
We are currently working on an Arduino Uno project and getting stuck at the conversion of the integer data to degrees celcius. This code is working however it converts the binary packed data (\xd01) etc. to int (0-255). Our question is: how to convert the integer value to read out a certain degree of Celcius. For example: int 2 = 2 degrees celcius and 255 = 35 degrees Celcius

This is our Python code with the Pyserial module

import serial
import struct
ser = serial.Serial('COM3', 19200, timeout=5)
while True:
    tempdata = ser.read(2)
    x= struct.unpack('!BB', tempdata)
    print(x)

And this is the code of the temperature conversion on our Arduino Uno, it is written in C.

    #define F_CPU 16E6

// output on USB = PD1 = board pin 1
// datasheet p.190; F_OSC = 16 MHz & baud rate = 19.200
#define UBBRVAL 51

void uart_init()
{
    // set the baud rate
    UBRR0H = 0;
    UBRR0L = UBBRVAL;
    // disable U2X mode
    UCSR0A = 0;
    // enable transmitter
    UCSR0B = _BV(TXEN0);
    // set frame format : asynchronous, 8 data bits, 1 stop bit, no parity
    UCSR0C = _BV(UCSZ01) | _BV(UCSZ00);
}
void transmit(uint8_t data)
{
    // wait for an empty transmit buffer
    // UDRE is set when the transmit buffer is empty
    loop_until_bit_is_set(UCSR0A, UDRE0);
    // send the data
    UDR0 = data;
}

void init_adc()
{
    // ref=Vcc, left adjust the result (8 bit resolution),
    // select channel 0 (PC0 = input)
    ADMUX = (1<<REFS0);
    // enable the ADC & prescale = 128
    ADCSRA = (1<<ADEN)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0);
}
uint8_t get_adc_value()
{

    //ADMUX |= 1
    ADCSRA |= (1<<ADSC); // start conversion
    loop_until_bit_is_clear(ADCSRA, ADSC);
    return ADC; // 8-bit resolution, left adjusted
}

/*
((value / 1024 * 5) - 0. 5) * 100
*/

int main(void) {
    init_adc();
    uart_init();
    //int x;
    while(1)
    {

        int x = get_adc_value();
        int temp = ((((float) x / 1024) * 5) - 0.5) * 100;
        transmit(temp);
        _delay_ms(200);
    }
}


问:
Jenkins Configuration error
I am getting an error in Jenkins while running my build as mentioned in below:

Can anyone help me on this?

答: Try to start a command prompt as an administrator</p>

Title: Jenkins Configuration error


问:
What is the best metric to evaluate how well a CNN is trained? validation error or training loss?
I want to train a CNN, but I want to use all data to train the network thus not performing validation. Is this a good choice? am I risking to overfit my CNN if using only the training loss as the criterium for early stopping the CNN?

In other words, what is the best 'monitor' parameter in KERAS (for example) for early stopping, among the options below?

```<code>early_stopper=EarlyStopping(monitor='train_loss', min_delta=0.0001, patience=20)
early_stopper=EarlyStopping(monitor='train_acc', min_delta=0.0001, patience=20)
early_stopper=EarlyStopping(monitor='val_loss', min_delta=0.0001, patience=20)
early_stopper=EarlyStopping(monitor='val_acc', min_delta=0.0001, patience=20)
</code>```

There is a discussion like this in stackoverflow Keras: Validation error is a good measure for stopping criteria or validation accuracy?, however, they talk about the validation only. Is it better using criteria in validation or training data to early stopping a CNN training?

答:
I want to train a CNN, but I want to use all data to train the network thus not performing validation. Is this a good choice? am I
  risking to overfit my CNN if using only the training loss as the
  criterium for early stopping the CNN?

Answer: No, your purpose is to predict on new samples, even you got 100% training accuracy but you may got bad prediction on new samples. You don't have a way to check whether you have an overfitting

In other words, what is the best 'monitor' parameter in KERAS (for example) for early stopping, among the options below?

Answer: It should be the criteria closest to the reality

early_stopper=EarlyStopping(monitor='val_acc', min_delta=0.0001, patience=20)

In addition, you may need train, validate, and test data. Train is to train your model, validate is to perform validating some models+parameters and select the best, and test is to verify independently your result (it's not used for choosing models, parameters, so it's equivalent to new samples)

Body:
I want to train a CNN, but I want to use all data to train the network thus not performing validation. Is this a good choice? am I risking to overfit my CNN if using only the training loss as the criterium for early stopping the CNN?

In other words, what is the best 'monitor' parameter in KERAS (for example) for early stopping, among the options below?

early_stopper=EarlyStopping(monitor='train_loss', min_delta=0.0001, patience=20)
early_stopper=EarlyStopping(monitor='train_acc', min_delta=0.0001, patience=20)
early_stopper=EarlyStopping(monitor='val_loss', min_delta=0.0001, patience=20)
early_stopper=EarlyStopping(monitor='val_acc', min_delta=0.0001, patience=20)

There is a discussion like this in stackoverflow Keras: Validation error is a good measure for stopping criteria or validation accuracy?, however, they talk about the validation only. Is it better using criteria in validation or training data to early stopping a CNN training?


问:
Django CreateView didn't return an HttpResponse object
Can't figure out why CreateView doesn't return HttpResponse. For now, I use this view just for posting (no GET). I thought that set self.success_url should be enough (as you can see in def post).

```<code>class TripCreationView(CreateView):
    form_class = TripCreationForm
    template_name = 'frontend/homepage.html'

    def post(self, request, *args, **kwargs):
        self.success_url = request.POST.get('success_url') or reverse('frontend:homepage')
        super(TripCreationView, self).post(self, request, *args, **kwargs)
    #
    # def form_valid(self, form):
    #     trip = form.save(self.request)
    #     return HttpResponseRedirect(self.success_url)

    def get_form_kwargs(self):
        kwargs = super(TripCreationView, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs
</code>```

Do you know what to do?

答:
You forgot a return statement.</p>

```<code>def post(self, request, *args, **kwargs):
    self.success_url = request.POST.get('success_url') or reverse('frontend:homepage')
    return super(TripCreationView, self).post(self, request, *args, **kwargs)
</code>```

Body:
Can't figure out why CreateView doesn't return HttpResponse. For now, I use this view just for posting (no GET). I thought that set self.success_url should be enough (as you can see in def post).

class TripCreationView(CreateView):
    form_class = TripCreationForm
    template_name = 'frontend/homepage.html'

    def post(self, request, *args, **kwargs):
        self.success_url = request.POST.get('success_url') or reverse('frontend:homepage')
        super(TripCreationView, self).post(self, request, *args, **kwargs)
    #
    # def form_valid(self, form):
    #     trip = form.save(self.request)
    #     return HttpResponseRedirect(self.success_url)

    def get_form_kwargs(self):
        kwargs = super(TripCreationView, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs

Do you know what to do?

Body:
You forgot a return statement.

def post(self, request, *args, **kwargs):
    self.success_url = request.POST.get('success_url') or reverse('frontend:homepage')
    return super(TripCreationView, self).post(self, request, *args, **kwargs)


问:
how can i check if image exists in assets folder using angular 4
I need to check if a image exists in the folder using Angular 4.I have a list of image name that is returned from the server. What I need is to check if that image exists in the asset folder. Any help or idea would be great.</p>

答:
Try this. Answer found on link

```<code>// The "callback" argument is called with either true or false
// depending on whether the image at "url" exists or not.
function imageExists(url, callback) {
  var img = new Image();
  img.onload = function() { callback(true); };
  img.onerror = function() { callback(false); };
  img.src = url;
}

// Sample usage
var imageUrl = 'http://www.google.com/images/srpr/nav_logo14.png';
imageExists(imageUrl, function(exists) {
  console.log('RESULT: url=' + imageUrl + ', exists=' + exists);
});
</code>```

I would like to warn you. Becareful with it, It can run you to performance issue for checking more images at once due to it's loading images to memory if exists.

Body:
Try this. Answer found on link

// The "callback" argument is called with either true or false
// depending on whether the image at "url" exists or not.
function imageExists(url, callback) {
  var img = new Image();
  img.onload = function() { callback(true); };
  img.onerror = function() { callback(false); };
  img.src = url;
}

// Sample usage
var imageUrl = 'http://www.google.com/images/srpr/nav_logo14.png';
imageExists(imageUrl, function(exists) {
  console.log('RESULT: url=' + imageUrl + ', exists=' + exists);
});

I would like to warn you. Becareful with it, It can run you to performance issue for checking more images at once due to it's loading images to memory if exists.


问:
alpha in sklearn LogisticRegression python
What is the default alpha in sklearn LogisticRegression with l1 penalty?</p>

```<code>lmMod = LogisticRegression(penalty='l1')
</code>```

答:
According to the documentation,

The parameter used for the the regularization is the parameter C in the input of the call. I represents the inverse of regularization strength. The default value is equal to 1.

C : float, default: 1.0 Inverse of regularization strength; must be a
  positive float. Like in support vector machines, smaller values
  specify stronger regularization.

Body:
What is the default alpha in sklearn LogisticRegression with l1 penalty?

lmMod = LogisticRegression(penalty='l1')


问:
Angular 2 cache http request using the power of observables
I've found a number of approaches to cache reactive observables and, more specifically, the results of http requests. However, I am not fully satisfied with the proposed solutions because of the reasons below:

1. This answer https://stackoverflow.com/a/36417240/1063354 uses a private field to store the result of the first request and reuses it in all subsequent calls.

the code:

```<code>private data: Data;
getData() {
    if(this.data) {
        return Observable.of(this.data);
    } else {
        ...
    }
}
</code>```

The sad thing is that the power of observables is completely ignored - you do all the stuff manually. In fact I wouldn't look for a proper solution if I was satisfied with assigning the result to a local variable/field.
Another important thing which I consider a bad practice is that a service should not have a state - i.e. should have no private fields containing data which are changed from call to call. And it's fairly easy to clear the cache - just set this.data to null and the request will be reexecuted.

2. This answer https://stackoverflow.com/a/36413003/1063354 proposes to use ReplaySubject:

```<code>    private dataObs$ = new ReplaySubject(1);

    constructor(private http: Http) { }

    getData(forceRefresh?: boolean) {
        // If the Subject was NOT subscribed before OR if forceRefresh is requested
        if (!this.dataObs$.observers.length || forceRefresh) {
            this.http.get('http://jsonplaceholder.typicode.com/posts/2').subscribe(
                data => this.dataObs$.next(data),
                error => {
                    this.dataObs$.error(error);
                    // Recreate the Observable as after Error we cannot emit data anymore
                    this.dataObs$ = new ReplaySubject(1);
                }
            );
        }

        return this.dataObs$;
    }
</code>```

Looks pretty awesome (and again - no problem to clear the cache) but I am not able to map the result of this call, i.e.

```<code>service.getData().map(data => anotherService.processData(data))
</code>```

which happens because the underlying observer has not called its complete method. I'm pretty sure that a lot of reactive methods won't work here as well. To actually get the data I have to subscribe to this observable but I don't want to do it: I want to get the cached data for one of my components via a resolver which should return an Observable (or Promise), not a Subscription:

The route

```<code>{
    path: 'some-path',
    component: SomeComponent,
    resolve: {
      defaultData: DefaultDataResolver
    }
}
</code>```

The Resolver

```<code>...
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Data> {
    return this.service.getData();
}
</code>```

The component is never activated because its dependency is never resolved.

3. Here https://stackoverflow.com/a/36296015/1063354 I found a proposal to use publishLast().refCount().

the code:

```<code>getCustomer() {
    return this.http.get('/someUrl')
        .map(res => res.json()).publishLast().refCount();
}
</code>```

This satisfies my demands for both caching and resolving BUT I haven't found a clean and neat solution to clear the cache.

Am I missing something? Could anyone think out a better way to cache reactive observables being able to map their results as well as refresh the cached data once it's no longer relevant?

答:
This simple class caches the result so you can subscribe to .value many times and makes only 1 request. You can also use .reload() to make new request and publish data.

You can use it like:

```<code>let res = new RestResource(() => this.http.get('inline.bundleo.js'));

res.status.subscribe((loading)=>{
    console.log('STATUS=',loading);
});

res.value.subscribe((value) => {
  console.log('VALUE=', value);
});
</code>```

and the source:

```<code>export class RestResource {

  static readonly LOADING: string = 'RestResource_Loading';
  static readonly ERROR: string = 'RestResource_Error';
  static readonly IDLE: string = 'RestResource_Idle';

  public value: Observable<any>;
  public status: Observable<string>;
  private loadStatus: Observer<any>;

  private reloader: Observable<any>;
  private reloadTrigger: Observer<any>;

  constructor(requestObservableFn: () => Observable<any>) {
    this.status = Observable.create((o) => {
      this.loadStatus = o;
    });

    this.reloader = Observable.create((o: Observer<any>) => {
      this.reloadTrigger = o;
    });

    this.value = this.reloader.startWith(null).switchMap(() => {
      if (this.loadStatus) {
        this.loadStatus.next(RestResource.LOADING);
      }
      return requestObservableFn()
        .map((res) => {
          if (this.loadStatus) {
            this.loadStatus.next(RestResource.IDLE);
          }
          return res;
        }).catch((err)=>{
          if (this.loadStatus) {
            this.loadStatus.next(RestResource.ERROR);
          }
          return Observable.of(null);
        });
    }).publishReplay(1).refCount();
  }

  reload() {
    this.reloadTrigger.next(null);
  }

}
</code>```

Body:
I've found a number of approaches to cache reactive observables and, more specifically, the results of http requests. However, I am not fully satisfied with the proposed solutions because of the reasons below:

1. This answer https://stackoverflow.com/a/36417240/1063354 uses a private field to store the result of the first request and reuses it in all subsequent calls.

the code:

private data: Data;
getData() {
    if(this.data) {
        return Observable.of(this.data);
    } else {
        ...
    }
}

The sad thing is that the power of observables is completely ignored - you do all the stuff manually. In fact I wouldn't look for a proper solution if I was satisfied with assigning the result to a local variable/field.
Another important thing which I consider a bad practice is that a service should not have a state - i.e. should have no private fields containing data which are changed from call to call. And it's fairly easy to clear the cache - just set this.data to null and the request will be reexecuted.

2. This answer https://stackoverflow.com/a/36413003/1063354 proposes to use ReplaySubject:

    private dataObs$ = new ReplaySubject(1);

    constructor(private http: Http) { }

    getData(forceRefresh?: boolean) {
        // If the Subject was NOT subscribed before OR if forceRefresh is requested
        if (!this.dataObs$.observers.length || forceRefresh) {
            this.http.get('http://jsonplaceholder.typicode.com/posts/2').subscribe(
                data => this.dataObs$.next(data),
                error => {
                    this.dataObs$.error(error);
                    // Recreate the Observable as after Error we cannot emit data anymore
                    this.dataObs$ = new ReplaySubject(1);
                }
            );
        }

        return this.dataObs$;
    }

Looks pretty awesome (and again - no problem to clear the cache) but I am not able to map the result of this call, i.e.

service.getData().map(data => anotherService.processData(data))

which happens because the underlying observer has not called its complete method. I'm pretty sure that a lot of reactive methods won't work here as well. To actually get the data I have to subscribe to this observable but I don't want to do it: I want to get the cached data for one of my components via a resolver which should return an Observable (or Promise), not a Subscription:

The route

{
    path: 'some-path',
    component: SomeComponent,
    resolve: {
      defaultData: DefaultDataResolver
    }
}

The Resolver

...
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Data> {
    return this.service.getData();
}

The component is never activated because its dependency is never resolved.

3. Here https://stackoverflow.com/a/36296015/1063354 I found a proposal to use publishLast().refCount().

the code:

getCustomer() {
    return this.http.get('/someUrl')
        .map(res => res.json()).publishLast().refCount();
}

This satisfies my demands for both caching and resolving BUT I haven't found a clean and neat solution to clear the cache.

Am I missing something? Could anyone think out a better way to cache reactive observables being able to map their results as well as refresh the cached data once it's no longer relevant?

Body:
This simple class caches the result so you can subscribe to .value many times and makes only 1 request. You can also use .reload() to make new request and publish data.

You can use it like:

let res = new RestResource(() => this.http.get('inline.bundleo.js'));

res.status.subscribe((loading)=>{
    console.log('STATUS=',loading);
});

res.value.subscribe((value) => {
  console.log('VALUE=', value);
});

and the source:

export class RestResource {

  static readonly LOADING: string = 'RestResource_Loading';
  static readonly ERROR: string = 'RestResource_Error';
  static readonly IDLE: string = 'RestResource_Idle';

  public value: Observable<any>;
  public status: Observable<string>;
  private loadStatus: Observer<any>;

  private reloader: Observable<any>;
  private reloadTrigger: Observer<any>;

  constructor(requestObservableFn: () => Observable<any>) {
    this.status = Observable.create((o) => {
      this.loadStatus = o;
    });

    this.reloader = Observable.create((o: Observer<any>) => {
      this.reloadTrigger = o;
    });

    this.value = this.reloader.startWith(null).switchMap(() => {
      if (this.loadStatus) {
        this.loadStatus.next(RestResource.LOADING);
      }
      return requestObservableFn()
        .map((res) => {
          if (this.loadStatus) {
            this.loadStatus.next(RestResource.IDLE);
          }
          return res;
        }).catch((err)=>{
          if (this.loadStatus) {
            this.loadStatus.next(RestResource.ERROR);
          }
          return Observable.of(null);
        });
    }).publishReplay(1).refCount();
  }

  reload() {
    this.reloadTrigger.next(null);
  }

}


问:
MySQL how to UPDATE a field in one table based on values in another table
This may have been asked before but my issue is maybe more complex.

I am working with an OpenCart database and need to update the images for categories. The image names are the same as the category names, just lowercase and appended with '.jpg'. The problem is, I only want to update specific entries, ones that are within a certain parent ID.

My SELECT to get the relevant category IDs is this:

```<code>SELECT c.category_id FROM oc23_category c LEFT JOIN oc23_category_description cd ON cd.category_id = c.category_id WHERE c.parent_id = 71
</code>```

So I attempted to use this SELECT statement to reference where to update the images:

```<code>UPDATE oc23_category SET image = LOWER(oc23_category_description.name) WHERE category_id IN(SELECT c.category_id FROM oc23_category c LEFT JOIN oc23_category_description cd ON cd.category_id = c.category_id WHERE c.parent_id = 71);
</code>```

But the error I get is:

You can't specify target table 'oc23_category' for update in FROM
  clause

I'm not sure what this means or how to rectify it. Any help with this is appreciated, thank you.

答:
Use join instead of sub query</p>

```<code>UPDATE
  oc23_category c
JOIN oc23_category_description cd
     ON cd.category_id = c.category_id
SET
  c.image = LOWER(cd.name)
WHERE c.parent_id = 71
</code>```

Body:
This may have been asked before but my issue is maybe more complex.

I am working with an OpenCart database and need to update the images for categories. The image names are the same as the category names, just lowercase and appended with '.jpg'. The problem is, I only want to update specific entries, ones that are within a certain parent ID.

My SELECT to get the relevant category IDs is this:

SELECT c.category_id FROM oc23_category c LEFT JOIN oc23_category_description cd ON cd.category_id = c.category_id WHERE c.parent_id = 71

So I attempted to use this SELECT statement to reference where to update the images:

UPDATE oc23_category SET image = LOWER(oc23_category_description.name) WHERE category_id IN(SELECT c.category_id FROM oc23_category c LEFT JOIN oc23_category_description cd ON cd.category_id = c.category_id WHERE c.parent_id = 71);

But the error I get is:

You can't specify target table 'oc23_category' for update in FROM
  clause

I'm not sure what this means or how to rectify it. Any help with this is appreciated, thank you.

Body:
Use join instead of sub query

UPDATE
  oc23_category c
JOIN oc23_category_description cd
     ON cd.category_id = c.category_id
SET
  c.image = LOWER(cd.name)
WHERE c.parent_id = 71


问:
category from url wordpress and keep parent category
I removed the word category in url wordpress by using a custom permalink structure

```<code>/%category%/%postname%
</code>```

and added . in base category

It works but it seems the parent category disappears as well

I would like to have this sructure

```<code>http://monsite.com/parent_cat/child_cat
</code>```

Could somebody help me with this ?

Thanks :)

答:
Using /%category%/%postname%, Wordpress will include the category structure in the URL.

Just select the final (child) category as the post category.

As an example, if you have categories

Book

Chapter

Page

And you select page as the category, the URL will include .../book/chapter/page/POSTNAME.

For more customisations, check the No Category Base (WPML) plugin.

Body:
I removed the word category in url wordpress by using a custom permalink structure

/%category%/%postname%

and added . in base category

It works but it seems the parent category disappears as well

I would like to have this sructure

http://monsite.com/parent_cat/child_cat

Could somebody help me with this ?

Thanks :)


问:
PHP code to get particular portion from an array
I have a version variable like

```<code>$version = "3.4.5";
</code>```

And a verison  array like

```<code>$verison= ["3.7.8", "3.5.2", "3.4.6", "3.3.2", "3.3.1", "3.2.1"];
</code>```

I have to return an array from the $verison array which is greater than the verison string  "3.4.5";
The resultant array will be

```<code>$final=["3.7.8", "3.5.2", "3.4.6"]
</code>```

How it can be perform with PHP code

答:
You can use array_filter() and you can compare the version string directly.

Note:this may be only work for each subversion number just one char. If big than 9, you can split the version with ., can compare each subversion number seperately.

Demo.

```<code>array_filter($array, function($v) use ($version){return $v > $version;});
</code>```

Body:
I have a version variable like

$version = "3.4.5";

And a verison  array like

$verison= ["3.7.8", "3.5.2", "3.4.6", "3.3.2", "3.3.1", "3.2.1"];

I have to return an array from the $verison array which is greater than the verison string  "3.4.5";
The resultant array will be

$final=["3.7.8", "3.5.2", "3.4.6"]

How it can be perform with PHP code

Body:
You can use array_filter() and you can compare the version string directly.

Note:this may be only work for each subversion number just one char. If big than 9, you can split the version with ., can compare each subversion number seperately.

Demo.

array_filter($array, function($v) use ($version){return $v > $version;});


问:
Can css class have class in it self and how would it be done?
My friend and I have had argument about CSS specifity and he was bringing up a class inside of a class:

```<code>.class{
    .subclass{
    }
}
</code>```

I have tried testing this in css but attributes from .subclass are not being applied.

My concern is are sub-classes done like this in css?

答: You can't do this in css, but you can do this in less (http://lesscss.org/) or sass(http://sass-lang.com/)</p>

Body:
My friend and I have had argument about CSS specifity and he was bringing up a class inside of a class:

.class{
    .subclass{
    }
}

I have tried testing this in css but attributes from .subclass are not being applied.

My concern is are sub-classes done like this in css?


问:
ASP.NET web page phamton loading
We have installed a web site written by others which is compiled with Visual Studio 2008 and hosted in Windows server 2008 R2.

The IIS connection timeout is set to 120 seconds.  But for some pages, the first page loading fails with HTTP 404 error but sequential refresh can bring the page up.  The same problem happens for some images which fail to load in web pages.  We are not very sure it is network related issue or hosting issue.  Anyone encountered this before?

Thanks

答: Have you checked the IIS logs to see if you can see the dead requests in there. If not then it's likely a network issue. If you can see them look in the event log for errors, likely IO related</p>

ContentLicense: CC BY-SA 2.5

Title: ASP.NET web page phamton loading


问:
karma-webpack not loading AngularJS bundle
I recently started the move from a custom gulp script that used to take care of all sorts of stuff to webpack. I have it working to a point where transpiling, bundling and serving the client app in the browser works great.

Now, when I was using gulp to run my karma tests against the bundled app.js file, the gulp script would first bundle the app.js file and then spit it into the dist folder. This file would then be used by karma to run the tests against it. My gulp test task would also watch for any test file changes or for the bundle file change, and re-run the tests based on that.

With webpack, I understand this dist/app.js resides in-memory, rather than being written to the disk (at least that's how I set it up). The problem with that is that it seems that my bundled app (which gets served fine with webpack-dev-server --open) does not get loaded by karma for some reason and I can't figure out what the missing piece of the puzzle is.

This is how my folder structure looks like (I left just the most basic stuff that could be relevant to the issue):

```<code>package.json
webpack.config.js
karma.conf.js
src/
--app/
----[other files/subfolders]
----app.ts
----index.ts
--boot.ts
--index.html
tests/
--common/
----services/
------account.service.spec.js
</code>```

This is my webpack.config.js

```<code>var path = require("path");

const webpack = require("webpack");

const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin");

module.exports = {
  context: path.join(__dirname),
  entry: "./src/boot.ts",
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new ForkTsCheckerWebpackPlugin(),
    new CleanWebpackPlugin(["dist"]),
    new HtmlWebpackPlugin({
      template: "./src/index.html"
    })
  ],
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [{
          loader: "style-loader"
        }, {
          loader: "css-loader"
        }, {
          loader: "sass-loader"
        }]
      },
      {
        test: /\.tsx?$/,
        use: [{
          loader: "ts-loader",
          options: {
            transpileOnly: true,
            exclude: /node_modules/
          }
        }]
      },
      {
        test: /\.html$/,
        loaders: "html-loader",
        options: {
          attrs: [":data-src"],
          minimize: true
        }
      }
    ]
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"],
    alias: {
      "common": path.resolve(__dirname, "src/app/common"),
      "common/*": path.resolve(__dirname, "src/app/common/*"),
      "modules": path.resolve(__dirname, "src/app/modules"),
      "modules/*": path.resolve(__dirname, "src/app/modules/*"),
    }
  },
  output: {
    filename: "app.js",
    path: path.resolve(__dirname, "dist")
  },
  devtool: "inline-source-map",
  devServer: {
    historyApiFallback: true,
    hot: false,
    contentBase: path.resolve(__dirname, "dist")
  }
};
</code>```

This is my karma.conf.js

```<code>const webpackConfig = require("./webpack.config");

module.exports = function (config) {
  config.set({
    frameworks: ["jasmine"],

    files: [
      "node_modules/angular/angular.js",
      "node_modules/angular-mocks/angular-mocks.js",
      "dist/app.js", // not sure about this
      "tests/common/*.spec.js",
      "tests/common/**/*.spec.js"
    ],

    preprocessors: {
      "dist/app.js": ["webpack", "sourcemap"], // not sure about this either
      "tests/common/*.spec.js": ["webpack", "sourcemap"],
      "tests/common/**/*.spec.js": ["webpack", "sourcemap"]
    },

    webpack: webpackConfig,

    webpackMiddleware: {
      noInfo: true,
      stats: {
        chunks: false
      }
    },

    reporters: ["progress", "coverage"], // , "teamcity"],

    coverageReporter: {
      dir: "coverage",
      reporters: [
        { type: "html", subdir: "html" },
        { type: "text-summary" }
      ]
    },

    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: [
      "PhantomJS"
      //"Chrome"
    ],
    singleRun: false,
    concurrency: Infinity,
    browserNoActivityTimeout: 100000
  });
};
</code>```

This is the boot.ts which is basically the entry point to the app:

```<code>import * as app from "./app/app";
import "./styles/app.scss";

// This never gets written to the console
// so I know it never gets loaded by karma
console.log("I NEVER OUTPUT TO CONSOLE");
</code>```

This is the app.ts (which then references anything below it:

```<code>import * as ng from "angular";
import * as _ from "lodash";

import "@uirouter/angularjs";
import "angular-cookies";
import "angular-material"
import "angular-local-storage";
import "angular-sanitize";
import "angular-messages";
import "angular-file-saver";
import "angular-loading-bar";
import "satellizer";

export * from "./index";

import * as Module from "common/module";
import * as AuthModule from "modules/auth/module";
import * as UserModule from "modules/user/module";

import { MyAppConfig } from "./app.config";
import { MyAppRun } from "./app.run";

export default ng.module("MyApp", [
  "ngCookies",
  "ngSanitize",
  "ngMessages",
  "ngFileSaver",
  "LocalStorageModule",
  "ui.router",
  "ngMaterial",
  "satellizer",
  "angular-loading-bar",
  Module.name,
  AuthModule.name,
  UserModule.name
])
.config(MyAppConfig)
.run(MyAppRun);
</code>```

And finally, this is the account.service.spec.js

```<code>describe("Account service", function () {
  // SETUP

  var _AccountService;

  beforeEach(angular.mock.module("MyApp.Common"));
  beforeEach(angular.mock.inject(function (_AccountService_) {
    // CODE NEVER GETS IN HERE EITHER
    console.log("I NEVER OUTPUT TO CONSOLE");
    _AccountService = _AccountService_;
  }));

  function expectValidPassword(result) {
    expect(result).toEqual({
      minCharacters: true,
      lowercase: true,
      uppercase: true,
      digits: true,
      isValid: true
    });
  }

  // TESTS

  describe(".validatePassword()", function () {
    describe("on valid password", function () {
      it("returns valid true state", function () {
        expectValidPassword(_AccountService.validatePassword("asdfASDF123"));
        expectValidPassword(_AccountService.validatePassword("as#dfAS!DF123%"));
        expectValidPassword(_AccountService.validatePassword("aA1234%$2"));
        expectValidPassword(_AccountService.validatePassword("YYyy22!@"));
        expectValidPassword(_AccountService.validatePassword("Ma#38Hr$"));
        expectValidPassword(_AccountService.validatePassword("aA1\"#$%(#/$\"#$/(=/#$=!\")(\")("));
      })
    });
  });
});
</code>```

And this is the output of running the karma start

```<code>> npm test

> myapp@1.0.0 test E:\projects\Whatever
> karma start

clean-webpack-plugin: E:\projects\Whatever\dist has been removed.
Starting type checking service...
Using 1 worker with 2048MB memory limit
31 10 2017 21:47:23.372:WARN [watcher]: Pattern "E:/projects/Whatever/dist/app.js" does not match any file.
31 10 2017 21:47:23.376:WARN [watcher]: Pattern "E:/projects/Whatever/tests/common/*.spec.js" does not match any file.
ts-loader: Using typescript@2.4.2 and E:\projects\Whatever\tsconfig.json
No type errors found
Version: typescript 2.4.2
Time: 2468ms
31 10 2017 21:47:31.991:WARN [karma]: No captured browser, open http://localhost:9876/
31 10 2017 21:47:32.004:INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/
31 10 2017 21:47:32.004:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
31 10 2017 21:47:32.010:INFO [launcher]: Starting browser PhantomJS
31 10 2017 21:47:35.142:INFO [PhantomJS 2.1.1 (Windows 8 0.0.0)]: Connected on socket PT-pno0eF3hlcdNEAAAA with id 71358105
PhantomJS 2.1.1 (Windows 8 0.0.0) Account service .validatePassword() on valid password returns valid true state FAILED
        forEach@node_modules/angular/angular.js:410:24
        loadModules@node_modules/angular/angular.js:4917:12
        createInjector@node_modules/angular/angular.js:4839:30
        WorkFn@node_modules/angular-mocks/angular-mocks.js:3172:60
        loaded@http://localhost:9876/context.js:162:17
        node_modules/angular/angular.js:4958:53
        TypeError: undefined is not an object (evaluating '_AccountService.validatePassword') in tests/common/services/account.service.spec.js (line 742)
        webpack:///tests/common/services/account.service.spec.js:27:0 <- tests/common/services/account.service.spec.js:742:44
        loaded@http://localhost:9876/context.js:162:17
PhantomJS 2.1.1 (Windows 8 0.0.0) Account service .validatePassword() on valid amount of characters returns minCharacters true FAILED
        forEach@node_modules/angular/angular.js:410:24
        loadModules@node_modules/angular/angular.js:4917:12
        createInjector@node_modules/angular/angular.js:4839:30
        WorkFn@node_modules/angular-mocks/angular-mocks.js:3172:60
        node_modules/angular/angular.js:4958:53
        TypeError: undefined is not an object (evaluating '_AccountService.validatePassword') in tests/common/services/account.service.spec.js (line 753)
        webpack:///tests/common/services/account.service.spec.js:38:0 <- tests/common/services/account.service.spec.js:753:37
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 2 of 2 (2 FAILED) ERROR (0.017 secs / 0.015 secs)
</code>```

Please note the few places where I left console.logs which never get triggered. That's how I know the app doesn't get loaded. That and the fact that jasmine is not able to inject the service I want to test.

I'm using:

```<code>karma v1.7.1
karma-webpack v2.0.5
webpack v3.3.0
</code>```

Any ideas? What am I doing wrong? I'm under the impression that my webpack.config.js is supposed to bundle my AngularJS/TS app and then essentially feed it to karma, but for whatever reason, that doesn't seem to work. Or do I have some fundamental misconception of how this is supposed to work?

Thank you.

I extracted a few files into a simple app and put it to github so the issue could be easily reproduced.

```<code>npm install # install deps
npm run serve:dev # run the app - works
npm run test # run karma tests - doesn't work
</code>```

Edit:

I managed to make the tests run by replacing the:

```<code>"dist/app.js"
</code>```

in karma setup with

```<code>var path = require("path");

const webpack = require("webpack");

const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin");

module.exports = {
  context: path.join(__dirname),
  entry: "./src/boot.ts",
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new ForkTsCheckerWebpackPlugin(),
    new CleanWebpackPlugin(["dist"]),
    new HtmlWebpackPlugin({
      template: "./src/index.html"
    })
  ],
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [{
          loader: "style-loader"
        }, {
          loader: "css-loader"
        }, {
          loader: "sass-loader"
        }]
      },
      {
        test: /\.tsx?$/,
        use: [{
          loader: "ts-loader",
          options: {
            transpileOnly: true,
            exclude: /node_modules/
          }
        }]
      },
      {
        test: /\.html$/,
        loaders: "html-loader",
        options: {
          attrs: [":data-src"],
          minimize: true
        }
      }
    ]
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"],
    alias: {
      "common": path.resolve(__dirname, "src/app/common"),
      "common/*": path.resolve(__dirname, "src/app/common/*"),
      "modules": path.resolve(__dirname, "src/app/modules"),
      "modules/*": path.resolve(__dirname, "src/app/modules/*"),
    }
  },
  output: {
    filename: "app.js",
    path: path.resolve(__dirname, "dist")
  },
  devtool: "inline-source-map",
  devServer: {
    historyApiFallback: true,
    hot: false,
    contentBase: path.resolve(__dirname, "dist")
  }
};
</code>```0

but that wouldn't drill down or load/import the rest of the app. Then I tried importing only the class I want to test to the spec but then I couldn't mock any DI-injected services that the class I'm testing is using. Anyway, I pretty much gave up on this at this stage and stopped trying to figure out how to do this, moving to ang2+.

答:
I faced a similar issue during transferring my AngularJS project building from Grunt to Webpack and tried 2 different approaches.

1. Webpack and Karma as two separate processes. I made an npm-script running webpack and karma in parallel. It looked like

```<code>"dev-build": "webpack --config webpack/development.js",
"dev-test": "karma start test/karma.development.conf.js",
"test": "concurrently --kill-others --raw \"npm run dev-build\" \"npm run dev-test\""
</code>```

Instead of concurrently you may do anything else, npm-run-all or even &. In that configuration Karma did not have any Webpack stuff, she just watched the ./temp folder for built distributive and worked stand-alone, re-running herself each time the tests or distributive had been changed. Webpack was started in the dev-mode (via "dev-build" script), he watched the ./src folder and compiled distributive into the ./temp folder. When he updated ./temp, Karma started tests re-running.

It worked, despite the problems of first Karma fail. Karma started tests before the Webpack first compilation had been finished. It's not critical. Also, a playing with restartOnFileChange setting could help... Maybe there is another good workaround. I didn't finished this story, I switched to option 2, which I believe fits the Webpack-way a bit more than just described one.

2. Karma is the only process, which uses Webpack. I refused the ./temp folder and decided that for the dev-mode all operations should be in-memory. Dev-mode Webpack got following settings (./webpack/development.js):

```<code>entry: { 'ui-scroll': path.resolve(__dirname, '../src/ui-scroll.js') },
output: { filename: '[name].js' }, // + path to ./dist in prod
devtool: 'inline-source-map', // 'source-map' in prod
compressing: false,
watch: true
</code>```

Dev-mode Karma (./test/karma.development.conf.js):

```<code>files: [
  // external libs
  // tests specs
  '../src/ui-scroll.js' // ../dist in prod
],
preprocessors: { // no preprocessors in prod
  '../src/ui-scroll.js': ['webpack', 'sourcemap']
},
webpack: require('../webpack/development.js'), // no webpack in prod
autoWatch: true,
keepalive: true,
singleRun: false
</code>```

This also required two npm packages to be installed: karma-webpack and karma-sourcemap-loader. The first option looks more familiar after Grunt/gulp, but this one is simpler, shorter and more stable.

Body:
I recently started the move from a custom gulp script that used to take care of all sorts of stuff to webpack. I have it working to a point where transpiling, bundling and serving the client app in the browser works great.

Now, when I was using gulp to run my karma tests against the bundled app.js file, the gulp script would first bundle the app.js file and then spit it into the dist folder. This file would then be used by karma to run the tests against it. My gulp test task would also watch for any test file changes or for the bundle file change, and re-run the tests based on that.

With webpack, I understand this dist/app.js resides in-memory, rather than being written to the disk (at least that's how I set it up). The problem with that is that it seems that my bundled app (which gets served fine with webpack-dev-server --open) does not get loaded by karma for some reason and I can't figure out what the missing piece of the puzzle is.

This is how my folder structure looks like (I left just the most basic stuff that could be relevant to the issue):

package.json
webpack.config.js
karma.conf.js
src/
--app/
----[other files/subfolders]
----app.ts
----index.ts
--boot.ts
--index.html
tests/
--common/
----services/
------account.service.spec.js

This is my webpack.config.js

var path = require("path");

const webpack = require("webpack");

const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin");

module.exports = {
  context: path.join(__dirname),
  entry: "./src/boot.ts",
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new ForkTsCheckerWebpackPlugin(),
    new CleanWebpackPlugin(["dist"]),
    new HtmlWebpackPlugin({
      template: "./src/index.html"
    })
  ],
  module: {
    rules: [
      {
        test: /\.scss$/,
        use: [{
          loader: "style-loader"
        }, {
          loader: "css-loader"
        }, {
          loader: "sass-loader"
        }]
      },
      {
        test: /\.tsx?$/,
        use: [{
          loader: "ts-loader",
          options: {
            transpileOnly: true,
            exclude: /node_modules/
          }
        }]
      },
      {
        test: /\.html$/,
        loaders: "html-loader",
        options: {
          attrs: [":data-src"],
          minimize: true
        }
      }
    ]
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"],
    alias: {
      "common": path.resolve(__dirname, "src/app/common"),
      "common/*": path.resolve(__dirname, "src/app/common/*"),
      "modules": path.resolve(__dirname, "src/app/modules"),
      "modules/*": path.resolve(__dirname, "src/app/modules/*"),
    }
  },
  output: {
    filename: "app.js",
    path: path.resolve(__dirname, "dist")
  },
  devtool: "inline-source-map",
  devServer: {
    historyApiFallback: true,
    hot: false,
    contentBase: path.resolve(__dirname, "dist")
  }
};

This is my karma.conf.js

const webpackConfig = require("./webpack.config");

module.exports = function (config) {
  config.set({
    frameworks: ["jasmine"],

    files: [
      "node_modules/angular/angular.js",
      "node_modules/angular-mocks/angular-mocks.js",
      "dist/app.js", // not sure about this
      "tests/common/*.spec.js",
      "tests/common/**/*.spec.js"
    ],

    preprocessors: {
      "dist/app.js": ["webpack", "sourcemap"], // not sure about this either
      "tests/common/*.spec.js": ["webpack", "sourcemap"],
      "tests/common/**/*.spec.js": ["webpack", "sourcemap"]
    },

    webpack: webpackConfig,

    webpackMiddleware: {
      noInfo: true,
      stats: {
        chunks: false
      }
    },

    reporters: ["progress", "coverage"], // , "teamcity"],

    coverageReporter: {
      dir: "coverage",
      reporters: [
        { type: "html", subdir: "html" },
        { type: "text-summary" }
      ]
    },

    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: [
      "PhantomJS"
      //"Chrome"
    ],
    singleRun: false,
    concurrency: Infinity,
    browserNoActivityTimeout: 100000
  });
};

This is the boot.ts which is basically the entry point to the app:

import * as app from "./app/app";
import "./styles/app.scss";

// This never gets written to the console
// so I know it never gets loaded by karma
console.log("I NEVER OUTPUT TO CONSOLE");

This is the app.ts (which then references anything below it:

import * as ng from "angular";
import * as _ from "lodash";

import "@uirouter/angularjs";
import "angular-cookies";
import "angular-material"
import "angular-local-storage";
import "angular-sanitize";
import "angular-messages";
import "angular-file-saver";
import "angular-loading-bar";
import "satellizer";

export * from "./index";

import * as Module from "common/module";
import * as AuthModule from "modules/auth/module";
import * as UserModule from "modules/user/module";

import { MyAppConfig } from "./app.config";
import { MyAppRun } from "./app.run";

export default ng.module("MyApp", [
  "ngCookies",
  "ngSanitize",
  "ngMessages",
  "ngFileSaver",
  "LocalStorageModule",
  "ui.router",
  "ngMaterial",
  "satellizer",
  "angular-loading-bar",
  Module.name,
  AuthModule.name,
  UserModule.name
])
.config(MyAppConfig)
.run(MyAppRun);

And finally, this is the account.service.spec.js

describe("Account service", function () {
  // SETUP

  var _AccountService;

  beforeEach(angular.mock.module("MyApp.Common"));
  beforeEach(angular.mock.inject(function (_AccountService_) {
    // CODE NEVER GETS IN HERE EITHER
    console.log("I NEVER OUTPUT TO CONSOLE");
    _AccountService = _AccountService_;
  }));

  function expectValidPassword(result) {
    expect(result).toEqual({
      minCharacters: true,
      lowercase: true,
      uppercase: true,
      digits: true,
      isValid: true
    });
  }

  // TESTS

  describe(".validatePassword()", function () {
    describe("on valid password", function () {
      it("returns valid true state", function () {
        expectValidPassword(_AccountService.validatePassword("asdfASDF123"));
        expectValidPassword(_AccountService.validatePassword("as#dfAS!DF123%"));
        expectValidPassword(_AccountService.validatePassword("aA1234%$2"));
        expectValidPassword(_AccountService.validatePassword("YYyy22!@"));
        expectValidPassword(_AccountService.validatePassword("Ma#38Hr$"));
        expectValidPassword(_AccountService.validatePassword("aA1\"#$%(#/$\"#$/(=/#$=!\")(\")("));
      })
    });
  });
});

And this is the output of running the karma start

> npm test

> myapp@1.0.0 test E:\projects\Whatever
> karma start

clean-webpack-plugin: E:\projects\Whatever\dist has been removed.
Starting type checking service...
Using 1 worker with 2048MB memory limit
31 10 2017 21:47:23.372:WARN [watcher]: Pattern "E:/projects/Whatever/dist/app.js" does not match any file.
31 10 2017 21:47:23.376:WARN [watcher]: Pattern "E:/projects/Whatever/tests/common/*.spec.js" does not match any file.
ts-loader: Using typescript@2.4.2 and E:\projects\Whatever\tsconfig.json
No type errors found
Version: typescript 2.4.2
Time: 2468ms
31 10 2017 21:47:31.991:WARN [karma]: No captured browser, open http://localhost:9876/
31 10 2017 21:47:32.004:INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/
31 10 2017 21:47:32.004:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
31 10 2017 21:47:32.010:INFO [launcher]: Starting browser PhantomJS
31 10 2017 21:47:35.142:INFO [PhantomJS 2.1.1 (Windows 8 0.0.0)]: Connected on socket PT-pno0eF3hlcdNEAAAA with id 71358105
PhantomJS 2.1.1 (Windows 8 0.0.0) Account service .validatePassword() on valid password returns valid true state FAILED
        forEach@node_modules/angular/angular.js:410:24
        loadModules@node_modules/angular/angular.js:4917:12
        createInjector@node_modules/angular/angular.js:4839:30
        WorkFn@node_modules/angular-mocks/angular-mocks.js:3172:60
        loaded@http://localhost:9876/context.js:162:17
        node_modules/angular/angular.js:4958:53
        TypeError: undefined is not an object (evaluating '_AccountService.validatePassword') in tests/common/services/account.service.spec.js (line 742)
        webpack:///tests/common/services/account.service.spec.js:27:0 <- tests/common/services/account.service.spec.js:742:44
        loaded@http://localhost:9876/context.js:162:17
PhantomJS 2.1.1 (Windows 8 0.0.0) Account service .validatePassword() on valid amount of characters returns minCharacters true FAILED
        forEach@node_modules/angular/angular.js:410:24
        loadModules@node_modules/angular/angular.js:4917:12
        createInjector@node_modules/angular/angular.js:4839:30
        WorkFn@node_modules/angular-mocks/angular-mocks.js:3172:60
        node_modules/angular/angular.js:4958:53
        TypeError: undefined is not an object (evaluating '_AccountService.validatePassword') in tests/common/services/account.service.spec.js (line 753)
        webpack:///tests/common/services/account.service.spec.js:38:0 <- tests/common/services/account.service.spec.js:753:37
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 2 of 2 (2 FAILED) ERROR (0.017 secs / 0.015 secs)

Please note the few places where I left console.logs which never get triggered. That's how I know the app doesn't get loaded. That and the fact that jasmine is not able to inject the service I want to test.

I'm using:

karma v1.7.1
karma-webpack v2.0.5
webpack v3.3.0

Any ideas? What am I doing wrong? I'm under the impression that my webpack.config.js is supposed to bundle my AngularJS/TS app and then essentially feed it to karma, but for whatever reason, that doesn't seem to work. Or do I have some fundamental misconception of how this is supposed to work?

Thank you.

I extracted a few files into a simple app and put it to github so the issue could be easily reproduced.

npm install # install deps
npm run serve:dev # run the app - works
npm run test # run karma tests - doesn't work

Edit:

I managed to make the tests run by replacing the:

"dist/app.js"

in karma setup with

"src/boot.ts"

but that wouldn't drill down or load/import the rest of the app. Then I tried importing only the class I want to test to the spec but then I couldn't mock any DI-injected services that the class I'm testing is using. Anyway, I pretty much gave up on this at this stage and stopped trying to figure out how to do this, moving to ang2+.

Body:
I faced a similar issue during transferring my AngularJS project building from Grunt to Webpack and tried 2 different approaches.

1. Webpack and Karma as two separate processes. I made an npm-script running webpack and karma in parallel. It looked like

"dev-build": "webpack --config webpack/development.js",
"dev-test": "karma start test/karma.development.conf.js",
"test": "concurrently --kill-others --raw \"npm run dev-build\" \"npm run dev-test\""

Instead of concurrently you may do anything else, npm-run-all or even &. In that configuration Karma did not have any Webpack stuff, she just watched the ./temp folder for built distributive and worked stand-alone, re-running herself each time the tests or distributive had been changed. Webpack was started in the dev-mode (via "dev-build" script), he watched the ./src folder and compiled distributive into the ./temp folder. When he updated ./temp, Karma started tests re-running.

It worked, despite the problems of first Karma fail. Karma started tests before the Webpack first compilation had been finished. It's not critical. Also, a playing with restartOnFileChange setting could help... Maybe there is another good workaround. I didn't finished this story, I switched to option 2, which I believe fits the Webpack-way a bit more than just described one.

2. Karma is the only process, which uses Webpack. I refused the ./temp folder and decided that for the dev-mode all operations should be in-memory. Dev-mode Webpack got following settings (./webpack/development.js):

entry: { 'ui-scroll': path.resolve(__dirname, '../src/ui-scroll.js') },
output: { filename: '[name].js' }, // + path to ./dist in prod
devtool: 'inline-source-map', // 'source-map' in prod
compressing: false,
watch: true

Dev-mode Karma (./test/karma.development.conf.js):

files: [
  // external libs
  // tests specs
  '../src/ui-scroll.js' // ../dist in prod
],
preprocessors: { // no preprocessors in prod
  '../src/ui-scroll.js': ['webpack', 'sourcemap']
},
webpack: require('../webpack/development.js'), // no webpack in prod
autoWatch: true,
keepalive: true,
singleRun: false

This also required two npm packages to be installed: karma-webpack and karma-sourcemap-loader. The first option looks more familiar after Grunt/gulp, but this one is simpler, shorter and more stable.


问:
Concatenating values from columns to a list in Python
I am working on a project which does automated descriptive analysis on data. In a line of code I am sending a row of a dataframe and I want all the values in columns returned in a single list.

The line of code is :

```<code>file_name1['validate'] = file_name1.apply(lambda x: ast.literal_eval(x[2]) + [x[3]] + [x[4]] + [x[5]] + [x[0]] + [x[1]], axis=1)
</code>```

and the filename1 looks like this

```<code>Value_share_total_next Value_share_total_prev Path                                            IYA      upper      lower
1497852                1270937                ['CVS + ALB + LNG CORP WO HI CENSUS TA']   117.85415  91.945763  66.936457
</code>```

I want to concatenate these values inside a list, and I am getting the error as :

```<code>ValueError: Wrong number of items passed 6, placement implies 1
</code>```

EDIT : The problem I am facing is only if the length of my dataframe is exactly 1. If the length of my dataframe is > 1 then the line of code is working. I could add an if else condition but I need to know why it is not working. Can I not apply a function to a single or of the dataframe?

答:
For every row you pass a list of 6 items when there is only one space allocated (one column: 'validate'). To make sure pandas understand the data type you want to pass (a list) and doesn't try to unpack it you can use parentheses:

file_name1['validate'] = file_name1.apply(lambda x: (ast.literal_eval(x[2]) + [x[3]] + [x[4]] + [x[5]] + [x[0]] + [x[1]]), axis=1)
```

Body:
I am working on a project which does automated descriptive analysis on data. In a line of code I am sending a row of a dataframe and I want all the values in columns returned in a single list.

The line of code is :

file_name1['validate'] = file_name1.apply(lambda x: ast.literal_eval(x[2]) + [x[3]] + [x[4]] + [x[5]] + [x[0]] + [x[1]], axis=1)

and the filename1 looks like this

Value_share_total_next Value_share_total_prev Path                                            IYA      upper      lower
1497852                1270937                ['CVS + ALB + LNG CORP WO HI CENSUS TA']   117.85415  91.945763  66.936457

I want to concatenate these values inside a list, and I am getting the error as :

ValueError: Wrong number of items passed 6, placement implies 1

EDIT : The problem I am facing is only if the length of my dataframe is exactly 1. If the length of my dataframe is > 1 then the line of code is working. I could add an if else condition but I need to know why it is not working. Can I not apply a function to a single or of the dataframe?


问:
With Redux-Form V7, how to gain access to which fields are currently touched?
I have a form (let's call it the LoginContainer) that has the <Field /> component on it:

```<code>import { reduxForm, Field } from 'redux-form'
...
class LoginContainer extends Component {
...

render() {
  const { handleSubmit, pristine, submitting } = this.props

  return (
  ...

  <Field
    component={AuthFormInput}
    type="password"
    name="person_password"
    placeholder="Password"
  />
</code>```

AuthFormInput.jsx

```<code>const AuthFormInput = ({
  input,
  name,
  placeholder,
  type,
  meta: { touched, error },
}) => {
  return [
    <div className="row-md" key={`${name}_field`}>
      <input
        placeholder={placeholder}
        name={name}
        type={type}
        className={maybeHasError}
        {...input}
      />
    </div>, // error display works amazing here, no problem
    <div key={`${name}_error`}>{touched && (error && <span className="edit_required">{error}</span>)}</div>,
  ]
}
</code>```

The problem is, I am trying to handle errors outside of the AuthFormInput component, and I can't find any solution that allows me to access the touched state of each field from anywhere other than AuthFormInput, which is abstracted inside <Field />

Is there a way I can get access to meta.touched from inside LoginContainer?

Redux-Form doesn't seem to have any kind of getTouchedFields() function that I can use.

I can collect the currently errored fields easily through the validate function, but I can't find a way to see what fields are touched.

I can't find a way to pass data from AuthFormInput to LoginContainer because <Field /> is between them which is internally controlled by Redux-Form.

Is there any way to do this with Redux-Form V7?

Is there a way I can create a HOC that allows me to track meta.touched inside <Field />?

答:
Ok, I was able to achieve this and it was extremely non-trivial.

Stepping forward from the code in the above question, I added this to LoginContainer:

```<code>import withFormListener from './withFormListener'

const listeningAuthFormInput = withFormListener(AuthFormInput)
</code>```

So, then <Field /> became this:

```<code><Field
  component={listeningAuthFormInput}
  type="password"
  name="person_password"
  placeholder="Password"
/>
</code>```

The HOC wraps around the text input field (or any field you want), and simply listens for changes to the props and then updates Redux:

```<code>import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { updateField } from './auth_actions'

const withFormListener = function listenToFormField(FormField) {
  class WrappedField extends Component {
    handleFieldUpdate() {
      const { name } = this.props.input
      const { touched, error } = this.props.meta
      if (touched && error) {
        if (this.props[`error_${name}`] === error) return null
        return this.props.updateField({ prop: name, value: error })
      }
      if ((touched && !error) && this.props[`error_${name}`].length) {
        return this.props.updateField({ prop: name, value: '' })
      }
      return null
    }
    componentDidUpdate() {
      this.handleFieldUpdate()
    }
    render() {
      return <FormField {...this.props} />
    }
  }
  const mapStateToProps = ({
    auth: { error_person_tel, error_person_password },
  }) => ({
    error_person_tel, error_person_password,
  })
  return connect(mapStateToProps, { updateField })(WrappedField)
}

export default withFormListener
</code>```

Logically, what is happening in the HOC is:

this.props inside AuthFormInput becomes this.props inside the HOC

listen to this.props.meta and this.props.input

if the field is touched and has an error, update Redux

if the field is touched and no longer has an error, wipe it out of Redux

You should see my action creator and reducer from LoginContainer so there is no confusion.

Action Creator

```<code>export const updateField = ({ prop, value }) => ({
  type: AUTH_UPDATE_FIELD,
  payload: { prop, value },
})
</code>```

Reducer

I recommend keeping the state object flat. I experimented with nesting in here, such as:

```<code>const INITIAL_STATE = {
  errors: { field1, field2 }
}
</code>```

But, it was giving me significant problems with updating the state, due to equality reasons and complexity with avoiding overwriting errors. It's much nastier than it looks. Therefore, I have settled on this:

```<code>const INITIAL_STATE = {
  ...
  error_person_tel: '',
  error_person_password: '',
}

case AUTH_UPDATE_FIELD: {
  const { prop, value } = action.payload
  return {
    ...state,
    [`error_${prop}`]: value,
  }
}
</code>```

You can read more about normalizing state here (ie: flattening):
https://redux.js.org/docs/recipes/reducers/NormalizingStateShape.html

I haven't got around to optimizing it at all, but here is how I am displaying the errors currently (inside LoginContainer):

```<code><ServerErrors
  errors={[
    this.props.error_person_tel,
    this.props.error_person_password,
  ].filter(val => val)}
/>
</code>```

It is a simple component that renders either null or an array of error strings.

I highly recommend using the built-in Redux-Form field error handling. It works great. I unfortunately had to abstract the control away from the field-level to accomplish a UI design, so this was the only solution in V7.

I searched for weeks. I made another Stack Overflow question and it got no activity, neither did this one. I'm glad I was able to achieve a functioning solution.

I also highly recommend you take a look at Formik. I used it in React Native to accomplish this UI requirement a few weeks ago. You will likely find it works very well. Talk to Jared Palmer on Twitter if you encounter any issues with it. Formik boasts performance gains vs. Redux-Form due to smarter architecture. I am very happy with it in React Native.

If you venture down this road, be extremely careful about setting off infinite loops caused by setState. I did hours and hours and hours of research and trial & error to make this :) I am reasonably happy with the conciseness of the solution. Please let me know if you have a better way.

Body:
I have a form (let's call it the LoginContainer) that has the <Field /> component on it:

import { reduxForm, Field } from 'redux-form'
...
class LoginContainer extends Component {
...

render() {
  const { handleSubmit, pristine, submitting } = this.props

  return (
  ...

  <Field
    component={AuthFormInput}
    type="password"
    name="person_password"
    placeholder="Password"
  />

AuthFormInput.jsx

const AuthFormInput = ({
  input,
  name,
  placeholder,
  type,
  meta: { touched, error },
}) => {
  return [
    <div className="row-md" key={`${name}_field`}>
      <input
        placeholder={placeholder}
        name={name}
        type={type}
        className={maybeHasError}
        {...input}
      />

, // error display works amazing here, no problem
    <div key={`${name}_error`}>{touched && (error && {error})}
,
  ]
}

The problem is, I am trying to handle errors outside of the AuthFormInput component, and I can't find any solution that allows me to access the touched state of each field from anywhere other than AuthFormInput, which is abstracted inside <Field />

Is there a way I can get access to meta.touched from inside LoginContainer?

Redux-Form doesn't seem to have any kind of getTouchedFields() function that I can use.

I can collect the currently errored fields easily through the validate function, but I can't find a way to see what fields are touched.

I can't find a way to pass data from AuthFormInput to LoginContainer because <Field /> is between them which is internally controlled by Redux-Form.

Is there any way to do this with Redux-Form V7?

Is there a way I can create a HOC that allows me to track meta.touched inside <Field />?

Body:
Ok, I was able to achieve this and it was extremely non-trivial.

Stepping forward from the code in the above question, I added this to LoginContainer:

import withFormListener from './withFormListener'

const listeningAuthFormInput = withFormListener(AuthFormInput)

So, then <Field /> became this:

<Field
  component={listeningAuthFormInput}
  type="password"
  name="person_password"
  placeholder="Password"
/>

The HOC wraps around the text input field (or any field you want), and simply listens for changes to the props and then updates Redux:

import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { updateField } from './auth_actions'

const withFormListener = function listenToFormField(FormField) {
  class WrappedField extends Component {
    handleFieldUpdate() {
      const { name } = this.props.input
      const { touched, error } = this.props.meta
      if (touched && error) {
        if (this.props[`error_${name}`] === error) return null
        return this.props.updateField({ prop: name, value: error })
      }
      if ((touched && !error) && this.props[`error_${name}`].length) {
        return this.props.updateField({ prop: name, value: '' })
      }
      return null
    }
    componentDidUpdate() {
      this.handleFieldUpdate()
    }
    render() {
      return <FormField {...this.props} />
    }
  }
  const mapStateToProps = ({
    auth: { error_person_tel, error_person_password },
  }) => ({
    error_person_tel, error_person_password,
  })
  return connect(mapStateToProps, { updateField })(WrappedField)
}

export default withFormListener

Logically, what is happening in the HOC is:

this.props inside AuthFormInput becomes this.props inside the HOC

listen to this.props.meta and this.props.input

if the field is touched and has an error, update Redux

if the field is touched and no longer has an error, wipe it out of Redux

You should see my action creator and reducer from LoginContainer so there is no confusion.

Action Creator

export const updateField = ({ prop, value }) => ({
  type: AUTH_UPDATE_FIELD,
  payload: { prop, value },
})

Reducer

I recommend keeping the state object flat. I experimented with nesting in here, such as:

const INITIAL_STATE = {
  errors: { field1, field2 }
}

But, it was giving me significant problems with updating the state, due to equality reasons and complexity with avoiding overwriting errors. It's much nastier than it looks. Therefore, I have settled on this:

const INITIAL_STATE = {
  ...
  error_person_tel: '',
  error_person_password: '',
}

case AUTH_UPDATE_FIELD: {
  const { prop, value } = action.payload
  return {
    ...state,
    [`error_${prop}`]: value,
  }
}

You can read more about normalizing state here (ie: flattening):
https://redux.js.org/docs/recipes/reducers/NormalizingStateShape.html

I haven't got around to optimizing it at all, but here is how I am displaying the errors currently (inside LoginContainer):

<ServerErrors
  errors={[
    this.props.error_person_tel,
    this.props.error_person_password,
  ].filter(val => val)}
/>

It is a simple component that renders either null or an array of error strings.

I highly recommend using the built-in Redux-Form field error handling. It works great. I unfortunately had to abstract the control away from the field-level to accomplish a UI design, so this was the only solution in V7.

I searched for weeks. I made another Stack Overflow question and it got no activity, neither did this one. I'm glad I was able to achieve a functioning solution.

I also highly recommend you take a look at Formik. I used it in React Native to accomplish this UI requirement a few weeks ago. You will likely find it works very well. Talk to Jared Palmer on Twitter if you encounter any issues with it. Formik boasts performance gains vs. Redux-Form due to smarter architecture. I am very happy with it in React Native.

If you venture down this road, be extremely careful about setting off infinite loops caused by setState. I did hours and hours and hours of research and trial & error to make this :) I am reasonably happy with the conciseness of the solution. Please let me know if you have a better way.


问:
Replace Windows filepath in text file by using a Linux sed regular expression
I have a huge number of text files with tag-like syntax. Those files contain patterns like this:

```<code><TAG1=foo><TAG-2=\\10.0.0.1\directory\filename.pdf><TAG3> ...
<TAG4=bar><TAG-6=\\10.0.0.1\directory\filename.tif,other content><TAG5>
</code>```

I need to replace the first part of those UNC paths with new ones, meaning:

```<code><TAG1=foo><TAG-2=D:\localdirectory\filename.pdf><TAG3> ...
<TAG4=bar><TAG-6=D:\localdirectory\filename.tif,other content><TAG7>
</code>```

There is a huge number of files to process and so I need to automate this path replacement. So far I tried multiple regex with sed (on Linux) but did not get close to a solution.

```<code>#!/bin/bash

# New directory (escaped)
newpath='D:\\localdirectory\\'
# Actual replacement (don't work)
sed -i "s@\(<TAG-2=\)\([^\\]+\.pdf\)@\1${newpath}\2@g" filetoprocess.txt
sed -i "s@\(<TAG-6=\)\([^\\]+\.tif\)@\1${newpath}\2@g" filetoprocess.txt
</code>```

Any suggestions are welcome

答:
Finally I came with the following regular expression. This solution can also, manage "/" Unix paths, dollar ($) and hyphens (-) :</p>

```<code>sed -i -r 's@(<TAG-2=|TAG-6=)([\/]{2})([0-9.a-zA-Z_$ -]+[\/])+([0-9.a-zA-Z_$ -]+\.[pPtT][dDiI][fF])@\1'"${newpath}"'\\\4@g'
</code>```

Body:
I have a huge number of text files with tag-like syntax. Those files contain patterns like this:

<TAG1=foo><TAG-2=\\10.0.0.1\directory\filename.pdf><TAG3> ...
<TAG4=bar><TAG-6=\\10.0.0.1\directory\filename.tif,other content><TAG5>

I need to replace the first part of those UNC paths with new ones, meaning:

<TAG1=foo><TAG-2=D:\localdirectory\filename.pdf><TAG3> ...
<TAG4=bar><TAG-6=D:\localdirectory\filename.tif,other content><TAG7>

There is a huge number of files to process and so I need to automate this path replacement. So far I tried multiple regex with sed (on Linux) but did not get close to a solution.

#!/bin/bash

# New directory (escaped)
newpath='D:\\localdirectory\\'
# Actual replacement (don't work)
sed -i "s@\(<TAG-2=\)\([^\\]+\.pdf\)@\1${newpath}\2@g" filetoprocess.txt
sed -i "s@\(<TAG-6=\)\([^\\]+\.tif\)@\1${newpath}\2@g" filetoprocess.txt

Any suggestions are welcome

Body:
Finally I came with the following regular expression. This solution can also, manage "/" Unix paths, dollar ($) and hyphens (-) :

sed -i -r 's@(<TAG-2=|TAG-6=)([\/]{2})([0-9.a-zA-Z_$ -]+[\/])+([0-9.a-zA-Z_$ -]+\.[pPtT][dDiI][fF])@\1'"${newpath}"'\\\4@g'


问:
Image upload to a customer form as a background
I need help with the following: I have created a new <select> button in a WordPress plugin. I want this button in a plugin, when selected, to select image from WordPress media library and upload to a customer form.

In short, I need the admin to be able to change background image of the form by selecting it from the media library.

Button looks like this:

```<code><button>Select Image</button>
</code>```

Customer form (preview end):

```<code><div id="giftcardForm" style="position:relative;">
    <img src="url" id="background img" style="width:100%; height:auto; z-index:0;">
    <div style="position:absolute; top:$from_y; left:$from_x; width:auto;" id="printname"></div>
    <div style="position:absolute; top:20%; left:$from_x; width:auto;" id="print_to_name"></div>
    <div style="position:absolute; top:30%; left:$from_x; width:auto;" id="showtext"></div>
</div>
</code>```

答:
You need to give class to your button like:

```<code><button class="media">Select Image</button>
</code>```

And give proper id to your image tag like

```<code><img src="url" id="background_img" style="width:100%; height:auto; z-index:0;">
</code>```

After that you need to add following jQuery code which will open select media popup on click of button and set img src which is selected.

```<code>jQuery(document).ready(function(){
        var frame = wp.media({
            multiple: true
        });
        jQuery(".media").on("click", function(e) {
            frame.open();
            e.preventDefault();
        });
        frame.on('select', function() {
            var selection = frame.state().get('selection');

            selection.each(function(attachment) {
                jQuery('#background_img').attr('src',attachment.attributes.url);
            });
        });
    });
</code>```

Body:
I need help with the following: I have created a new <select> button in a WordPress plugin. I want this button in a plugin, when selected, to select image from WordPress media library and upload to a customer form.

In short, I need the admin to be able to change background image of the form by selecting it from the media library.

Button looks like this:

<button>Select Image</button>

Customer form (preview end):

Body:
You need to give class to your button like:

<button class="media">Select Image</button>

And give proper id to your image tag like

<img src="url" id="background_img" style="width:100%; height:auto; z-index:0;">

After that you need to add following jQuery code which will open select media popup on click of button and set img src which is selected.

jQuery(document).ready(function(){
        var frame = wp.media({
            multiple: true
        });
        jQuery(".media").on("click", function(e) {
            frame.open();
            e.preventDefault();
        });
        frame.on('select', function() {
            var selection = frame.state().get('selection');

            selection.each(function(attachment) {
                jQuery('#background_img').attr('src',attachment.attributes.url);
            });
        });
    });


问:
Cannot Connect to Server - A network-related or instance-specific error
I get the following error when trying to connect to SQL Server:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

This error is thrown when I try to configure my database to gridview in Visual Studio 2010. I'm at a loss as to how to debug this error.

How would you debug this error? What steps should I take in order to determine what is really going on here, in addition to the one mentioned in the error message?

答:
Why this error is so boresome and noisy, just because it can occur in varied situation.

I have done all approchs above here, and still being sucked. So make sure u have done the same as me before browsing downward.

Maybe I am not able to fix ur situation instantly, but I can point out a direction or thinking to u(The one who finally slide down here).  I have started to ponder the error of  my running program occurring after I made sure that the instance name is clearly right and set my database to allow remote control following the methods above. After then, I suspected something wrong happening in my code snippet of SQL connection.

Solution of my problem:

Check my sqlconnection function

Click to see its configuration

New a connection

Select ur server name

It works for me with pondering what exactly happen in the process of connection.Hope my thinking will lead u to kill ur error.

ContentLicense: CC BY-SA 4.0


问:
how to add cookie in the header using retrofit2?
i need to add cookie with session id and session name in the header of webservice.

```<code>@POST(ApiUrl.AUTH_TOKEN_VERIFICATION)
Call<LogoutResponse> authTokenVerification(@Body Logout logout);
</code>```

This is my current implementation. How to append header tag with cookie. do i need to create a cookie object or how to achieve this?

答:
You can send cookie in HEADER in Retrofit as given below :</p>

```<code>@POST(ApiUrl.AUTH_TOKEN_VERIFICATION)
Call<LogoutResponse> authTokenVerification(@Body Logout logout, @Header("Cookie") String sessionIdAndName);
</code>```

Body:
i need to add cookie with session id and session name in the header of webservice.

@POST(ApiUrl.AUTH_TOKEN_VERIFICATION)
Call<LogoutResponse> authTokenVerification(@Body Logout logout);

This is my current implementation. How to append header tag with cookie. do i need to create a cookie object or how to achieve this?

Body:
You can send cookie in HEADER in Retrofit as given below :

@POST(ApiUrl.AUTH_TOKEN_VERIFICATION)
Call<LogoutResponse> authTokenVerification(@Body Logout logout, @Header("Cookie") String sessionIdAndName);


问:
Equivalent to bash "expect" in powershell
I'm using powershell to run another powershell script, at some point the other script asks for some input, I would like to be able to read the output from the other script and based on that supply input to it. Similar to what you can do with expect on bash.

Any ideas?

Thanks

答:
Just posting my solution so that it can help someone. I faced the same problem while running some other script that will ask for answers. First create a file "inputFileLocation.txt" with answers to each question in each line in sequence. Then run the script in below syntax. And it will do the work.</p>

```<code>`cmd.exe /c "script.bat < inputFileLocation.txt"`
</code>```

Body:
Just posting my solution so that it can help someone. I faced the same problem while running some other script that will ask for answers. First create a file "inputFileLocation.txt" with answers to each question in each line in sequence. Then run the script in below syntax. And it will do the work.

`cmd.exe /c "script.bat < inputFileLocation.txt"`


问:
Silverlight IGoogle example (Photo linked)
Does anyone know which silverlight or third party controls can help me make an igoogle dashboard similar to the one in the photo.

http://imgur.com/86MaY

Notice how "Weather", "Date & Time", and "YouTube" all have different sized windows.

Dragging and rearranging windows is also supported

I've seen plenty of examples of floating windows or docking windows (similar to visual studio docking windows), but that's not what igoogle has or does.

答:
I have used the Blacklight controls library in the past to achieve that dashboard like functionality.  Checkout the demo and you should find what you need.

http://blacklight.codeplex.com/


问:
Adding multi-language option to a Qt app with hard-coded text
I'm a beginner in Qt. I have an app designed using Qt which has multiple windows with each consisting of several labels with hard coded text. What would be the easiest way to add multi language support for this app? Which built in Qt objects/functions I should use?

My current idea is to maybe create a separate xml file including the text for all labels for a language. Then once the user selects a language icon from the menu, load the relevant xml file. But I have no idea how to do this. Any help would be highly appreciated!

UPDATE:
I have tried to implement the example given here. But it throws the following error and I can't fix it. 'class Ui::MainWindow' has no member named 'menuLanguage'

QActionGroup* langGroup = new QActionGroup(ui->menuLanguage);

答:
Qt has translation support. Look into Qt Linguist

Basically, you mark all you hard coded texts with a call to QObject::tr, e.g.

```<code>lbl->setText(tr("My text to translate"));
</code>```

Qt Linguist parses all source files and UI forms for such calls (using lupdate.exe) and builds a ts file. With the Qt Linguist GUI application, you can translate them. With lrelease you create a qm file that will be loaded at runtime, and automatically translate the texts

Body:
Qt has translation support. Look into Qt Linguist

Basically, you mark all you hard coded texts with a call to QObject::tr, e.g.

lbl->setText(tr("My text to translate"));

Qt Linguist parses all source files and UI forms for such calls (using lupdate.exe) and builds a ts file. With the Qt Linguist GUI application, you can translate them. With lrelease you create a qm file that will be loaded at runtime, and automatically translate the texts


问:
CRM 2016 - How to create a parent-child relationship with multiple parent types?
I have an entity - EntityZ, which has a ParentId where ParentId could be EntityA.Id, EntityB.Id or EntityC.Id. Is it possible to create this in MS Dynamics CRM 2016? If yes, how? I've looked but couldn't find a similar question or any help on the web.

答:
There’s a trade off to achieve this. Custom entity as Custom Activity

Creating custom entity EntityZ as custom activity and EntityA, B, C can act as parent.

EntityA or B or C can be chosen as RegardingObjectId of EntityZ.

This has security limitation like EntityZ will be visible to everyone as this will be listed like other activities (Email, Phonecall, Task, etc)