问:
Encoding audio data using ffmpeg
I am receiving a byte array (int8_t*) and I would like to use FFMPEG to encode it into FLAC. All the examples I found are reading data from files, which is not the case for me. Following the original documents (see here), I came up with the following solution:

```<code>#include "libavcodec/avcodec.h"

// ...

// params:
//  audioData: original audio data
//  len: length of the byte array (audio data)
//  sampleRate: sample rate of the original audio data
//  frameSize: frame size of the original data
uint8_t* encodeToFlac(uint8_t* audioData, int len, int sampleRate, int frameSize) {
  uint8_t* convertedAudioData;

  // Context information
  AVCodecContext* context = avcodec_alloc_context();
  context->bit_rate = 64000;
  context->sample_rate = sampleRate;
  context->channels = 2;
  context->frame_size = frameSize;

  short* samples = malloc(frameSize * 2 * context->channels);
  int outAudioDataSize = len * 2;
  convertedAudioData = malloc(outAudioDataSize);
  int outSize = avcodec_encode_audio(c, convertedAudioData, outAudioDataSize, samples);

  return convertedAudioData;
}
</code>```

I have two main issues with the above solution:

I did not specify what the final encoding should be (for example, MP3, FLAC, etc), which makes me wonder if I'm using FFMPEG library correctly?

Do I have all the necessary information about the source - original audio data? I am not certain if I have all the necessary information to perform the encoding.

答:
You are nearly there, follow this example: https://github.com/FFmpeg/FFmpeg/blob/master/doc/examples/encode_audio.c

Answer to 1st question:
There you'll see codec = avcodec_find_encoder(AV_CODEC_ID_MP2).

In your case, you guessed it, it probably will be codec = avcodec_find_encoder(AV_CODEC_ID_FLAC) and check/fix other values accordingly.

As for 2nd one... I'm sure you'll find out yourself, especially you must set this correctly (line 158) c->sample_fmt = AV_SAMPLE_FMT_S16 according to what your int8_t array formatted.

Hope that helps.

Title: Encoding audio data using ffmpeg

Body:
I am receiving a byte array (int8_t*) and I would like to use FFMPEG to encode it into FLAC. All the examples I found are reading data from files, which is not the case for me. Following the original documents (see here), I came up with the following solution:

#include "libavcodec/avcodec.h"

// ...

// params:
//  audioData: original audio data
//  len: length of the byte array (audio data)
//  sampleRate: sample rate of the original audio data
//  frameSize: frame size of the original data
uint8_t* encodeToFlac(uint8_t* audioData, int len, int sampleRate, int frameSize) {
  uint8_t* convertedAudioData;

  // Context information
  AVCodecContext* context = avcodec_alloc_context();
  context->bit_rate = 64000;
  context->sample_rate = sampleRate;
  context->channels = 2;
  context->frame_size = frameSize;

  short* samples = malloc(frameSize * 2 * context->channels);
  int outAudioDataSize = len * 2;
  convertedAudioData = malloc(outAudioDataSize);
  int outSize = avcodec_encode_audio(c, convertedAudioData, outAudioDataSize, samples);

  return convertedAudioData;
}

I have two main issues with the above solution:

I did not specify what the final encoding should be (for example, MP3, FLAC, etc), which makes me wonder if I'm using FFMPEG library correctly?

Do I have all the necessary information about the source - original audio data? I am not certain if I have all the necessary information to perform the encoding.


来源: stackexchange

问:
How to read complex objects from json file in .net core
I have a json like this to read in c# but it showing null.

Provices.json contains this json

```<code>{
   "Provinces": {
        "States": [
          {
            "CountryId": 1,
            "Name": "AA (Armed Forces Americas)",
            "Abbreviation": null,
            "Published": false,
            "DisplayOrder": 0,
            "Country": null,
            "Id": 1
          },
          {
            "CountryId": 1,
            "Name": "AE (Armed Forces Europe)",
            "Abbreviation": null,
            "Published": false,
            "DisplayOrder": 0,
            "Country": null,
            "Id": 54
          }
    ]
  }
}
</code>```

start up file contains

```<code> services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
 services.Configure<Provinces>(Configuration.GetSection("Provinces"));
</code>```

This is c# models

```<code>   public class Provinces
    {
        public Provinces()
        {
            this.States = new List<State>();
        }
        public List<State> States { get; set; }
    }

    public class State
    {
        public int CountryId { get; set; }

        public string Name { get; set; }

        public string Abbreviation { get; set; }

        public bool Published { get; set; }

        public bool DisplayOrder { get; set; }

        public string Country { get; set; }

        public int Id { get; set; }

    }
</code>```

This is how I am reading this file which is giving me null values

```<code>public class UserService
{
 public UserService(IOptions<AppSettings> appSettings,
  IOptions<Provinces> states)
    {
           _appSettings = appSettings;
            _states = states;
     }

//Getting value from json

 public List<State> GetStates()
        {
            var data = this._states.Value.States; // Zero count shows here
            return new List<State>();
        }

}
</code>```

I am also reading AppSettings.json which is working fine but province.json is not working.Can You please tell what's wrong i did

答:
```<code>var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJson(yourconfigSetting.json optional: true, reloadOnChange: true)
.AddJsonFile("Provinces.json", optional: true, reloadOnChange: true)
.Build();
</code>```

If you call as separate file like this then it will come, or else you can add the contents of Provinces to your appconfig json file and get it as section for that your current code will work.

ContentLicense: CC BY-SA 4.0

Body:
I have a json like this to read in c# but it showing null.

Provices.json contains this json

{
   "Provinces": {
        "States": [
          {
            "CountryId": 1,
            "Name": "AA (Armed Forces Americas)",
            "Abbreviation": null,
            "Published": false,
            "DisplayOrder": 0,
            "Country": null,
            "Id": 1
          },
          {
            "CountryId": 1,
            "Name": "AE (Armed Forces Europe)",
            "Abbreviation": null,
            "Published": false,
            "DisplayOrder": 0,
            "Country": null,
            "Id": 54
          }
    ]
  }
}

start up file contains

 services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
 services.Configure<Provinces>(Configuration.GetSection("Provinces"));

This is c# models

   public class Provinces
    {
        public Provinces()
        {
            this.States = new List<State>();
        }
        public List<State> States { get; set; }
    }

    public class State
    {
        public int CountryId { get; set; }

        public string Name { get; set; }

        public string Abbreviation { get; set; }

        public bool Published { get; set; }

        public bool DisplayOrder { get; set; }

        public string Country { get; set; }

        public int Id { get; set; }

    }

This is how I am reading this file which is giving me null values

public class UserService
{
 public UserService(IOptions<AppSettings> appSettings,
  IOptions<Provinces> states)
    {
           _appSettings = appSettings;
            _states = states;
     }

//Getting value from json

 public List<State> GetStates()
        {
            var data = this._states.Value.States; // Zero count shows here
            return new List<State>();
        }

}

I am also reading AppSettings.json which is working fine but province.json is not working.Can You please tell what's wrong i did

Body:
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJson(yourconfigSetting.json optional: true, reloadOnChange: true)
.AddJsonFile("Provinces.json", optional: true, reloadOnChange: true)
.Build();

If you call as separate file like this then it will come, or else you can add the contents of Provinces to your appconfig json file and get it as section for that your current code will work.


问:
how to avoid memory wastage when storing UTF-8 characters (8 bit) in Java character (16 bit). two in one?
I'm afraid I have a question on a detail of a rather oversaturated topic, I searched aroudn a lot, but couldn't find a clear answer to that specific obvious -imho- important, problem:

When converting byte[] to String using UTF-8, each byte (8bit) becomes a 8 bit character encoded by UTF-8, but each UTF-8 character is saved as a 16 bit character in java. Is that correct?
If yes, this means, that each stupid java character only uses the first 8 bits, and consumes double the memory? Is that correct too? I wonder how this wasteful behaviour is acceptable..

Isn't there some trick to have a pseudo String that is 8 bit?  Would that actually result in less memory consumption?
Or maybe, is there a way to store >two< 8bit characters in one java 16bit character to avoid this memory waste?

thanks for any deconfusing answers...

EDIT:
hi, thanks everybody for answering. I was aware of the variable-length property of UTF-8. However, since my source is byte which is 8 bit, I understood (apparently wrongly) that it needs only 8-bit UTF-8 words. Is UTF-8 conversion actually saving the strange symbols that you see when on the CLI you do "cat somebinary" ? I thought UTF-8 was just somehow used to map each of the possible 8bit words of byte to one particular 8 bit word of UTF-8. Wrong? I thought about using Base64 but it's bad because it uses only 7 bit..

questions reformulated: is there a smarter way to convert byte to something String?
May favorite was to just cast byte[] to char[], but then I still have 16bit words.

additional use case info:

I'm adapting Jedis (java client for the NoSQL Redis) as the  "primitive storage layer" for hypergraphDB. So, jedis is a database for another "database".
My problem is that I have to feed jedis with byte[] data all the time, but internally, >Redis< (the actual server)  is dealing only with "binary safe" Strings. Since Redis is written in C, a char is 8 bit long, AFAIK not ASCIII which is 7 bit. In Jedis however, java world, every character is 16 bit long internally. I don't understand this code (yet), but I suppose jedis then converts this java 16 bit strings to a Redis conforming 8 bit string (([here][3]). It says it extends FilterOutputStream. My hope is to bypass the byte[] <-> string conversion altogether and use that Filteroutputstream...?  )

now I wonder: if I had to interconvert byte[] and String all the time, with datasizes ranging from very small to potentially very big, isn't there a huge waste of memory to have each 8 bit character passed around as 16bit within java?

答:
Redis (the actual server) is dealing only with "binary safe" Strings.

I take this to mean that you can use arbitrary octet sequences for the keys/values. If you can use any C char sequence without thought to character encoding, then the equivalent in Java is the byte type.

Strings in Java are implicitly UTF-16. I mean, you could stick arbitrary numbers in there, but the intent of the class is to represent Unicode character data. Methods that do byte-to-char transformations perform transcoding operations from a known encoding to UTF-16.

If Jedis treats keys/values as UTF-8, then it will not support every value that Redis supports. Not every byte sequence is valid UTF-8, so the encoding can't be used for binary safe strings.

Whether UTF-8 or UTF-16 consumes more memory depends on the data - the euro symbol (€) for example consumes three bytes in UTF-8 and only two in UTF-16.

ContentLicense: CC BY-SA 3.0


问:
Select data where condition matches and if none, then select all?

select * from (values
    ('dept1','user1'),
    ('dept2','user2'),
    ('dept3','user3'),
    ('dept4','user4')
    )table1([department],[user])
where [user] = @id
```

<p>scenario1:
     @id = 'user1'</p>

```dept1
```

<p>scenario2:
    @id = 'user5'</p>

```dept1
dept2
dept3
dept4
```

<p>this is what it looks like from a noobish query</p>

<pre class="lang-sql prettyprint-override"><code>declare @id varchar(12) = 'user1'
declare @var int = (select count(*) from table1 where [user] = @id)

select * from table1 where [user] = @id or @var = 0
</code>```

答:
```<code>declare @tab table (id int , value varchar(10))
declare @id int = 4

insert into @tab
select 1,'Ajay'
union all
select 2,'Ajay1'
union all
select 3,'Ajay2'
union all
select 4,'Ajay3'
union all
select 5,'Ajay4'

select * from @tab
where id = case when exists (select * from @tab where id = @id) then @id else id end
</code>```

Body:
select * from (values
    ('dept1','user1'),
    ('dept2','user2'),
    ('dept3','user3'),
    ('dept4','user4')
    )table1([department],[user])
where [user] = @id

scenario1:
     @id = 'user1'

dept1

scenario2:
    @id = 'user5'

dept1
dept2
dept3
dept4

this is what it looks like from a noobish query

declare @id varchar(12) = 'user1'
declare @var int = (select count(*) from table1 where [user] = @id)

select * from table1 where [user] = @id or @var = 0


问:
Is there a way to create custom URLs in WordPress for each client
I'm trying to create a site for a client who want's to use the WP Workscout theme. He want's a client portal that's able to do 2 things;

The clients logo and basic chosen style in their portal area

A url for the client for example clientname.companyname.com

I could do this quite simply with a custom site but I'm not sure about WordPress. Is it possible? If so, how?

Any help would be greatly appreciated

答:
You might want to consider building a WordPress multisite. Sounds like it might be what you're looking for.

It will allow you to have some different styling for each site in the network, and you can set up each site on different subdomains.

https://wordpress.org/support/article/create-a-network/

https://www.wpbeginner.com/wp-tutorials/how-to-install-and-setup-wordpress-multisite-network/


问:
Implementation of BERT in keras with TF_HUB
I was trying to implement the Google Bert model in tensorflow-keras using tensorflow hub. For this I designed a custom keras layer "Bertlayer" . Now the problem is when I am compiling the keras model it keeps showing that

AttributeError: 'Bertlayer' object has no attribute '_keras_style'

I don't know where I am wrong and what _keras_style attribute is.Please help to find the error in the code.

This is the github link to the full code: https://github.com/PradyumnaGupta/BERT/blob/master/Untitled21.ipynb

class BertLayer(tf.layers.Layer):
    def __init__(self, n_fine_tune_layers=10, **kwargs):
        self.n_fine_tune_layers = n_fine_tune_layers
        self.trainable = True
        self.output_size = 768
        super(BertLayer, self).__init__(**kwargs)

    def build(self, input_shape):
        self.bert = hub.Module(
            bert_path,
            trainable=self.trainable,
            name="{}_module".format(self.name)
        )

        trainable_vars = self.bert.variables

        # Remove unused layers
        trainable_vars = [var for var in trainable_vars if not "/cls/" in var.name]

        # Select how many layers to fine tune
        trainable_vars = trainable_vars[-self.n_fine_tune_layers :]

        # Add to trainable weights
        for var in trainable_vars:
            self._trainable_weights.append(var)

        for var in self.bert.variables:
            if var not in self._trainable_weights:
                self._non_trainable_weights.append(var)

        super(BertLayer, self).build(input_shape)

    def call(self, inputs):
        inputs = [K.cast(x, dtype="int32") for x in inputs]
        input_ids, input_mask, segment_ids = inputs
        bert_inputs = dict(
            input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids
        )
        result = self.bert(inputs=bert_inputs, signature="tokens", as_dict=True)[
            "pooled_output"
        ]
        return result

    def compute_output_shape(self, input_shape):
        return (input_shape[0], self.output_size)
```

答:
So, tensorflow version 1.* is a bit misleading. It actually has 2 bases classes called Layer. One - the one that you are using. It is intended to implement shortcut wrappers over regular TF operations. The other from tensorflow.keras.layers import Layer is for Keras-like models and sequencies.

Judging by your error, you are using keras/models to train further.

You probably should start form derivering your layer from keras.layers.Layer instead of tf.layers.Layer.


问:
What is best way to externalize error messages(resource bundles) out of src code in spring and springboot?
I am looking for best way to externalize my validation error messages out of my src code in spring and spring boot application, in order to avoid build/deployment on each time the error messages changes. Is there possibly any such ways to achieve it?</p>

答:
The default resource bundle framework assumes your resource bundles are property files in your resources folder. So they are packaged inside your jar file as part of your build process.

However you can implement your own ResourceBundle loading:

https://docs.oracle.com/javase/tutorial/i18n/resbundle/control.html

You can then opt to use other mechanisms, including using a database instead of property files (with a TTL to cache messages for a specific period of time). This way you don't even have to restart the application when a message changes.


问:
Is there a better way to use rabbitMQ to consume multithreaded messages?
I am currently learning how to use RabbitMQ to schedule and dispatch jobs to different VM.I am now working on the worker side. The worker on the VM need to do some hard-loading jobs and return to the server if it is successfully done.

I have done some surveys on the official api and also here ,trying to test if it can work.

```<code>Connection connection = factory.newConnection();
final Channel channel = connection.createChannel();
channel.basicQos(10);
Consumer consumer = new DefaultConsumer(channel) {
    @Override
    public void handleDelivery(String consumerTag, final Envelope envelope, AMQP.BasicProperties properties, final byte[] body) throws IOException {
        Thread th = new Thread() {public void run() {
        try{
        //do some jobs here...
        synchronized (this) {channel.basicAck(envelope.getDeliveryTag(), false);}
        } catch (Exception e) {
            e.printStackTrace();
            try {
                synchronized (this) {channel.basicReject(envelope.getDeliveryTag(), false)}
            } catch (IOException e1) {e1.printStackTrace();}
        }
        };
        th.start();
    }
};
channel.basicConsume(queueName, false, consumer);
</code>```

This code works for me. But I am just wondering if there is a better and thread-safer way to do it.

答: How about using an ExecutorService instead of a new thread for every message? Depending on the rate of incoming messages the number of threads created by your approach can grow very large very quickly which could bring down your service.

Body:
I am currently learning how to use RabbitMQ to schedule and dispatch jobs to different VM.I am now working on the worker side. The worker on the VM need to do some hard-loading jobs and return to the server if it is successfully done.

I have done some surveys on the official api and also here ,trying to test if it can work.

Connection connection = factory.newConnection();
final Channel channel = connection.createChannel();
channel.basicQos(10);
Consumer consumer = new DefaultConsumer(channel) {
    @Override
    public void handleDelivery(String consumerTag, final Envelope envelope, AMQP.BasicProperties properties, final byte[] body) throws IOException {
        Thread th = new Thread() {public void run() {
        try{
        //do some jobs here...
        synchronized (this) {channel.basicAck(envelope.getDeliveryTag(), false);}
        } catch (Exception e) {
            e.printStackTrace();
            try {
                synchronized (this) {channel.basicReject(envelope.getDeliveryTag(), false)}
            } catch (IOException e1) {e1.printStackTrace();}
        }
        };
        th.start();
    }
};
channel.basicConsume(queueName, false, consumer);

This code works for me. But I am just wondering if there is a better and thread-safer way to do it.


问:
FAILURE: Build failed with an exception in ionic 4
I have created an app called phone(ionic v-4). I have tried to implement Phone authentication i,e OTP verification using firebase by following this article   in the medium.

Now i tried to deploy my app(phone) in my android device, using below command.

```<code>ionic cordova run android
</code>```

I am getting this error:

But the app runs fine in the browser.

I am unable to perceive the error.

答:
Do try to remove and add again the Android platform

```<code>ionic cordova platform rm android
ionic cordova platform add android
</code>```

Body:
I have created an app called phone(ionic v-4). I have tried to implement Phone authentication i,e OTP verification using firebase by following this article   in the medium.

Now i tried to deploy my app(phone) in my android device, using below command.

ionic cordova run android

I am getting this error:

But the app runs fine in the browser.

I am unable to perceive the error.

Body:
Do try to remove and add again the Android platform

ionic cordova platform rm android
ionic cordova platform add android


问:
Encrypting config files for deployment
I have a windows service that reads from app.config.

I want some settings to be encrypted, however, I don't want to use the ProtectedConfigurationProvider classes provided in .NET because they encrypt files based on the machine they are running on using DPAPI.

What I wanted was a way for our administrator to deploy the config file already encrypted to many machines and have each machine decrypt them when needed.

I don't want to hardcode a password into the assembly either so I'm not sure how I can go about this.

答:
reduce the problem to its simplest form:

you have a program

that will be given an encrypted file

and you want to decrypt the file

without hard-coding the key

the obvious solution is to ask for the key when needed from a trusted third party

OwnerDisplayName: Sir Psycho

ContentLicense: CC BY-SA 2.5

Title: Encrypting config files for deployment

LastEditorDisplayName: Steven A. Lowe

OwnerDisplayName: Steven A. Lowe


问:
What's the difference between hacks and messy/bad code
When is code a hack?

People seem to define a hack as ugly coding to solve a problem but how is that different from writing messy code.

Also is the only difference between a problem coded badly and a problem hacked the mindset of the programmer?

When I say hack I mean in the programming/development sense not the illegal sense.

答:
A hack is a section of code you write to overcome a technology deficiency such as your programming language, communications protocol, hardware, or some other programmer's bug.  You usually tag your code as a hack to let other people know you could have done it the "right" way if you just didn't have this limitation.

That being said, it is often misused and simply refers to a section of code where the programmer was too lazy to do it the "right" way, or where the code seems to work for what they designed, but they are aren't sure of the unintended consequences. For example: one may "hack" code if it was poorly designed and they don't understand what the change is going to really do to the entire system.  That isn't really a hack, it is just a lack of understanding.


问:
Problem to Implement intlTelInput in Laravel
I am using intlTelInput in plain HTML/CSS using below code and it's working fine you can see the demo (intl-tel-input sample).

HTML code

```<code><label for="phone" class="control-label">Mobile Phone Number</label><br/>
<input type="tel" class="form-control" id="phone" placeholder="">
</code>```

Javascript code

```<code> <script>
 var input = document.querySelector("#phone");
intlTelInput(input, {
initialCountry: "auto",
geoIpLookup: function(success, failure) {
    $.get("https://ipinfo.io", function() {}, "jsonp").always(function(resp) {
        var countryCode = (resp && resp.country) ? resp.country : "";
        success(countryCode);
    });
},
utilsScript: "css/intl-tel-input-master/build/js/utils.js"
});
</code>```

Now, I am using the same code in laravel and it shows me nothing. Can you please tell me how to solve the issue?

GET https://ipinfo.io/?callback=jQuery1111094…1559198167627&=1559198167628 net::ERR_ABORTED 429

答:
This has nothing to do with Laravel. If you try your javascript code outside of Laravel you should find you get the same error.

429 TOO MANY REQUESTS

  The user has sent too many requests in a given amount of time ("rate limiting").

A 429 error suggests you have exceeded the request limit for the ipinfo.io API.

Looking on ipinfo.io it shows that the free tier of only allows a maximum of 1000 requests per day. Could you have exceeded that amount?

Body:
I am using intlTelInput in plain HTML/CSS using below code and it's working fine you can see the demo (intl-tel-input sample).

HTML code

Mobile Phone Number

<input type="tel" class="form-control" id="phone" placeholder="">

Javascript code


问:
SymPy/SciPy: Involving time-dependent values
I'm new to SymPy and SciPy and looking for a way to involve time-dependent variables in a symbolic expression.

For example to differentiate x(t) with respect to t which should result in xd(t) or similar.

Up to know I did not find an appropriate example, how to do that?

答:
dynamicsymbols has an automatic t that comes with the symbol, too:

```<code>>>> from sympy.physics.mechanics import *
>>> dynamicsymbols('x')
x(t)
>>> _.diff(t)
Derivative(x(t), t)
</code>```

Body:
dynamicsymbols has an automatic t that comes with the symbol, too:

>>> from sympy.physics.mechanics import *
>>> dynamicsymbols('x')
x(t)
>>> _.diff(t)
Derivative(x(t), t)


问:
HttpSendRequest() functions fails after two request and returns after timeout, how to deal
I am trying to download same files with different ranges at a time via multiple threads( >2 )

But among all these threads, any two threads are successfully passes HttpSendRequest() function and in remaining threads HttpSendRequest() fails after timeout with GetLastError() code of 0.

Is HttpSendRequest() only allow to send 2 request or is their any other way to handle this situation??

答:
HTTP allowed maximum two connection. to increase connections you can use Option Flags to with InternetSetOption() function.

You will find code in this link.


问:
JEditable custom types causes edit to go blank
I need an inline format hat consists of one text area and one text box. I decided to write a custom type for Jeditable using the following code:

```<code>    $.editable.addInputType('edit_area', {
        element : function(settings, original) {
            var input = $('<textarea id=\"bio\">');
            $(this).append(input);

            var source = $('<input type="text" id="source" />');
            $(this).append(source);

            var hidden = $('<input type="hidden" />');
            $(this).append(hidden);

            return(hidden);
        },
        submit: function (settings, original) {
            var value = $('#bio').val();

            $(':hidden', this).val(value);
        }
    });

    $('.edit_area').editable('/MyUrl/', {
        type      : 'edit_area',
        cancel    : 'Cancel',
        submit    : 'OK',
        submitdata : function(value, settings) {
            var source = $("#source").val();

            return {foo: source};
        }
    });
</code>```

This code works BUT once the information is posted to the server (server returns an empty result) it looks like Jeditable takes that empty response and uses it on the screen which causes the edited text to go blank. I tried returning the edited text in which case the code works but I don't want to be returning all that text unless I have to.

Has anyone seen this issue before? Any help is appreciated.

Thanks

答: I think it's not possible not to return the value in your server action. In the Jeditable documentation it's clearly stated that there are two parameters posted to the server: "id" and "value", and that the new displayed text is what the server returns.</p>

Body:
I need an inline format hat consists of one text area and one text box. I decided to write a custom type for Jeditable using the following code:

    $.editable.addInputType('edit_area', {
        element : function(settings, original) {
            var input = $('<textarea id=\"bio\">');
            $(this).append(input);

            var source = $('<input type="text" id="source" />');
            $(this).append(source);

            var hidden = $('<input type="hidden" />');
            $(this).append(hidden);

            return(hidden);
        },
        submit: function (settings, original) {
            var value = $('#bio').val();

            $(':hidden', this).val(value);
        }
    });

    $('.edit_area').editable('/MyUrl/', {
        type      : 'edit_area',
        cancel    : 'Cancel',
        submit    : 'OK',
        submitdata : function(value, settings) {
            var source = $("#source").val();

            return {foo: source};
        }
    });

This code works BUT once the information is posted to the server (server returns an empty result) it looks like Jeditable takes that empty response and uses it on the screen which causes the edited text to go blank. I tried returning the edited text in which case the code works but I don't want to be returning all that text unless I have to.

Has anyone seen this issue before? Any help is appreciated.

Thanks


问:
How to use map(ES6) to return a list of functions?(ES6)
How can I use map to return this output

get funcone() { return this.Form.get(funcone"); }
get functwo() { return this.Form.get("functwo"); }
get functhree() { return this.Form.get("functhree"); }
get funcfour() { return this.Form.get("funcfour"); }
 ```
</div>
</div>
</p>

<p>I used this array</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>FormValues=['funcone','functwo','functhree','funcfour'];</code>```

And this map

FormValues.map(Value=>{
    get Value() { return this.Form.get(Value); }
 })```

I would appreciate any help!

答:
Presumably you want to define those functions as getters on some object, or class. Let's assume it's a class.

That syntax can't work - it creates a Value getter, rather than funcone getter. Now, while you can define a getter using a variable for the getter's name:

```<code>let propName = "foo";
class Foo {
  get [propName]() { return "You're getting a foo"; }
}
new Foo().foo
// => "You're getting a foo"
</code>```

as far as I know, there's no way to make a loop inside the class declaration, nor a way to keep reopening a class and adding new stuff to it like in Ruby, so class definition inside a loop also won't work.

However, class syntax is just a sugar for the older prototypal inheritance, so everything we can do with the class syntax, we can also do without it (though vice versa does not hold). In order to add new stuff to the class, we just need to stick it to the class's prototype object. We can explicitly define a getter method using Object.defineProperty.

```<code>class Foo {
  constructor() {
    this.Form = {
      one: 1,
      two: 2,
      three: 3,
      four: 4
    }
  }
}

let props = ['one', 'two', 'three', 'four'];
props.forEach(propName =>
  Object.defineProperty(Foo.prototype, propName, {
    get: function() { return this.Form[propName]; }
  })
);

new Foo().three
// => 3
</code>```

It would be almost the same code to give the getters to an object rather than a class; you'd just be defining properties on the object itself, rather than on a prototype.

Body:
How can I use map to return this output

get funcone() { return this.Form.get(funcone"); }
get functwo() { return this.Form.get("functwo"); }
get functhree() { return this.Form.get("functhree"); }
get funcfour() { return this.Form.get("funcfour"); }

I used this array

FormValues=['funcone','functwo','functhree','funcfour'];

And this map

FormValues.map(Value=>{
    get Value() { return this.Form.get(Value); }
 })

I would appreciate any help!

Body:
Presumably you want to define those functions as getters on some object, or class. Let's assume it's a class.

That syntax can't work - it creates a Value getter, rather than funcone getter. Now, while you can define a getter using a variable for the getter's name:

let propName = "foo";
class Foo {
  get [propName]() { return "You're getting a foo"; }
}
new Foo().foo
// => "You're getting a foo"

as far as I know, there's no way to make a loop inside the class declaration, nor a way to keep reopening a class and adding new stuff to it like in Ruby, so class definition inside a loop also won't work.

However, class syntax is just a sugar for the older prototypal inheritance, so everything we can do with the class syntax, we can also do without it (though vice versa does not hold). In order to add new stuff to the class, we just need to stick it to the class's prototype object. We can explicitly define a getter method using Object.defineProperty.

class Foo {
  constructor() {
    this.Form = {
      one: 1,
      two: 2,
      three: 3,
      four: 4
    }
  }
}

let props = ['one', 'two', 'three', 'four'];
props.forEach(propName =>
  Object.defineProperty(Foo.prototype, propName, {
    get: function() { return this.Form[propName]; }
  })
);

new Foo().three
// => 3

It would be almost the same code to give the getters to an object rather than a class; you'd just be defining properties on the object itself, rather than on a prototype.


问:
Laravel/Mysql - Manipulate large data
Dears,

Actually, I would like to know the best solution to manipulate BIG DATA in LARAVEL/MYSQL.

In my system, am uploading daily excel file (5K rows) into my DB, in case I find the same row in my table so I don't insert it, and if I find the same row, I changed the uploaded date in my DB.

Every time I upload the excel, am checking each row if exist in my table (table contain > 50K) with a normal array like the below

           $res = policies::where('phone', '=', $row['phone'])
                      ->where('draft_no', '=', $row['draftno'])
                      ->where('due_date', '=', $duedate)
                      ->where('status', '=', $stat)
                      ->where('bord_date', '=', $borddate)
                      ->where('amount', '=', $row['amnt'])
                      ->where('remarks', '=', $row['remarks'])
                      ->exists();

                    if(!$res) {
                   // insert row ($table->save())
                    }
                    else {
                      //update uploaded date to this row.
                    }

```

this process takes lots of time bcz each time is checking the table.  I tried to use array_chunk in order to insert, but still, the load is big (15 min to 20 min) to finish

Your advice are highly appreciated.

Thanks

答:
You can create an hash of each row and store along with the row. Then check only the row with given hash.

For instance try this stub of code

```<code>foreach ($rows as $row) {
    $hash = md5($row['phone'] . $row['draft_no'] . $row['due_date'] ...);
    $res = Policiess::where('hash', $hash);
    if (!$res) {
         // create a new row and store the `$hash` in `hash` column
    } else {
         //update uploaded date to this row
    }
}
</code>```

Title: Laravel/Mysql - Manipulate large data

Body:
Dears,

Actually, I would like to know the best solution to manipulate BIG DATA in LARAVEL/MYSQL.

In my system, am uploading daily excel file (5K rows) into my DB, in case I find the same row in my table so I don't insert it, and if I find the same row, I changed the uploaded date in my DB.

Every time I upload the excel, am checking each row if exist in my table (table contain > 50K) with a normal array like the below

           $res = policies::where('phone', '=', $row['phone'])
                      ->where('draft_no', '=', $row['draftno'])
                      ->where('due_date', '=', $duedate)
                      ->where('status', '=', $stat)
                      ->where('bord_date', '=', $borddate)
                      ->where('amount', '=', $row['amnt'])
                      ->where('remarks', '=', $row['remarks'])
                      ->exists();

                    if(!$res) {
                   // insert row ($table->save())
                    }
                    else {
                      //update uploaded date to this row.
                    }

this process takes lots of time bcz each time is checking the table.  I tried to use array_chunk in order to insert, but still, the load is big (15 min to 20 min) to finish

Your advice are highly appreciated.

Thanks

Body:
You can create an hash of each row and store along with the row. Then check only the row with given hash.

For instance try this stub of code

foreach ($rows as $row) {
    $hash = md5($row['phone'] . $row['draft_no'] . $row['due_date'] ...);
    $res = Policiess::where('hash', $hash);
    if (!$res) {
         // create a new row and store the `$hash` in `hash` column
    } else {
         //update uploaded date to this row
    }
}


问:
Short way to apply a function to all elements in a list in golang
Suppose I would like to apply a function to every element in a list, and then put the resulting values in another list so I can immediately use them. In python, I would do something like this:

list = [1,2,3]
str = ', '.join(multiply(x, 2) for x in list)
```

<p>In Go, I do something like this:</p>

```list := []int{1,2,3}
list2 := []int

for _,x := range list {
    list2 := append(list2, multiply(x, 2))
}

str := strings.Join(list2, ", ")
```

Is it possible to do this in a shorter way?

答:
Found a way to define a generic map array function</p>

```<code>func Map(t interface{}, f func(interface{}) interface{} ) []interface{} {
    switch reflect.TypeOf(t).Kind() {
    case reflect.Slice:
        s := reflect.ValueOf(t)
        arr := make([]interface{}, s.Len())
        for i := 0; i < s.Len(); i++ {
            arr[i] = f(s.Index(i).Interface())
        }
        return arr
    }
    return nil
}

origin := []int{4,5,3}
newArray := Map(origin, func(item interface{}) interface{} { return item.(int) + 1})
</code>```

Body:
Suppose I would like to apply a function to every element in a list, and then put the resulting values in another list so I can immediately use them. In python, I would do something like this:

list = [1,2,3]
str = ', '.join(multiply(x, 2) for x in list)

In Go, I do something like this:

list := []int{1,2,3}
list2 := []int

for _,x := range list {
    list2 := append(list2, multiply(x, 2))
}

str := strings.Join(list2, ", ")

Is it possible to do this in a shorter way?

Body:
Found a way to define a generic map array function

func Map(t interface{}, f func(interface{}) interface{} ) []interface{} {
    switch reflect.TypeOf(t).Kind() {
    case reflect.Slice:
        s := reflect.ValueOf(t)
        arr := make([]interface{}, s.Len())
        for i := 0; i < s.Len(); i++ {
            arr[i] = f(s.Index(i).Interface())
        }
        return arr
    }
    return nil
}

origin := []int{4,5,3}
newArray := Map(origin, func(item interface{}) interface{} { return item.(int) + 1})


问:
Regex for getting exact git email configured
Here is the git show -s HEAD output

```<code>smilyface@smilingface /d/workspace/shirt (develop)
$ git show -s HEAD
commit f601411d4be3c3fbafea79c72ecc84ad78219265
Author: Smily Face <v-smily@somedomaingoeshere.com>
Date:   Wed May 29 15:22:45 2019 +0530

    Ticket-249843 : [shirt team apps] Deprecation of x function in Jenkinsfile
</code>```

Here is what I have tried -

Try 1 :

```<code>git show -s HEAD | grep "Author:" | grep -Po '(?<=(<)).*(?=@)'
</code>```

Output:

v-smily

Problem :

Sometimes the email could start with v- and sometimes without v-.

For example - Email and Output expected

abcd@somedomaingoeshere.com -> abcd

v-xyz@somedomaingoeshere.com -> xyz

v-pqr@somedomaingoeshere.com -> pqr

答:
If you want to stick with PCRE, you may use

```<code>git show -s HEAD | grep -oP 'Author:.*<(v-)?\K[^@]+'
</code>```

The Author:.*<(v-)?\K[^@]+ pattern matches Author:, any 0+ chars up to the rightmost < that is optionally followed with v-, then \K is used to delete all matched text from the match buffer, and then [^@]+ matches 1+ chars other than @.

See the regex demo and the online grep demo.

Alternatively, use

```<code>git show -s HEAD | grep -oE 'Author:.*<[^@]+' | sed -E 's/Author:.*<(v-)?//'
</code>```

Extract a string starting with Author:, any 0+ chars, < and then 1+ chars other than @, and then use sed to remove what you do not need, all the string from Author: up to < and an optional v-.

Body:
Here is the git show -s HEAD output

smilyface@smilingface /d/workspace/shirt (develop)
$ git show -s HEAD
commit f601411d4be3c3fbafea79c72ecc84ad78219265
Author: Smily Face <v-smily@somedomaingoeshere.com>
Date:   Wed May 29 15:22:45 2019 +0530

    Ticket-249843 : [shirt team apps] Deprecation of x function in Jenkinsfile

Here is what I have tried -

Try 1 :

git show -s HEAD | grep "Author:" | grep -Po '(?<=(<)).*(?=@)'

Output:

v-smily

Problem :

Sometimes the email could start with v- and sometimes without v-.

For example - Email and Output expected

abcd@somedomaingoeshere.com -> abcd

v-xyz@somedomaingoeshere.com -> xyz

v-pqr@somedomaingoeshere.com -> pqr

Body:
If you want to stick with PCRE, you may use

git show -s HEAD | grep -oP 'Author:.*<(v-)?\K[^@]+'

The Author:.*<(v-)?\K[^@]+ pattern matches Author:, any 0+ chars up to the rightmost < that is optionally followed with v-, then \K is used to delete all matched text from the match buffer, and then [^@]+ matches 1+ chars other than @.

See the regex demo and the online grep demo.

Alternatively, use

git show -s HEAD | grep -oE 'Author:.*<[^@]+' | sed -E 's/Author:.*<(v-)?//'

Extract a string starting with Author:, any 0+ chars, < and then 1+ chars other than @, and then use sed to remove what you do not need, all the string from Author: up to < and an optional v-.


问:
Patching an entity and getting duplicate items
I'm having problems with editing an entity. I have ObjectSpecifications that have different conditions. The problem I have has to do with the DimensionalConditions.

Whenever I edit an ObjectSpecification which has let's say "length: 1", and I try to add "width: 2" to it, the conditions end up being "length: 1, length: 1, width: 2".

Long story short, the conditions that were present before, get inserted again for some reason.

```<code>public ObjectSpecification modifySpecification(Long id, ObjectSpecificationRequest request) {
        ObjectSpecification objectSpecification = this.getObjectSpecificationById(id);
        return this.setSpecData(request, objectSpecification);
    }

public ObjectSpecification createSpecification(ObjectSpecificationRequest request){
        return this.setSpecData(request, new ObjectSpecification());
    }

public void deleteSpecification(Long id) {
        objectSpecificationRepository.delete(getObjectSpecificationById(id));
    }

public ObjectSpecification setSpecData(ObjectSpecificationRequest request, ObjectSpecification objectSpecification) {
        if (request.getName() != null) {
            objectSpecification.setName(request.getName());
        }

        if (request.getDimensionalConditions() != null) {
            List<DimensionalCondition> dimensionalConditions = new ArrayList<>();
            for (DimensionalCondition condition:request.getDimensionalConditions()) {
                DimensionalCondition dimensionalCondition = new DimensionalCondition();
                dimensionalCondition.setConditionType(condition.getConditionType());
                dimensionalCondition.setValue(condition.getValue());
                dimensionalCondition.setObjectSpecification(objectSpecification);
                dimensionalConditions.add(dimensionalCondition);
            }
            objectSpecification.setDimensionalConditions(dimensionalConditions);
        }

        if (request.getMechanisms() != null) {
            objectSpecification.setMechanismConditions(request.getMechanisms());
        }

        if (request.getServices() != null) {
            objectSpecification.setServiceConditions(request.getServices());
        }

        if (request.getWorkDetails() != null) {
            List<WorkDetail> workDetails = new ArrayList<>();
            for (WorkDetail workDetail:request.getWorkDetails()) {
                workDetails.add(workDetailService.getWorkDetailById(workDetail.getId()));
            }
            objectSpecification.setWorkDetailConditions(workDetails);
        }

        return objectSpecificationRepository.save(objectSpecification);
    }
</code>```

答:
1) This is a big update list there, make sure you merge your ObjectSpecification so that it is aligned with the PersistenceContext before you do any amendments.

2) You do not take under consideration the existing DimensionalCondition that are linked to ObjectSpecification. You always create a new one:

```<code>List<DimensionalCondition> dimensionalConditions = new ArrayList<>();
</code>```

3) Make sure you have your cascading configured to {PERSIST, MERGE} at least on @OneToMany List<DimensionalCondition>.

Body:
I'm having problems with editing an entity. I have ObjectSpecifications that have different conditions. The problem I have has to do with the DimensionalConditions.

Whenever I edit an ObjectSpecification which has let's say "length: 1", and I try to add "width: 2" to it, the conditions end up being "length: 1, length: 1, width: 2".

Long story short, the conditions that were present before, get inserted again for some reason.

public ObjectSpecification modifySpecification(Long id, ObjectSpecificationRequest request) {
        ObjectSpecification objectSpecification = this.getObjectSpecificationById(id);
        return this.setSpecData(request, objectSpecification);
    }

public ObjectSpecification createSpecification(ObjectSpecificationRequest request){
        return this.setSpecData(request, new ObjectSpecification());
    }

public void deleteSpecification(Long id) {
        objectSpecificationRepository.delete(getObjectSpecificationById(id));
    }

public ObjectSpecification setSpecData(ObjectSpecificationRequest request, ObjectSpecification objectSpecification) {
        if (request.getName() != null) {
            objectSpecification.setName(request.getName());
        }

        if (request.getDimensionalConditions() != null) {
            List<DimensionalCondition> dimensionalConditions = new ArrayList<>();
            for (DimensionalCondition condition:request.getDimensionalConditions()) {
                DimensionalCondition dimensionalCondition = new DimensionalCondition();
                dimensionalCondition.setConditionType(condition.getConditionType());
                dimensionalCondition.setValue(condition.getValue());
                dimensionalCondition.setObjectSpecification(objectSpecification);
                dimensionalConditions.add(dimensionalCondition);
            }
            objectSpecification.setDimensionalConditions(dimensionalConditions);
        }

        if (request.getMechanisms() != null) {
            objectSpecification.setMechanismConditions(request.getMechanisms());
        }

        if (request.getServices() != null) {
            objectSpecification.setServiceConditions(request.getServices());
        }

        if (request.getWorkDetails() != null) {
            List<WorkDetail> workDetails = new ArrayList<>();
            for (WorkDetail workDetail:request.getWorkDetails()) {
                workDetails.add(workDetailService.getWorkDetailById(workDetail.getId()));
            }
            objectSpecification.setWorkDetailConditions(workDetails);
        }

        return objectSpecificationRepository.save(objectSpecification);
    }

Body:
1) This is a big update list there, make sure you merge your ObjectSpecification so that it is aligned with the PersistenceContext before you do any amendments.

2) You do not take under consideration the existing DimensionalCondition that are linked to ObjectSpecification. You always create a new one:

List<DimensionalCondition> dimensionalConditions = new ArrayList<>();

3) Make sure you have your cascading configured to {PERSIST, MERGE} at least on @OneToMany List<DimensionalCondition>.


答: if you not add new record same excel then not need check in database. but you add same excel file new record then insert all record after update this excel file</p>

Title: Laravel/Mysql - Manipulate large data


问:
How to find a servlet object by name?
OK, completely noob to JSP here. I need to find the code that handles a form submission, but I did a text search and can't find it at all.

I have this in my web.xml

```<code><servlet-mapping>
    <servlet-name>myservlet</servlet-name>
    <url-pattern>/flow.htm</url-pattern>
</servlet-mapping>
</code>```

The flow.htm is where the form is posting to. How do I locate the java code that handles the post?

答:
In the same web.xml there must be a declaration of myservlet servlet similar to this:

```<code><servlet>
    <servlet-name>myservlet</servlet-name>
    <servlet-class>com.example.YourServlet</servlet-class>
</servlet>
</code>```

com.example.YourServlet is the class you should investigate (of course in your code it will be a different class). If your form sends the data using POST, look at doService method in this class.

Title: How to find a servlet object by name?

Body:
OK, completely noob to JSP here. I need to find the code that handles a form submission, but I did a text search and can't find it at all.

I have this in my web.xml

<servlet-mapping>
    <servlet-name>myservlet</servlet-name>
    <url-pattern>/flow.htm</url-pattern>
</servlet-mapping>

The flow.htm is where the form is posting to. How do I locate the java code that handles the post?

Body:
In the same web.xml there must be a declaration of myservlet servlet similar to this:

<servlet>
    <servlet-name>myservlet</servlet-name>
    <servlet-class>com.example.YourServlet</servlet-class>
</servlet>

com.example.YourServlet is the class you should investigate (of course in your code it will be a different class). If your form sends the data using POST, look at doService method in this class.


问:
How to test styled components conditionally and children elements?
I'm new to unit testing and I've spent some 20-30 hours in docs, articles and YT videos but still can't make sense of how to achieve this. Basically I want to test 3 things here:

Make sure that this component renders 3  components

Test the conditional styling

Test the click event

So far, for the 1st thing, if I try to do:

```<code>import { shallow } from "enzyme";
import React from "react";
import ButtonsComponent, { SchedButton } from "./ButtonsComponent";

it("renders three <MyButton /> components", () => {
  const wrapper = shallow(<ButtonsComponent />);
  expect(wrapper.find(MyButton)).to.have.lengthOf(3);
});
</code>```

I get the following error:
TypeError: Enzyme::Selector expects a string, object, or Component Constructor

And I don't have any good idea how to test the other two things, I've seen some examples but I don't understand how to adapt them to my particular situation since they don't seem to be testing exactly what I'm trying to do.

This is a simplifed version of my component:

```<code>import React from "react";
import styled from "styled-components";

const MyButton = styled.button`
  background: ${props =>
    props.color ? theme.palette.secondary.dark : "#e6e6e6"};
  color: ${props => (props.color ? "white" : "#737373")};
`;

const ButtonsComponent = ({ currentState, updateState }) => {
  const handleClick = event => {
    updateState(event.target.value);
  };

  return (
    <div>
      <MyButton
        value="Button 1"
        onClick={handleClick}
        color={currentState === "Button 1" ? "#1fbd45" : ""}
      >
        Button 1
      </MyButton>
      <MyButton
        value="Button 2"
        onClick={handleClick}
        color={currentState === "Button 2" ? "#1fbd45" : ""}
      >
        Button 2
      </MyButton>

      <MyButton
        value="Button 3"
        onClick={handleClick}
        color={!currentState || currentState === "Button 3" ? "#1fbd45" : ""}
      >
        Button 3
      </MyButton>
    </div>
  );
};

export default ButtonsComponent;
</code>```

Any help is greatly appreciated, an ELI5 explanation would be so much more!

答:
I will try to answer your questions as detailed as possible.

So you have 3 questions:

1. Make sure that this component renders 3 components

Your test was almost correct. The error was that you were doing:
wrapper.find(MyButton) instead of wrapper.find('MyButton').
To do wrapper.find(MyButton) you need to import the MyButton component first, so something like this should work:

```<code>import { shallow } from "enzyme";
import React from "react";
import ButtonsComponent, { MyButton } from "./ButtonsComponent";

it("renders three <MyButton /> components", () => {
  const wrapper = shallow(<ButtonsComponent />);
  expect(wrapper.find(MyButton)).to.have.lengthOf(3);
});
</code>```

But you can't do this in your code because you are not exporting the MyButton component.
My advise regarding this question would be that you create a file for MyButton component and another file for ButtonsComponent component. In general it is much more clear to have one component per file, and unit testing becomes clearer as well.
Then you will be able to do something like this:

```<code>import { shallow } from "enzyme";
import React from "react";
import ButtonsComponent from "./ButtonsComponent";
import MyButton from "./MyButton"

it("renders three <MyButton /> components", () => {
  const wrapper = shallow(<ButtonsComponent />);
  expect(wrapper.find(MyButton)).to.have.lengthOf(3);
});
</code>```

2. Test the conditional styling

I do not know what testing engine (mocha, jest, etc) you are using, but if I had to choose one to test a React app I would choose Jest (this is just a matter of taste though).
I suggest jest because it have everything you would need, like spies, matchers, etc, and there are also some additional packages that will make your life easier, like in this case.

So to test your styled-components with jest you will need two extra packages react-test-renderer (which basically converts a React components into a js object) and jest-styled-components (which will give you an extra matcher named toHaveStyleRule that will help you a lot with your goal).

With those 2 packages installed what you will do is, first import them:

```<code>import renderer from "react-test-renderer";
import "jest-styled-components";
</code>```

Then you will convert your component to a js object:

```<code>const tree =
  renderer
  .create(<MyButton color="red">Test</MyButton>)
  .toJSON();
</code>```

And finally you will ask for the style you are expecting to have applied with the properties you specified for your component:

```<code>expect(tree).toHaveStyleRule("background-color", "red");
</code>```

3. Test the click event

To test the click event you will need a spy. If you are using jest you already have this feature, if you are using mocha I think you will probably need an extra package like sinon or similar.

The spy will let you track what happen to your updateState function, so when you are testing the click event you will pass a spy function as value of updateState prop. In this way when you simulate the click on your button your spy would be invoked and then you will be able to ask question to it like "have you been called?", as a result you will be able to check that on click event you invoke the updateState function with the expected params.

In this link you will find your example (with a few small modifications) working and with tests for all the things you wanted to check (do not pay attention to the place where the dependencies appear in package.json file, many of them should appear as dev dependencies but for some reason if I do that it does not work, it is probably something I am doing wrong in that tool).

I hope this answer helps you.

Body:
I'm new to unit testing and I've spent some 20-30 hours in docs, articles and YT videos but still can't make sense of how to achieve this. Basically I want to test 3 things here:

Make sure that this component renders 3  components

Test the conditional styling

Test the click event

So far, for the 1st thing, if I try to do:

import { shallow } from "enzyme";
import React from "react";
import ButtonsComponent, { SchedButton } from "./ButtonsComponent";

it("renders three <MyButton /> components", () => {
  const wrapper = shallow(<ButtonsComponent />);
  expect(wrapper.find(MyButton)).to.have.lengthOf(3);
});

I get the following error:
TypeError: Enzyme::Selector expects a string, object, or Component Constructor

And I don't have any good idea how to test the other two things, I've seen some examples but I don't understand how to adapt them to my particular situation since they don't seem to be testing exactly what I'm trying to do.

This is a simplifed version of my component:

import React from "react";
import styled from "styled-components";

const MyButton = styled.button`
  background: ${props =>
    props.color ? theme.palette.secondary.dark : "#e6e6e6"};
  color: ${props => (props.color ? "white" : "#737373")};
`;

const ButtonsComponent = ({ currentState, updateState }) => {
  const handleClick = event => {
    updateState(event.target.value);
  };

  return (

      <MyButton
        value="Button 1"
        onClick={handleClick}
        color={currentState === "Button 1" ? "#1fbd45" : ""}
      >
        Button 1
      </MyButton>
      <MyButton
        value="Button 2"
        onClick={handleClick}
        color={currentState === "Button 2" ? "#1fbd45" : ""}
      >
        Button 2
      </MyButton>

      <MyButton
        value="Button 3"
        onClick={handleClick}
        color={!currentState || currentState === "Button 3" ? "#1fbd45" : ""}
      >
        Button 3
      </MyButton>

  );
};

export default ButtonsComponent;

Any help is greatly appreciated, an ELI5 explanation would be so much more!

Body:
I will try to answer your questions as detailed as possible.

So you have 3 questions:

1. Make sure that this component renders 3 components

Your test was almost correct. The error was that you were doing:
wrapper.find(MyButton) instead of wrapper.find('MyButton').
To do wrapper.find(MyButton) you need to import the MyButton component first, so something like this should work:

import { shallow } from "enzyme";
import React from "react";
import ButtonsComponent, { MyButton } from "./ButtonsComponent";

it("renders three <MyButton /> components", () => {
  const wrapper = shallow(<ButtonsComponent />);
  expect(wrapper.find(MyButton)).to.have.lengthOf(3);
});

But you can't do this in your code because you are not exporting the MyButton component.
My advise regarding this question would be that you create a file for MyButton component and another file for ButtonsComponent component. In general it is much more clear to have one component per file, and unit testing becomes clearer as well.
Then you will be able to do something like this:

import { shallow } from "enzyme";
import React from "react";
import ButtonsComponent from "./ButtonsComponent";
import MyButton from "./MyButton"

it("renders three <MyButton /> components", () => {
  const wrapper = shallow(<ButtonsComponent />);
  expect(wrapper.find(MyButton)).to.have.lengthOf(3);
});

2. Test the conditional styling

I do not know what testing engine (mocha, jest, etc) you are using, but if I had to choose one to test a React app I would choose Jest (this is just a matter of taste though).
I suggest jest because it have everything you would need, like spies, matchers, etc, and there are also some additional packages that will make your life easier, like in this case.

So to test your styled-components with jest you will need two extra packages react-test-renderer (which basically converts a React components into a js object) and jest-styled-components (which will give you an extra matcher named toHaveStyleRule that will help you a lot with your goal).

With those 2 packages installed what you will do is, first import them:

import renderer from "react-test-renderer";
import "jest-styled-components";

Then you will convert your component to a js object:

const tree =
  renderer
  .create(<MyButton color="red">Test</MyButton>)
  .toJSON();

And finally you will ask for the style you are expecting to have applied with the properties you specified for your component:

expect(tree).toHaveStyleRule("background-color", "red");

3. Test the click event

To test the click event you will need a spy. If you are using jest you already have this feature, if you are using mocha I think you will probably need an extra package like sinon or similar.

The spy will let you track what happen to your updateState function, so when you are testing the click event you will pass a spy function as value of updateState prop. In this way when you simulate the click on your button your spy would be invoked and then you will be able to ask question to it like "have you been called?", as a result you will be able to check that on click event you invoke the updateState function with the expected params.

In this link you will find your example (with a few small modifications) working and with tests for all the things you wanted to check (do not pay attention to the place where the dependencies appear in package.json file, many of them should appear as dev dependencies but for some reason if I do that it does not work, it is probably something I am doing wrong in that tool).

I hope this answer helps you.


问:
Angular Filter by 2 dates
I need to add a Filter of the Date range. Mean I need to show only that data which user input from the date and to date. I have an array of data in which there is only one date is showing. But I want to filter it like this user input any 2 dates (From and To) And in the array I only that data show which are between input dates.

```<code>   <div class="row">
   <div class="col-12">
     <div class="content-header">Claims Status</div>
       <p class="content-sub-header">Claims Settled 23</p>
   </div>
  </div>

 <section id="extended">

   <div class="row">
     <div class="col-sm-12">
       <div class="card">

    <div class="row" >
     <div class="col-sm bg-primary text-white" style="text-align: center;" ><div>Claims<br>(settled)</div><div *ngIf="statusunsettledcc">  {{statusunsettledcc}}</div></div>
    <div class="col-sm bg-success text-white" style="text-align: center;"><div>Claim Amount<br>(settled)</div><div *ngIf="statusunsettledamount">{{statusunsettledamount | number : fractionSize}}</div></div>
    <div class="col-sm bg-danger text-white" style="text-align: center;" ><div>Claims<br>(unsettled)</div><div *ngIf="status2settledcc">{{status2settledcc}}</div></div>
    <div class="col-sm bg-warning text-white" style="text-align: center;"><div>Claim Amount<br>(unsettled)</div><div *ngIf="status2settledamount">{{status2settledamount | number : fractionSize}}</div></div>
    </div>

  <div class="card-header">
    <div class="card-title-wrap bar-success">
      <h4 class="card-title">Claims</h4>
    </div>
  </div>
  <div class="card-body">
    <div class="card-block">

      <div class="row">
        <div class="col-md-3">
          <div class="form-group" >
            <label for="">Search Name</label>

            <input type="text" class="form-control" [(ngModel)]="userFilter.member_name" placeholder="Search name" name="search">
          </div>
        </div>

        <div class="col-md-3">
          <div class="form-group" >
            <label for="">Search Claim No</label>
            <input type="search"
            class="form-control" placeholder="Claim No" [(ngModel)]="userFilter.claim_no">
          </div>
        </div>

   <div class="col-md-3 form-group">
        <input type="date" class="form-control" [(ngModel)]="from"> //From date
    </div>
    <div class="col-md-3 form-group">
        <input type="date" class="form-control" [(ngModel)]="to"> //To Date
    </div>

        <div class="col-md-3" *ngIf="company">
          <div class="form-group">
            <label for="">Company</label>
            <select class="form-control" [(ngModel)]="userFilter.company_id" (change)="getClaims()">
              <option value='' >All</option>
              <option value="999">Airlink Communication</option>
              <option value="637">Ascertia (Pvt) Ltd</option>
              <option value="1053">Frontier Works Organization</option>
              <option value="1174">Ebryx (pvt) Ltd</option>
              <option value="274">HY Enterprises (Pvt) Limited</option>
              <option value="459">Naimat Saleem trust NST (US GROUP)</option>
              <option value="659">Samad Rubber Works (Pvt) Ltd</option>
              <option value="56">Sundry Clients</option>
              <option value="620">TIMEXPERTS (PRIVATE) Limited</option>
              <option value="39">US Apparel & Textile (Pvt) Limited</option>
              <option value="40">US Denim Mills (Pvt) Limited</option>
            </select>
          </div>
        </div>

        <div class="col-md-3">
          <div class="form-group">
            <label for="">Claim Status</label>
            <select class="form-control" [(ngModel)]="userFilter.status">
              <option value='' >All</option>

              <option value="submitted">Submitted</option>
              <option value="approved">Approved</option>
              <option value="cancel">Objection Claim</option>
              <option value="settled">Settled</option>
              <option value="rejected">Rejected</option>
              <option value="CLOSED">Closed</option>
              <option value="OUTSTANDING">Outstanding</option>

            </select>
          </div>
        </div>

        <div class="col-md-3" *ngIf="policyclaim">
          <div class="form-group">
           <label for="">Policy</label>
           <select class="form-control" [(ngModel)]="userFilter.policy_id" (change)="getClaims()" style="width: 400px" >
             <option value='' >Select Policy No</option>

             <option *ngFor="let policy of policynumbers" value="{{policy.policy_id}}">{{policy.policy_id}}</option>

           </select>
         </div>
       </div>

        <div class="col-md-3" *ngIf="policysamad">
          <div class="form-group">
           <label for="">Policy</label>
           <select class="form-control" [(ngModel)]="userFilter.policy_id" (change)="getSamad()" style="width: 400px" >
             <option value='' >Select Policy No</option>

             <option *ngFor="let policy of policynumbers" value="{{policy.policy_id}}">{{policy.policy_id}}</option>

           </select>
         </div>
       </div>

     </div>

     <table class="table table-responsive-md text-center">
      <thead>
        <tr>
          <th>STATUS</th>
          <th>Name</th>
          <th>Patient Name</th>
          <th>Approved Amount</th>
          <th>Claimed Amount</th>
          <th>Company</th>
          <th>Submitted By</th>
          <th>Claim No</th>
          <!-- <th>Website URL</th> -->

        </tr>
      </thead>
      <tbody *ngIf="data1">

        <tr *ngFor="let x of data1 | filterBy: userFilter" (click)="openDeal(deletecontent, x)" >

          <td>
            <span class="text-success" *ngIf="x.status == 'submitted'">Submitted</span>
            <span class="text-primary" *ngIf="x.status == 'settled'">Settled</span>
            <span class="text-warning" *ngIf="x.status == 'rejected'">Rejected</span>
            <span class="text-danger" *ngIf="x.status == 'Approved'">Approved</span>
            <span class="text-danger" *ngIf="x.status == 'ojection claim'">Objection claim</span>

          </td>
          <td >
            <div style="text-align: left;">
              <img [src]="x.userPhoto || 'https://mbtskoudsalg.com/images/user-image-png.png'" class="img-sm" alt="" style="text-align: left;">
              {{x.member_name}}
            </div>
          </td>
          <td style="text-align: left;">{{x.patient_name}}</td>
          <td>{{x.approved_value}}</td>
          <td>{{x.claimed_value}}</td>
          <td>

            <span  class="text-success" *ngIf="x.company_id == '999'" >Airlink Communication</span>
            <span class="text-success" *ngIf="x.company_id == '637'">Ascertia (Pvt) Ltd</span>
            <span *ngIf="x.company_id == '1053'" class="text-success">Frontier Works Organization</span>
            <span *ngIf="x.company_id == '1174'" class="text-success">Ebryx (pvt) Ltd</span>
            <span  *ngIf="x.company_id == '274'" class="text-success">HY Enterprises (Pvt) Limited</span>
            <span *ngIf="x.company_id == '459'" class="text-success">Naimat Saleem trust NST (US GROUP)</span>
            <span *ngIf="x.company_id == '659'" class="text-success">Samad Rubber Works (Pvt) Ltd</span>
            <span *ngIf="x.company_id == '56'" class="text-success">Sundry Clients</span>
            <span *ngIf="x.company_id == '620'" class="text-success">TIMEXPERTS (PRIVATE) Limited</span>
            <span *ngIf="x.company_id == '39'" class="text-success">US Apparel & Textile (Pvt) Limited</span>
            <span *ngIf="x.company_id == '40'" class="text-success">US Denim Mills (Pvt) Limited</span>

          </td>

          <td>{{x.submitted_at || 'not-defined'}}

          </td>
          <td>{{x.claim_no}}</td>

        </tr>
       </tbody>
      </table>
    </div>
   </div>
  </div>
</div>
</div>
</section>
</code>```

.ts

```<code>getClaims(){

this.policyclaim = true;

if(this.userFilter.company_id){
this.url = 'url='+this.userFilter.company_id;

this.httpClient.get<any>('url'+this.userFilter.company_id).subscribe(statuses => {
  console.log(statuses);
  console.log(statuses.records[0].Amount);
  this.statusunsettledamount = statuses.records[0].Amount;
  console.log(this.statusunsettledamount);
    console.log(statuses.records[0].cc);
    this.statusunsettledcc = statuses.records[0].cc;

});

this.httpClient.get<any>('url'+this.userFilter.company_id).subscribe(statuses2 => {
  console.log(statuses2);
    console.log(statuses2.records[0].Amount);
    this.status2settledamount = statuses2.records[0].Amount;
    console.log(this.status2settledamount);
    console.log(statuses2.records[0].cc);
    this.status2settledcc = statuses2.records[0].cc;
    console.log(this.status2settledcc);
});

this.httpClient.get<any>('url'+this.userFilter.company_id).subscribe(policyinfo => {
  console.log(policyinfo);
  this.policynumbers = policyinfo.records;
  console.log(this.policynumbers);
});

}

  if (this.from && this.to) {
    const fromDate = new Date(this.from.split(/\D/));
    const toDate = new Date(this.to.split(/\D/));
    this.data1.filter(obj => new Date(obj.date) > fromDate && new Date(obj.date) < toDate);
    console.log(this.data1);
  }

else
{
this.url = 'url/get_claims.php?offset=0&limit=50';

this.httpClient.get<any>('http://api.igiinsurance.com.pk:8888/insurance_IGItakaful/insurance-api/get_claims_amt.php?cstatus=OUTSTANDING').subscribe(statuses => {
  console.log(statuses);
  console.log(statuses.records[0].Amount);
  this.statusunsettledamount = statuses.records[0].Amount;
  console.log(this.statusunsettledamount);
    console.log(statuses.records[0].cc);
    this.statusunsettledcc = statuses.records[0].cc;

});

this.httpClient.get<any>('url/get_claims_amt.php?cstatus=CLOSED').subscribe(statuses2 => {
  console.log(statuses2);
    console.log(statuses2.records[0].Amount);
    this.status2settledamount = statuses2.records[0].Amount;
    console.log(this.status2settledamount);
    console.log(statuses2.records[0].cc);
    this.status2settledcc = statuses2.records[0].cc;
    console.log(this.status2settledcc);
});

this.httpClient.get<any>('url/insurance-api/get_company_policy.php?').subscribe(policyinfo => {
  console.log(policyinfo);
  this.policynumbers = policyinfo.records;
  console.log(this.policynumbers);
});

}

this.clientData = this.httpClient.get<any>(this.url).
subscribe(data => {
console.log(data);
this.spinner.hide();

this.data1 = data.records;
this.data1.forEach(d => this.policy_id.add(d.policy_id));
console.log(this.userFilter.policy_id);

if(this.userFilter.policy_id){

let vv = this.data1.filter(v => v.policy_id === this.userFilter.policy_id);
console.log(vv);

this.httpClient.get<any>('http://url='+this.userFilter.policy_id).subscribe(statuses => {
  console.log(statuses);
  console.log(statuses.records[0].Amount);
  this.statusunsettledamount = statuses.records[0].Amount;
  console.log(this.statusunsettledamount);
    console.log(statuses.records[0].cc);
    this.statusunsettledcc = statuses.records[0].cc;

});

this.httpClient.get<any>('url='+this.userFilter.policy_id).subscribe(statuses2 => {
  console.log(statuses2);
    console.log(statuses2.records[0].Amount);
    this.status2settledamount = statuses2.records[0].Amount;
    console.log(this.status2settledamount);
    console.log(statuses2.records[0].cc);
    this.status2settledcc = statuses2.records[0].cc;
    console.log(this.status2settledcc);
});

this.httpClient.get<any>('http://api.igiinsurance.com.pk:8888/insurance_IGItakaful/insurance-api/get_company_policy.php?company_id='+this.company_id).subscribe(policyinfo => {
  console.log(policyinfo);
  this.policynumbers = policyinfo.records;
  console.log(this.policynumbers);
});

this.url = 'url/get_claims.php?';

this.clientData = this.httpClient.get<any>(this.url,
{
params: {
policy_id: this.userFilter.policy_id
 },

}).
subscribe(data => {
console.log(data);
this.spinner.hide();

this.data1 = data.records;
this.data1.forEach(d => this.policy_id.add(d.policy_id));
console.log(this.userFilter.policy_id);

});

//const sum1 = vv.filter(item => item.status === 'settled')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum1);
//this.sum1 = sum1;

//const sum2 = vv.filter(item => item.status === 'submitted')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum2);
//this.sum2 = sum2;

//var status = 'settled';
//var status2 = 'submitted';

//var countsettled = vv.filter((obj) => obj.status === status).length;
//var countunsettled = vv.filter((obj) => obj.status === status2).length;

//console.log(countsettled);
//this.countsettled = countsettled;
//console.log(countunsettled);
//this.countunsettled = countunsettled;

}
//else{

//const sum1 = this.data1.filter(item => item.status === 'settled')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum1);
//this.sum1 = sum1;

//const sum2 = this.data1.filter(item => item.status === 'submitted')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum2);
//this.sum2 = sum2;

//var status = 'settled';
//var status2 = 'submitted';

//var countsettled = this.data1.filter((obj) => obj.status === status).length;
//var countunsettled = this.data1.filter((obj) => obj.status === status2).length;

//console.log(countsettled);
//this.countsettled = countsettled;
//console.log(countunsettled);
//this.countunsettled = countunsettled;

//}

});

}
</code>```

答:
Here is a rough sketch on how you can solve that problem. It probably won't work if you copy and paste directly, but this should nudge you in the right direction.

You can filter the data by using the ngModelChange event binding on both date inputs.

```<code><div class="col-md-3 form-group">
    <input type="date" class="form-control" (ngModelChange)="onDateSelection($event)" [(ngModel)]="from"> //From date
</div>
<div class="col-md-3 form-group">
    <input type="date" class="form-control" (ngModelChange)="onDateSelection($event)" [(ngModel)]="to"> //To Date
</div>
</code>```

And on your Component.ts, you might want to create a shallow copy of your data so that we can use that copy for filtering purposes. Then, we define the onDateSelection() method. We decode the date inputs, and convert them into the javascript Date object. Then, we filter them accordingly.

```<code>ngOnInit() {
  this.temp = [...this.data1];
}

onDateSelection() {
  if (this.from && this.to) {
    const fromDate = new Date(this.from.split(/\D/));
    const toDate = new Date(this.to.split(/\D/));
    this.data1 = this.temp.filter(obj => new Date(obj.date) > fromDate && new Date(obj.date) < toDate);
  }
}
</code>```

Title: Angular Filter by 2 dates

Body:
I need to add a Filter of the Date range. Mean I need to show only that data which user input from the date and to date. I have an array of data in which there is only one date is showing. But I want to filter it like this user input any 2 dates (From and To) And in the array I only that data show which are between input dates.

Claims Status

Claims Settled 23

Claims
(settled)

  {{statusunsettledcc}}

Claim Amount
(settled)

{{statusunsettledamount | number : fractionSize}}

Claims
(unsettled)

{{status2settledcc}}

Claim Amount
(unsettled)

{{status2settledamount | number : fractionSize}}

Claims

            Search Name

            <input type="text" class="form-control" [(ngModel)]="userFilter.member_name" placeholder="Search name" name="search">

            Search Claim No
            <input type="search"
            class="form-control" placeholder="Claim No" [(ngModel)]="userFilter.claim_no">

        <input type="date" class="form-control" [(ngModel)]="from"> //From date

        <input type="date" class="form-control" [(ngModel)]="to"> //To Date

            Company
            <select class="form-control" [(ngModel)]="userFilter.company_id" (change)="getClaims()">
              <option value='' >All</option>
              <option value="999">Airlink Communication</option>
              <option value="637">Ascertia (Pvt) Ltd</option>
              <option value="1053">Frontier Works Organization</option>
              <option value="1174">Ebryx (pvt) Ltd</option>
              <option value="274">HY Enterprises (Pvt) Limited</option>
              <option value="459">Naimat Saleem trust NST (US GROUP)</option>
              <option value="659">Samad Rubber Works (Pvt) Ltd</option>
              <option value="56">Sundry Clients</option>
              <option value="620">TIMEXPERTS (PRIVATE) Limited</option>
              <option value="39">US Apparel & Textile (Pvt) Limited</option>
              <option value="40">US Denim Mills (Pvt) Limited</option>
            </select>

            Claim Status
            <select class="form-control" [(ngModel)]="userFilter.status">
              <option value='' >All</option>

              <option value="submitted">Submitted</option>
              <option value="approved">Approved</option>
              <option value="cancel">Objection Claim</option>
              <option value="settled">Settled</option>
              <option value="rejected">Rejected</option>
              <option value="CLOSED">Closed</option>
              <option value="OUTSTANDING">Outstanding</option>

            </select>

           Policy
           <select class="form-control" [(ngModel)]="userFilter.policy_id" (change)="getClaims()" style="width: 400px" >
             <option value='' >Select Policy No</option>

             <option *ngFor="let policy of policynumbers" value="{{policy.policy_id}}">{{policy.policy_id}}</option>

           </select>

           Policy
           <select class="form-control" [(ngModel)]="userFilter.policy_id" (change)="getSamad()" style="width: 400px" >
             <option value='' >Select Policy No</option>

             <option *ngFor="let policy of policynumbers" value="{{policy.policy_id}}">{{policy.policy_id}}</option>

           </select>

          STATUS
          Name
          Patient Name
          Approved Amount
          Claimed Amount
          Company
          Submitted By
          Claim No

            Submitted
            Settled
            Rejected
            Approved
            Objection claim

              {{x.member_name}}

          {{x.patient_name}}
          {{x.approved_value}}
          {{x.claimed_value}}

            Airlink Communication
            Ascertia (Pvt) Ltd
            Frontier Works Organization
            Ebryx (pvt) Ltd
            HY Enterprises (Pvt) Limited
            Naimat Saleem trust NST (US GROUP)
            Samad Rubber Works (Pvt) Ltd
            Sundry Clients
            TIMEXPERTS (PRIVATE) Limited
            US Apparel & Textile (Pvt) Limited
            US Denim Mills (Pvt) Limited

          {{x.submitted_at || 'not-defined'}}

          {{x.claim_no}}

.ts

getClaims(){

this.policyclaim = true;

if(this.userFilter.company_id){
this.url = 'url='+this.userFilter.company_id;

this.httpClient.get<any>('url'+this.userFilter.company_id).subscribe(statuses => {
  console.log(statuses);
  console.log(statuses.records[0].Amount);
  this.statusunsettledamount = statuses.records[0].Amount;
  console.log(this.statusunsettledamount);
    console.log(statuses.records[0].cc);
    this.statusunsettledcc = statuses.records[0].cc;

});

this.httpClient.get<any>('url'+this.userFilter.company_id).subscribe(statuses2 => {
  console.log(statuses2);
    console.log(statuses2.records[0].Amount);
    this.status2settledamount = statuses2.records[0].Amount;
    console.log(this.status2settledamount);
    console.log(statuses2.records[0].cc);
    this.status2settledcc = statuses2.records[0].cc;
    console.log(this.status2settledcc);
});

this.httpClient.get<any>('url'+this.userFilter.company_id).subscribe(policyinfo => {
  console.log(policyinfo);
  this.policynumbers = policyinfo.records;
  console.log(this.policynumbers);
});

}

  if (this.from && this.to) {
    const fromDate = new Date(this.from.split(/\D/));
    const toDate = new Date(this.to.split(/\D/));
    this.data1.filter(obj => new Date(obj.date) > fromDate && new Date(obj.date) < toDate);
    console.log(this.data1);
  }

else
{
this.url = 'url/get_claims.php?offset=0&limit=50';

this.httpClient.get<any>('http://api.igiinsurance.com.pk:8888/insurance_IGItakaful/insurance-api/get_claims_amt.php?cstatus=OUTSTANDING').subscribe(statuses => {
  console.log(statuses);
  console.log(statuses.records[0].Amount);
  this.statusunsettledamount = statuses.records[0].Amount;
  console.log(this.statusunsettledamount);
    console.log(statuses.records[0].cc);
    this.statusunsettledcc = statuses.records[0].cc;

});

this.httpClient.get<any>('url/get_claims_amt.php?cstatus=CLOSED').subscribe(statuses2 => {
  console.log(statuses2);
    console.log(statuses2.records[0].Amount);
    this.status2settledamount = statuses2.records[0].Amount;
    console.log(this.status2settledamount);
    console.log(statuses2.records[0].cc);
    this.status2settledcc = statuses2.records[0].cc;
    console.log(this.status2settledcc);
});

this.httpClient.get<any>('url/insurance-api/get_company_policy.php?').subscribe(policyinfo => {
  console.log(policyinfo);
  this.policynumbers = policyinfo.records;
  console.log(this.policynumbers);
});

}

this.clientData = this.httpClient.get<any>(this.url).
subscribe(data => {
console.log(data);
this.spinner.hide();

this.data1 = data.records;
this.data1.forEach(d => this.policy_id.add(d.policy_id));
console.log(this.userFilter.policy_id);

if(this.userFilter.policy_id){

let vv = this.data1.filter(v => v.policy_id === this.userFilter.policy_id);
console.log(vv);

this.httpClient.get<any>('http://url='+this.userFilter.policy_id).subscribe(statuses => {
  console.log(statuses);
  console.log(statuses.records[0].Amount);
  this.statusunsettledamount = statuses.records[0].Amount;
  console.log(this.statusunsettledamount);
    console.log(statuses.records[0].cc);
    this.statusunsettledcc = statuses.records[0].cc;

});

this.httpClient.get<any>('url='+this.userFilter.policy_id).subscribe(statuses2 => {
  console.log(statuses2);
    console.log(statuses2.records[0].Amount);
    this.status2settledamount = statuses2.records[0].Amount;
    console.log(this.status2settledamount);
    console.log(statuses2.records[0].cc);
    this.status2settledcc = statuses2.records[0].cc;
    console.log(this.status2settledcc);
});

this.httpClient.get<any>('http://api.igiinsurance.com.pk:8888/insurance_IGItakaful/insurance-api/get_company_policy.php?company_id='+this.company_id).subscribe(policyinfo => {
  console.log(policyinfo);
  this.policynumbers = policyinfo.records;
  console.log(this.policynumbers);
});

this.url = 'url/get_claims.php?';

this.clientData = this.httpClient.get<any>(this.url,
{
params: {
policy_id: this.userFilter.policy_id
 },

}).
subscribe(data => {
console.log(data);
this.spinner.hide();

this.data1 = data.records;
this.data1.forEach(d => this.policy_id.add(d.policy_id));
console.log(this.userFilter.policy_id);

});

//const sum1 = vv.filter(item => item.status === 'settled')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum1);
//this.sum1 = sum1;

//const sum2 = vv.filter(item => item.status === 'submitted')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum2);
//this.sum2 = sum2;

//var status = 'settled';
//var status2 = 'submitted';

//var countsettled = vv.filter((obj) => obj.status === status).length;
//var countunsettled = vv.filter((obj) => obj.status === status2).length;

//console.log(countsettled);
//this.countsettled = countsettled;
//console.log(countunsettled);
//this.countunsettled = countunsettled;

}
//else{

//const sum1 = this.data1.filter(item => item.status === 'settled')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum1);
//this.sum1 = sum1;

//const sum2 = this.data1.filter(item => item.status === 'submitted')
//.reduce((acc, item) => acc + Number(item.approved_value), 0);
//console.log(sum2);
//this.sum2 = sum2;

//var status = 'settled';
//var status2 = 'submitted';

//var countsettled = this.data1.filter((obj) => obj.status === status).length;
//var countunsettled = this.data1.filter((obj) => obj.status === status2).length;

//console.log(countsettled);
//this.countsettled = countsettled;
//console.log(countunsettled);
//this.countunsettled = countunsettled;

//}

});

}

Body:
Here is a rough sketch on how you can solve that problem. It probably won't work if you copy and paste directly, but this should nudge you in the right direction.

You can filter the data by using the ngModelChange event binding on both date inputs.

<div class="col-md-3 form-group">
    <input type="date" class="form-control" (ngModelChange)="onDateSelection($event)" [(ngModel)]="from"> //From date
</div>
<div class="col-md-3 form-group">
    <input type="date" class="form-control" (ngModelChange)="onDateSelection($event)" [(ngModel)]="to"> //To Date
</div>

And on your Component.ts, you might want to create a shallow copy of your data so that we can use that copy for filtering purposes. Then, we define the onDateSelection() method. We decode the date inputs, and convert them into the javascript Date object. Then, we filter them accordingly.

ngOnInit() {
  this.temp = [...this.data1];
}

onDateSelection() {
  if (this.from && this.to) {
    const fromDate = new Date(this.from.split(/\D/));
    const toDate = new Date(this.to.split(/\D/));
    this.data1 = this.temp.filter(obj => new Date(obj.date) > fromDate && new Date(obj.date) < toDate);
  }
}


问:
Get Public IP Address on current EC2 Instance
Using Amazon CLI, is there a way to get the public ip address of the current EC2?  I'm just looking for the single string value, so not the json response describe-addresses returns.  </p>

答:
Get attached InstanceID with PublicIP.</p>

```<code>aws ec2 describe-network-interfaces --query NetworkInterfaces[*].[Attachment.[InstanceId],Association.[PublicIp]] --output=json
</code>```

Body:
Get attached InstanceID with PublicIP.

aws ec2 describe-network-interfaces --query NetworkInterfaces[*].[Attachment.[InstanceId],Association.[PublicIp]] --output=json


问:
Rails Association Has_One Having Pluralisation Model Name Instead of Singular and not working
I have a model called as BigbluebuttonRoom.

```<code>class BigbluebuttonRoom < ActiveRecord::Base
has_one :room_options, :class_name => 'BigbluebuttonRoomOptions'
</code>```

So when I am calling room.room_options then getting no method error.

答:
Why you named your model BigbluebuttonRoomOptions in plural form? It's a bad idea to break rails conventions. Model name should be in singular form, BigbluebuttonRoomOption. Change it and a corresponding file name.

Also, convention for has_one is singular form too. Should be:

```<code>has_one :room_option, :class_name => 'BigbluebuttonRoomOption'
</code>```

Body:
I have a model called as BigbluebuttonRoom.

class BigbluebuttonRoom < ActiveRecord::Base
has_one :room_options, :class_name => 'BigbluebuttonRoomOptions'

So when I am calling room.room_options then getting no method error.

Body:
Why you named your model BigbluebuttonRoomOptions in plural form? It's a bad idea to break rails conventions. Model name should be in singular form, BigbluebuttonRoomOption. Change it and a corresponding file name.

Also, convention for has_one is singular form too. Should be:

has_one :room_option, :class_name => 'BigbluebuttonRoomOption'