问:
Parallel task execution at different time
I have console app which performs a couple of tasks in parallel. In my case the important part is that i want the tasks to complete at the same time. I know how long each task is going to take. So the idea is to delay somehow every task in the Parallel.ForEach with custom time delay per task so they all finish at the same time and in the end all the tasks will complete approximately at the same time as the one which takes most time.

Example:

```<code>interface IService
{
    void DoWork();
}

class Program
{
    static void Main(string[] args)
    {
        var services = new List<IService>();
        services.Add(new ServiceA());//Takes 500ms to DoWork()
        services.Add(new ServiceB());//Takes 1000ms to DoWork()
        services.Add(new ServiceC());//Takes 5000ms to DoWork()

        Parallel.ForEach(services, z =>
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            z.DoWork();
            Console.WriteLine($"Ready for {sw.Elapsed}");
        });
    }
}
</code>```

Output:

```<code>Ready for 00:00:00.5006837
Ready for 00:00:01.0002284
Ready for 00:00:05.0010202
Press any key to continue . . .
</code>```

How to modify the code so the output will look like:

```<code>Ready for 00:00:05.5006837
Ready for 00:00:05.0002284
Ready for 00:00:05.0010202
Press any key to continue . . .
</code>```

I guess the most obvious solution would be to distinguish which Service is z in the loop and add custom Thread.Sleep before calling z.DoWork(), but I am looking for smarter solution.

答:
Thanks for the help!  So this is what i wanted to achieve. All the services finish their job at the same time. Is this the right way of doing it?

```<code>class Program
{
    static void Main(string[] args)
    {
        ServiceA a = new ServiceA();
        ServiceB b = new ServiceB();
        ServiceC c = new ServiceC();

        int maxDelay = 3000;
        var sw = new Stopwatch();
        sw.Start();

        Task taskA = Task.Delay(maxDelay - a.ResponseTime).ContinueWith(x =>
          {
              a.DoWork();
              Console.WriteLine($"taskA ready for {sw.Elapsed}");
          });

        Task taskB = Task.Delay(maxDelay - b.ResponseTime).ContinueWith(x =>
          {
              b.DoWork();
              Console.WriteLine($"taskB ready for {sw.Elapsed}");
          });

        Task taskC = Task.Delay(maxDelay - c.ResponseTime).ContinueWith(x =>
        {
            c.DoWork();
            Console.WriteLine($"taskC ready for {sw.Elapsed}");
        });

        taskA.Wait();
        taskB.Wait();
        taskC.Wait();

        Console.WriteLine(sw.Elapsed);
    }
}

class ServiceA
{
    public int ResponseTime { get => 500; }
    public void DoWork() => Thread.Sleep(500);
}

class ServiceB
{
    public int ResponseTime { get => 1000; }
    public void DoWork() => Thread.Sleep(1000);
}

class ServiceC
{
    public int ResponseTime { get => 3000; }
    public void DoWork() => Thread.Sleep(3000);
}
</code>```

Output:

```<code>taskA ready for 00:00:03.0084344
taskC ready for 00:00:03.0102184
taskB ready for 00:00:03.0102588
</code>```

*Thread.Sleep(x) represents some time consuming operations.

Body:
I have console app which performs a couple of tasks in parallel. In my case the important part is that i want the tasks to complete at the same time. I know how long each task is going to take. So the idea is to delay somehow every task in the Parallel.ForEach with custom time delay per task so they all finish at the same time and in the end all the tasks will complete approximately at the same time as the one which takes most time.

Example:

interface IService
{
    void DoWork();
}

class Program
{
    static void Main(string[] args)
    {
        var services = new List<IService>();
        services.Add(new ServiceA());//Takes 500ms to DoWork()
        services.Add(new ServiceB());//Takes 1000ms to DoWork()
        services.Add(new ServiceC());//Takes 5000ms to DoWork()

        Parallel.ForEach(services, z =>
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            z.DoWork();
            Console.WriteLine($"Ready for {sw.Elapsed}");
        });
    }
}

Output:

Ready for 00:00:00.5006837
Ready for 00:00:01.0002284
Ready for 00:00:05.0010202
Press any key to continue . . .

How to modify the code so the output will look like:

Ready for 00:00:05.5006837
Ready for 00:00:05.0002284
Ready for 00:00:05.0010202
Press any key to continue . . .

I guess the most obvious solution would be to distinguish which Service is z in the loop and add custom Thread.Sleep before calling z.DoWork(), but I am looking for smarter solution.

Body:
Thanks for the help!  So this is what i wanted to achieve. All the services finish their job at the same time. Is this the right way of doing it?

class Program
{
    static void Main(string[] args)
    {
        ServiceA a = new ServiceA();
        ServiceB b = new ServiceB();
        ServiceC c = new ServiceC();

        int maxDelay = 3000;
        var sw = new Stopwatch();
        sw.Start();

        Task taskA = Task.Delay(maxDelay - a.ResponseTime).ContinueWith(x =>
          {
              a.DoWork();
              Console.WriteLine($"taskA ready for {sw.Elapsed}");
          });

        Task taskB = Task.Delay(maxDelay - b.ResponseTime).ContinueWith(x =>
          {
              b.DoWork();
              Console.WriteLine($"taskB ready for {sw.Elapsed}");
          });

        Task taskC = Task.Delay(maxDelay - c.ResponseTime).ContinueWith(x =>
        {
            c.DoWork();
            Console.WriteLine($"taskC ready for {sw.Elapsed}");
        });

        taskA.Wait();
        taskB.Wait();
        taskC.Wait();

        Console.WriteLine(sw.Elapsed);
    }
}

class ServiceA
{
    public int ResponseTime { get => 500; }
    public void DoWork() => Thread.Sleep(500);
}

class ServiceB
{
    public int ResponseTime { get => 1000; }
    public void DoWork() => Thread.Sleep(1000);
}

class ServiceC
{
    public int ResponseTime { get => 3000; }
    public void DoWork() => Thread.Sleep(3000);
}

Output:

taskA ready for 00:00:03.0084344
taskC ready for 00:00:03.0102184
taskB ready for 00:00:03.0102588

*Thread.Sleep(x) represents some time consuming operations.


来源: stackexchange

问:
UMBRACO: How to add image on template
So, I'm currently new to Umbraco and I'm following some tutorial videos on umbraco.tv. I have created my template and is currently using it to setup the Home Page for my website. I have all the front end working and its displaying properly.

My problem is on the images. I'm using a lot of images for my website and I'm trying to link it to content so the images can be easily changed(not sure if I'm making sense).

Navigation bar image

If you click the link above, that's how my current navigation bar look like. I want to be able to change the LOGO using Umbraco's media picker. However, everytime I do so, it either gives me the alt name or a runtime error.

This is the code for the image on the template.

```<code><img src="@Umbraco.Field("navigationLogo")" height="100" width="50" alt="Logo">
</code>```

I'd appreciate it if you can help me. I'm not sure if I've explained it properly so feel free to ask in detail. Thanks!

Edit -----

I am only coding on browser since it doesn't allow me to login to pull the codes locally (only on trial version since I'm just testing out if its a good CMS).

Not sure if I'm doing it correctly so I apologize. I wrote my code like this

```<code>@{
   var navigationLogo = @Umbraco.AssignedContent.Site().GetPropertyValue("navigationLogo");
   var navigationLogoMediaItem = @Umbraco.TypedMedia(navigationLogo);

   <img src="@navigationLogoMediaItem.Url" height="100" width="50" alt="Logo" />
 }
</code>```

It's giving me the following error so far.

Compiler Error Message: CS1061: 'Umbraco.Web.UmbracoHelper' does not contain a definition for 'AssignedContent' and no extension method 'AssignedContent' accepting a first argument of type 'Umbraco.Web.UmbracoHelper' could be found (are you missing a using directive or an assembly reference?

答:
I'm going to make a few assumptions so please bear with me here.

Assumption 1) On your home node (assuming a document type of 'home") you have a property on it called "navigationLogo".
Assumption 2) This is a media picker data type
Assumption 3) You are using Umbraco 7.6 or newer.
Assumption 4) You aren't using Models Builder

So, assumptions in place there are a few steps you need to go through.

1) Get the navigation logo where ever you are in the site.

```<code>var navigationLogo = @Umbraco.AssignedContent.Site().GetPropertyValue("navigationLogo");
</code>```

2) next, you'll need to get the media item as I belive you will only have a UDI at this stage.

```<code>var navigationLogoMediaItem = @Umbraco.TypedMedia(navigationLogo);
</code>```

3) You'll want to put a null check in at this point but to get the url of the logo you simple need to do this:

```<code><img src="@navigationLogoMediaItem.Url" height="100" width="50" alt="Logo" />
</code>```

That should get you what you are after. :-)

ContentLicense: CC BY-SA 3.0

Title: UMBRACO: How to add image on template

Body:
So, I'm currently new to Umbraco and I'm following some tutorial videos on umbraco.tv. I have created my template and is currently using it to setup the Home Page for my website. I have all the front end working and its displaying properly.

My problem is on the images. I'm using a lot of images for my website and I'm trying to link it to content so the images can be easily changed(not sure if I'm making sense).

Navigation bar image

If you click the link above, that's how my current navigation bar look like. I want to be able to change the LOGO using Umbraco's media picker. However, everytime I do so, it either gives me the alt name or a runtime error.

This is the code for the image on the template.

I'd appreciate it if you can help me. I'm not sure if I've explained it properly so feel free to ask in detail. Thanks!

Edit -----

I am only coding on browser since it doesn't allow me to login to pull the codes locally (only on trial version since I'm just testing out if its a good CMS).

Not sure if I'm doing it correctly so I apologize. I wrote my code like this

@{
   var navigationLogo = @Umbraco.AssignedContent.Site().GetPropertyValue("navigationLogo");
   var navigationLogoMediaItem = @Umbraco.TypedMedia(navigationLogo);

 }

It's giving me the following error so far.

Compiler Error Message: CS1061: 'Umbraco.Web.UmbracoHelper' does not contain a definition for 'AssignedContent' and no extension method 'AssignedContent' accepting a first argument of type 'Umbraco.Web.UmbracoHelper' could be found (are you missing a using directive or an assembly reference?

Body:
I'm going to make a few assumptions so please bear with me here.

Assumption 1) On your home node (assuming a document type of 'home") you have a property on it called "navigationLogo".
Assumption 2) This is a media picker data type
Assumption 3) You are using Umbraco 7.6 or newer.
Assumption 4) You aren't using Models Builder

So, assumptions in place there are a few steps you need to go through.

1) Get the navigation logo where ever you are in the site.

var navigationLogo = @Umbraco.AssignedContent.Site().GetPropertyValue("navigationLogo");

2) next, you'll need to get the media item as I belive you will only have a UDI at this stage.

var navigationLogoMediaItem = @Umbraco.TypedMedia(navigationLogo);

3) You'll want to put a null check in at this point but to get the url of the logo you simple need to do this:

<img src="@navigationLogoMediaItem.Url" height="100" width="50" alt="Logo" />

That should get you what you are after. :-)


问:
OSGi Compendium (R6) Annotations + Felix SCR 2.0.0 + Karaf 3.0.6
I'm changing my code from Felix SCR annotations to OSGi Compendium R6.

When I want to start my Karaf container, my bundle needs the capability osgi.extender to start correctly.
I could see this is provided by org.apache.felix.scr >= 2.0.0 (https://mvnrepository.com/artifact/org.apache.felix/org.apache.felix.scr)

Now the problem:
I have the version 1.8.4 of org.apache.felix.scr in my Karaf container (this is a MUST as some bundle has a filter to this version), when I try to put the two versions, my container NEVER CAME UP.

How can I debug this kind of behaviour ? can I get the osgi.extender capability from another place ?

答:
Have you tried updating your Karaf to version 4.1.x ?

Here, you can see that this version of Karaf already provides support to Felix SCR 2.0.6.


问:
Rails - Using true and false
I have the following in my controller:

```<code>if params[:archive] == 'true'
  @archived_new_status = true
else
  @archived_new_status = false
end
</code>```

Then later in create.je.erb do:

```<code><% if !@archived_new_status.nil? %>
   xxx.myfuncthatNeedsTrueOrFalse(<%=@archived_new_status%>);
<% end %>
</code>```

That only works when @archived_new_status is true, when it's false that seems to not be getting set as false. When I do a Rails.logger.info on @archived_new_status for false it outputs nothing, if I inspect it, I get false.

Any thoughts?

答:
The code in the controller can be written:

```<code>@archive_new_status = (params[:archive] == 'true')
</code>```

View: I don't understand why you check if the variable is nil; @archive_new_status is either true or false, so simply call the JS code (using to_json for any argument you have):

```<code>xxx.myfuncthatNeedsTrueOrFalse(<%= @archived_new_status.to_json %>);
</code>```

ContentLicense: CC BY-SA 2.5

Title: Rails - Using true and false

Body:
I have the following in my controller:

if params[:archive] == 'true'
  @archived_new_status = true
else
  @archived_new_status = false
end

Then later in create.je.erb do:

<% if !@archived_new_status.nil? %>
   xxx.myfuncthatNeedsTrueOrFalse(<%=@archived_new_status%>);
<% end %>

That only works when @archived_new_status is true, when it's false that seems to not be getting set as false. When I do a Rails.logger.info on @archived_new_status for false it outputs nothing, if I inspect it, I get false.

Any thoughts?

Body:
The code in the controller can be written:

@archive_new_status = (params[:archive] == 'true')

View: I don't understand why you check if the variable is nil; @archive_new_status is either true or false, so simply call the JS code (using to_json for any argument you have):

xxx.myfuncthatNeedsTrueOrFalse(<%= @archived_new_status.to_json %>);


问:
Flask SQLAlchemy sum function comparison
I have table that is holding some data about users. There are two fields there like and smile. I need to get data from table, grouped by user_id that will show if user has likes or smiles. Query that I would write in SQL looks like:

```<code>select sum(smile) > 0 as has_smile,
       sum(like) > 0 as has_like,
       user_id
from ratings
group by user_id.
</code>```

This would provide output like:

```<code>| has_smile | has_like | user_id |
+-----------+----------+---------+
|         1 |        0 |       1 |
|         1 |        1 |       2 |
</code>```

Is there any chance this query can be translated to SQLAlchemy (Flask-SQLAlchemy to be precise)? I know there is db.func.sum but I don't know how to add comparison there, and to have label. What I did for now is:

```<code>cls.query.with_entities("user_id").group_by(user_id).\
    add_columns(db.func.sum(cls.smile).label("has_smile"),
                db.func.sum(cls.like).label("has_like")).all()
</code>```

but that will return exact number of smiles/likes instead of just 1/0 if there is or there is not smile/like.

答:
Thanks to operator overloading you'd do comparison the way you're used to doing in Python in general:

```<code>db.func.sum(cls.smile) > 0
</code>```

which produces an SQL expression object that you can then give a label to:

```<code>(db.func.sum(cls.smile) > 0).label('has_smile')
</code>```

Body:
I have table that is holding some data about users. There are two fields there like and smile. I need to get data from table, grouped by user_id that will show if user has likes or smiles. Query that I would write in SQL looks like:

select sum(smile) > 0 as has_smile,
       sum(like) > 0 as has_like,
       user_id
from ratings
group by user_id.

This would provide output like:

| has_smile | has_like | user_id |
+-----------+----------+---------+
|         1 |        0 |       1 |
|         1 |        1 |       2 |

Is there any chance this query can be translated to SQLAlchemy (Flask-SQLAlchemy to be precise)? I know there is db.func.sum but I don't know how to add comparison there, and to have label. What I did for now is:

cls.query.with_entities("user_id").group_by(user_id).\
    add_columns(db.func.sum(cls.smile).label("has_smile"),
                db.func.sum(cls.like).label("has_like")).all()

but that will return exact number of smiles/likes instead of just 1/0 if there is or there is not smile/like.

Body:
Thanks to operator overloading you'd do comparison the way you're used to doing in Python in general:

db.func.sum(cls.smile) > 0

which produces an SQL expression object that you can then give a label to:

(db.func.sum(cls.smile) > 0).label('has_smile')


问:
How generate width html element to fill rest of width window
I would ask how i can set css to set width of element to fill rest of width window screen  without using unit of measure (px, pt, et).

for example i have two div

```<code><div id="div1"></div>
<div id="div2"></div>
</code>```

some css

```<code>#div1{
   width:200px;
   height: 40px;
   float: left;
   border: 1px solid black;
}
#div2{
  width: // here what i should set to get rest of window screen until 100%,
         // depending on resolution. When i try set param auto this param
         // work that resize my div when i put something into, but i except
         // at start already set rest of window width. It is possible to set
         // this value without using javascript only in CSS??
  height: 40px;
  float: left;
  border: 1px solid black;
}
</code>```

答:
You could also just use flexbox to achieve your goal.

HTML:

```<code><div class="wrapper background">
  <img src="images/ant.png" class=logo>
  <div class=leftbox>
    <h1>Ant Arni</h1>
  </div>
  <div class=rightbox>
    <table>
      <tr>
        <td><a href=#>Link 1</a></td>
        <td><a href=#>Link 4</a></td>
      </tr>
      <tr>
        <td><a href=#>Link 2</a></td>
        <td><a href=#>Link 5</a></td>
      </tr>
      <tr>
        <td><a href=#>Link 3</a></td>
        <td><a href=#>Link 6</a></td>
      </tr>
    </table>
  </div>
</div>
</code>```

And CSS:

```<code>.wrapper {
    display: flex;
}
.leftbox {
    background: red;
    width: 200px;
}
.rightbox {
    background: yellow;
    flex: 1;
}
</code>```

fiddle

"flex: 1" means, you're changing the flex-grow property of the item. You can read about it here.

Body:
I would ask how i can set css to set width of element to fill rest of width window screen  without using unit of measure (px, pt, et).

for example i have two div

some css

#div1{
   width:200px;
   height: 40px;
   float: left;
   border: 1px solid black;
}
#div2{
  width: // here what i should set to get rest of window screen until 100%,
         // depending on resolution. When i try set param auto this param
         // work that resize my div when i put something into, but i except
         // at start already set rest of window width. It is possible to set
         // this value without using javascript only in CSS??
  height: 40px;
  float: left;
  border: 1px solid black;
}

Body:
You could also just use flexbox to achieve your goal.

HTML:

<div class="wrapper background">
  <img src="images/ant.png" class=logo>
  <div class=leftbox>
    <h1>Ant Arni</h1>
  </div>
  <div class=rightbox>
    <table>
      <tr>
        <td><a href=#>Link 1</a></td>
        <td><a href=#>Link 4</a></td>
      </tr>
      <tr>
        <td><a href=#>Link 2</a></td>
        <td><a href=#>Link 5</a></td>
      </tr>
      <tr>
        <td><a href=#>Link 3</a></td>
        <td><a href=#>Link 6</a></td>
      </tr>
    </table>
  </div>
</div>

And CSS:

.wrapper {
    display: flex;
}
.leftbox {
    background: red;
    width: 200px;
}
.rightbox {
    background: yellow;
    flex: 1;
}

fiddle

"flex: 1" means, you're changing the flex-grow property of the item. You can read about it here.


问:
Send number from NumberPicker to Firebase
Is there a way to send Number from NumberPicker to Firebase? I have connected a NumberPicker library from GITHUB. But I want when select number to send to Firebase, is there a way ?

I tried with this code :

```<code> String number = numberPicker.getText().toString().trim();
</code>```

Code for Firebase:

```<code>private boolean updateProdus(String id, String number){

    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("produse").child(id);

    Produse produse = new Produse(id, number);

    databaseReference.setValue(produse);
    Toast.makeText(this, "Edited", Toast.LENGTH_LONG).show();
    return true;
}
</code>```

But it's not working.

答:
```<code>private boolean updateProdus(String id, String number){

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("produse").push();

databaseReference.child("number").setValue(number);
Toast.makeText(this, "Edited", Toast.LENGTH_LONG).show();
return true;
}
</code>```

Use push() to create a random id, then inside of it there will be a child that has the value number.

check this: https://developer.android.com/reference/android/widget/NumberPicker.html

you can get the number doing this:

```<code>String number=""+numberpicker.getValue();
</code>```

Body:
Is there a way to send Number from NumberPicker to Firebase? I have connected a NumberPicker library from GITHUB. But I want when select number to send to Firebase, is there a way ?

I tried with this code :

 String number = numberPicker.getText().toString().trim();

Code for Firebase:

private boolean updateProdus(String id, String number){

    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("produse").child(id);

    Produse produse = new Produse(id, number);

    databaseReference.setValue(produse);
    Toast.makeText(this, "Edited", Toast.LENGTH_LONG).show();
    return true;
}

But it's not working.

Body:
private boolean updateProdus(String id, String number){

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("produse").push();

databaseReference.child("number").setValue(number);
Toast.makeText(this, "Edited", Toast.LENGTH_LONG).show();
return true;
}

Use push() to create a random id, then inside of it there will be a child that has the value number.

check this: https://developer.android.com/reference/android/widget/NumberPicker.html

you can get the number doing this:

String number=""+numberpicker.getValue();


答:
As the error message states, the method used to get the F score is from the "Classification" part of sklearn - thus the talking about "labels".

Do you have a regression problem? Sklearn provides a "F score" method for regression under the "feature selection" group: http://scikit-learn.org/stable/modules/generated/sklearn.feature_selection.f_regression.html

In case you do have a classification problem, @Shovalt's answer seems correct to me.

ContentLicense: CC BY-SA 4.0

Body:
I'm getting this weird error:

classification.py:1113: UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples.
'precision', 'predicted', average, warn_for)`

but then it also prints the f-score the first time I run:

metrics.f1_score(y_test, y_pred, average='weighted')

The second time I run, it provides the score without error. Why is that?

>>> y_pred = test.predict(X_test)
>>> y_test
array([ 1, 10, 35,  9,  7, 29, 26,  3,  8, 23, 39, 11, 20,  2,  5, 23, 28,
       30, 32, 18,  5, 34,  4, 25, 12, 24, 13, 21, 38, 19, 33, 33, 16, 20,
       18, 27, 39, 20, 37, 17, 31, 29, 36,  7,  6, 24, 37, 22, 30,  0, 22,
       11, 35, 30, 31, 14, 32, 21, 34, 38,  5, 11, 10,  6,  1, 14, 12, 36,
       25,  8, 30,  3, 12,  7,  4, 10, 15, 12, 34, 25, 26, 29, 14, 37, 23,
       12, 19, 19,  3,  2, 31, 30, 11,  2, 24, 19, 27, 22, 13,  6, 18, 20,
        6, 34, 33,  2, 37, 17, 30, 24,  2, 36,  9, 36, 19, 33, 35,  0,  4,
        1])
>>> y_pred
array([ 1, 10, 35,  7,  7, 29, 26,  3,  8, 23, 39, 11, 20,  4,  5, 23, 28,
       30, 32, 18,  5, 39,  4, 25,  0, 24, 13, 21, 38, 19, 33, 33, 16, 20,
       18, 27, 39, 20, 37, 17, 31, 29, 36,  7,  6, 24, 37, 22, 30,  0, 22,
       11, 35, 30, 31, 14, 32, 21, 34, 38,  5, 11, 10,  6,  1, 14, 30, 36,
       25,  8, 30,  3, 12,  7,  4, 10, 15, 12,  4, 22, 26, 29, 14, 37, 23,
       12, 19, 19,  3, 25, 31, 30, 11, 25, 24, 19, 27, 22, 13,  6, 18, 20,
        6, 39, 33,  9, 37, 17, 30, 24,  9, 36, 39, 36, 19, 33, 35,  0,  4,
        1])
>>> metrics.f1_score(y_test, y_pred, average='weighted')
C:\Users\Michael\Miniconda3\envs\snowflakes\lib\site-packages\sklearn\metrics\classification.py:1113: UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples.
  'precision', 'predicted', average, warn_for)
0.87282051282051276
>>> metrics.f1_score(y_test, y_pred, average='weighted')
0.87282051282051276
>>> metrics.f1_score(y_test, y_pred, average='weighted')
0.87282051282051276

Also, why is there a trailing 'precision', 'predicted', average, warn_for) error message? There is no open parenthesis so why does it end with a closing parenthesis? I am running sklearn 0.18.1 using Python 3.6.0 in a conda environment on Windows 10.

I also looked at here and I don't know if it's the same bug. This SO post doesn't have solution either.


问:
Connector/J depends on libmysqlclient.so?
I wanna research mysql-connector-java depends on .so files

Do you know that mysql-connector is pure java?

答: MySQL Connector/J is pure Java driver. It does not require libmysqlclient.</p>


问:
iPhone X keyboard appear showing extra space
I have created a chat UI in which I have added a constraint for the tableView to the bottom of the screen. I am changing the constraint value by adding the height of the keyboard which is working fine in all the devices except iPhone X.

UI when key board is not visible:

Which is fine.

Problem is when keyboard appears blank space is visible in between the textView and the keyboard:

Do I have to try for a different approach for this or it can be resolved using constraints ?

答:
Make an outlet to your constraint to your ViewController. I'll refer to it as yourConstraint for now. Then add code to discover when the keyboard is being shown and when it is being dismissed. There you change the constant of the constraint accordingly. This allows you to keep using constraints.

In viewWillAppear:

```<code>NotificationCenter.default.addObserver(self, selector: #selector(YourViewController.keyboardWillShow), name:        NSNotification.Name.UIKeyboardWillShow, object: nil) // <=== Replace YourViewController with name of your view controller
NotificationCenter.default.addObserver(self, selector: #selector(YourViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) // <=== Replace YourViewController with name of your view controller
</code>```

In viewWillDisappear:

```<code>NotificationCenter.default.removeObserver(self)
</code>```

In your UIViewController

```<code>@objc private func keyboardWillShow(notification: Notification) {
    guard let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
        yourConstraint.isActive = false // <===
        view.layoutIfNeeded()
        return
    }
    let duration: TimeInterval = ((notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue) ?? 0.4
    yourConstraint.constant = newValue // <===
    UIView.animate(withDuration: duration) {
        self.view.layoutIfNeeded()
    }
}

@objc private func keyboardWillHide(notification: Notification) {
    let duration: TimeInterval = ((notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue) ?? 0.4
    yourConstraint.constant = oldValue
    UIView.animate(withDuration: duration) {
        self.view.layoutIfNeeded()
    }
}
</code>```

The UIView.animate is not necessary (the inside of the block is), but it makes the transition look nice.

Body:
Make an outlet to your constraint to your ViewController. I'll refer to it as yourConstraint for now. Then add code to discover when the keyboard is being shown and when it is being dismissed. There you change the constant of the constraint accordingly. This allows you to keep using constraints.

In viewWillAppear:

NotificationCenter.default.addObserver(self, selector: #selector(YourViewController.keyboardWillShow), name:        NSNotification.Name.UIKeyboardWillShow, object: nil) // <=== Replace YourViewController with name of your view controller
NotificationCenter.default.addObserver(self, selector: #selector(YourViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) // <=== Replace YourViewController with name of your view controller

In viewWillDisappear:

NotificationCenter.default.removeObserver(self)

In your UIViewController

@objc private func keyboardWillShow(notification: Notification) {
    guard let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
        yourConstraint.isActive = false // <===
        view.layoutIfNeeded()
        return
    }
    let duration: TimeInterval = ((notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue) ?? 0.4
    yourConstraint.constant = newValue // <===
    UIView.animate(withDuration: duration) {
        self.view.layoutIfNeeded()
    }
}

@objc private func keyboardWillHide(notification: Notification) {
    let duration: TimeInterval = ((notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue) ?? 0.4
    yourConstraint.constant = oldValue
    UIView.animate(withDuration: duration) {
        self.view.layoutIfNeeded()
    }
}

The UIView.animate is not necessary (the inside of the block is), but it makes the transition look nice.


问:
How To Set NULL is 0 in SQL Dynamic Pivot Query
I developed one dynamic pivot table, and I set  ISNULL = 0.00.
The query is given below

```<code>SELECT DISTINCT hdr.EmpNo,hdr.FirstName AS Name,
                ISNULL(TBL.shortname,'')AS shortname,
                ISNULL(TBL.Amount,0.00) AS Amount,
                TBL.Adtype INTO #Temp FROM  tbl1 AS hdr
LEFT JOIN tbl2 TBL  ON TBL.EmpNo = hdr.EmpNo
DECLARE @Ded AS NVARCHAR(MAX)
SET @Ded = STUFF((SELECT ', ISNULL( ' + QUOTENAME(c.shortname) + ', 0.00 )AS ' +
            QUOTENAME(c.shortname)  FROM (SELECT DISTINCT shortname FROM #Temp
            WHERE ISNULL(shortname,'') <> '' AND Adtype = 2) AS c ORDER BY
            shortname  FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)')
            ,1,1,'')
SET @Query = 'SELECT CAST(ROW_NUMBER() OVER(ORDER BY EmpNo ASC) AS
              VARCHAR(100)) AS [S.No],EmpNo,Name,' + @Ded +' FROM  #Temp
              PIVOT(SUM(Amount)  FOR shortname IN (' + @Ded + ')) AS PVTTable'
EXEC sp_executesql @Query
</code>```

But it displays the following error, and line 3 doesn't not have a "(".

Msg 102, Level 15, State 1, Line 3
                     Incorrect syntax near '('.

Any help to solve this problem would be appreciated.

答:
Problem is with @der variable use in in clause.
you are setting column name with isnull and in in clause, it is not supported.

Please try below query.

```<code>;with tbl1 as
(
select 1 EmpNo,'Emp1' FirstName
union all
select 2 EmpNo,'Emp2' FirstName
),
tbl2 as
(
select 'EMP1' shortname,100 Amount, 2 Adtype,1 EmpNo
union all
select 'EMP2' shortname,100 Amount, 2 Adtype,2 EmpNo
)

SELECT DISTINCT hdr.EmpNo,hdr.FirstName AS Name,
                ISNULL(TBL.shortname,'')AS shortname,
                ISNULL(TBL.Amount,0.00) AS Amount,
                TBL.Adtype INTO #Temp FROM  tbl1 AS hdr
LEFT JOIN tbl2 TBL  ON TBL.EmpNo = hdr.EmpNo

DECLARE @Ded AS NVARCHAR(MAX)='' ,@Query AS NVARCHAR(MAX)=''
DECLARE @Wer AS NVARCHAR(MAX)=''
SET @Ded = STUFF((SELECT ', ISNULL( ' +  QUOTENAME(c.shortname) + ', 0.00 )AS ' +
            QUOTENAME(c.shortname)  FROM (SELECT DISTINCT shortname FROM #Temp
            WHERE ISNULL(shortname,'') <> '' AND Adtype = 2) AS c ORDER BY
            shortname  FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)')
            ,1,1,'')

SET @Wer = STUFF((SELECT ',  ' +  QUOTENAME(c.shortname)  FROM (SELECT DISTINCT shortname FROM #Temp
            WHERE ISNULL(shortname,'') <> '' AND Adtype = 2) AS c ORDER BY
            shortname  FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)')
            ,1,1,'')

SET @Query = 'SELECT CAST(ROW_NUMBER() OVER(ORDER BY EmpNo ASC) AS
              VARCHAR(100)) AS [S.No],EmpNo,Name,' + @Ded +' FROM  #Temp
              PIVOT(SUM(Amount)  FOR shortname IN (' + @Wer + ')) AS PVTTable'
--print @Query

EXEC sp_executesql @Query
</code>```

Body:
I developed one dynamic pivot table, and I set  ISNULL = 0.00.
The query is given below

SELECT DISTINCT hdr.EmpNo,hdr.FirstName AS Name,
                ISNULL(TBL.shortname,'')AS shortname,
                ISNULL(TBL.Amount,0.00) AS Amount,
                TBL.Adtype INTO #Temp FROM  tbl1 AS hdr
LEFT JOIN tbl2 TBL  ON TBL.EmpNo = hdr.EmpNo
DECLARE @Ded AS NVARCHAR(MAX)
SET @Ded = STUFF((SELECT ', ISNULL( ' + QUOTENAME(c.shortname) + ', 0.00 )AS ' +
            QUOTENAME(c.shortname)  FROM (SELECT DISTINCT shortname FROM #Temp
            WHERE ISNULL(shortname,'') <> '' AND Adtype = 2) AS c ORDER BY
            shortname  FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)')
            ,1,1,'')
SET @Query = 'SELECT CAST(ROW_NUMBER() OVER(ORDER BY EmpNo ASC) AS
              VARCHAR(100)) AS [S.No],EmpNo,Name,' + @Ded +' FROM  #Temp
              PIVOT(SUM(Amount)  FOR shortname IN (' + @Ded + ')) AS PVTTable'
EXEC sp_executesql @Query

But it displays the following error, and line 3 doesn't not have a "(".

Msg 102, Level 15, State 1, Line 3
                     Incorrect syntax near '('.

Any help to solve this problem would be appreciated.

Body:
Problem is with @der variable use in in clause.
you are setting column name with isnull and in in clause, it is not supported.

Please try below query.

;with tbl1 as
(
select 1 EmpNo,'Emp1' FirstName
union all
select 2 EmpNo,'Emp2' FirstName
),
tbl2 as
(
select 'EMP1' shortname,100 Amount, 2 Adtype,1 EmpNo
union all
select 'EMP2' shortname,100 Amount, 2 Adtype,2 EmpNo
)

SELECT DISTINCT hdr.EmpNo,hdr.FirstName AS Name,
                ISNULL(TBL.shortname,'')AS shortname,
                ISNULL(TBL.Amount,0.00) AS Amount,
                TBL.Adtype INTO #Temp FROM  tbl1 AS hdr
LEFT JOIN tbl2 TBL  ON TBL.EmpNo = hdr.EmpNo

DECLARE @Ded AS NVARCHAR(MAX)='' ,@Query AS NVARCHAR(MAX)=''
DECLARE @Wer AS NVARCHAR(MAX)=''
SET @Ded = STUFF((SELECT ', ISNULL( ' +  QUOTENAME(c.shortname) + ', 0.00 )AS ' +
            QUOTENAME(c.shortname)  FROM (SELECT DISTINCT shortname FROM #Temp
            WHERE ISNULL(shortname,'') <> '' AND Adtype = 2) AS c ORDER BY
            shortname  FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)')
            ,1,1,'')

SET @Wer = STUFF((SELECT ',  ' +  QUOTENAME(c.shortname)  FROM (SELECT DISTINCT shortname FROM #Temp
            WHERE ISNULL(shortname,'') <> '' AND Adtype = 2) AS c ORDER BY
            shortname  FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)')
            ,1,1,'')

SET @Query = 'SELECT CAST(ROW_NUMBER() OVER(ORDER BY EmpNo ASC) AS
              VARCHAR(100)) AS [S.No],EmpNo,Name,' + @Ded +' FROM  #Temp
              PIVOT(SUM(Amount)  FOR shortname IN (' + @Wer + ')) AS PVTTable'
--print @Query

EXEC sp_executesql @Query


问:
Solr 6.6.0 Case Insensitive Query Not Working
Solr 6.6.0 Case Insensitive Query Not Working.
I had tried all other option/answer available on internet.

I had tired with,

```<code><tokenizer class="solr.LowerCaseTokenizerFactory"/>
</code>```

but its not working.

I had tired with,

```<code><filter class="solr.LowerCaseFilterFactory"/>
</code>```

but its not working.

I had tired many different way, but none working.

i.e I want same result searching with title_s:iPhone and title_s:iphone.

I am not sure what would cause problem.

答:
If case insensitive search was not working in a Solr release, you would get much more noise than just one stack overflow question.

Let's use this question to illustrate the approach everyone should follow for basic Solr usage :

1) Refer to the documentation - Solr has a good free online documentation.
   Specifically describing how to configure the schema.xml and the various aspects of it [1].
From there you can learn that is quite simple to configure a field to be case insensitive :

<field name="title" type="text_case_insensitive" indexed="true" stored="true"/>

<fieldType name="text_case_insensitive" class="solr.TextField" positionIncrementGap="100">
        <analyzer type="index">
            <tokenizer class="solr.StandardTokenizerFactory"/>
            <filter class="solr.LowerCaseFilterFactory"/>
        </analyzer>
        <analyzer type="query">
            <tokenizer class="solr.StandardTokenizerFactory"/>
            <filter class="solr.LowerCaseFilterFactory"/>
        </analyzer>
</fieldType>```

N.B. if you had a previous configuration in the schema for the title field, you need to re-index

[1]https://lucene.apache.org/solr/guide/6_6/field-type-definitions-and-properties.html

Body:
Solr 6.6.0 Case Insensitive Query Not Working.
I had tried all other option/answer available on internet.

I had tired with,

<tokenizer class="solr.LowerCaseTokenizerFactory"/>

but its not working.

I had tired with,

<filter class="solr.LowerCaseFilterFactory"/>

but its not working.

I had tired many different way, but none working.

i.e I want same result searching with title_s:iPhone and title_s:iphone.

I am not sure what would cause problem.

Body:
If case insensitive search was not working in a Solr release, you would get much more noise than just one stack overflow question.

Let's use this question to illustrate the approach everyone should follow for basic Solr usage :

1) Refer to the documentation - Solr has a good free online documentation.
   Specifically describing how to configure the schema.xml and the various aspects of it [1].
From there you can learn that is quite simple to configure a field to be case insensitive :

<field name="title" type="text_case_insensitive" indexed="true" stored="true"/>

<fieldType name="text_case_insensitive" class="solr.TextField" positionIncrementGap="100">
        <analyzer type="index">
            <tokenizer class="solr.StandardTokenizerFactory"/>
            <filter class="solr.LowerCaseFilterFactory"/>
        </analyzer>
        <analyzer type="query">
            <tokenizer class="solr.StandardTokenizerFactory"/>
            <filter class="solr.LowerCaseFilterFactory"/>
        </analyzer>
</fieldType>

N.B. if you had a previous configuration in the schema for the title field, you need to re-index

[1]https://lucene.apache.org/solr/guide/6_6/field-type-definitions-and-properties.html


问:
A ghci session without Prelude
This question arose on #haskell irc chat:

How can I start ghci without importing prelude?

The possible answer seemed obvious:

ghci -XNoImplicitPrelude, or load a file with import Prelude ()

The latter seems to work, while the former strangely does not. However, import Prelude () imports the declared instances from Prelude, right? Is there a better way of creating a ghci session without loading Prelude at all?

答:
The accepted answer doesn't seem to work anymore. This does work in ghci 8.0.2.</p>

```<code>Prelude> :set -XNoImplicitPrelude
Prelude> :m -Prelude
>
</code>```

Title: A ghci session without Prelude

Body:
The accepted answer doesn't seem to work anymore. This does work in ghci 8.0.2.

Prelude> :set -XNoImplicitPrelude
Prelude> :m -Prelude
>


问:
jQueryValidate - check if a control is required without triggering validation
I'm trying to show asterisks for controls which are required. The code was working fine with required class but now I have two fields, company and name. Only one of them is required based on other elements value. Is it possible to check if an input is required without validating the control or the form?

Example html structure:

```<code><div class="form-group">
    <label class="control-label" for="CompanyName">Company Name</label>
    <div>
        <input type="text" id="CompanyName" name="CompanyName" class="form-control required">
    </div>
</div>
</code>```

JS:

```<code>validationOptions: {
    ignore: ":disabled,:hidden",

    rules: {
        CompanyName: {
            required: function () {
                return ($("#ContactName").val().length === 0);
            }
        },
        ContactName: {
            required: function () {
                return ($("#CompanyName").val().length === 0);
            }
        }
    },

    onkeyup: function (element) {
        const $parent = $(element).parents(".form-group");

        if ($(element).valid()) {
            $parent.removeClass("invalid");
        } else {
            $parent.addClass("invalid");
        }
    },

    onfocusout: function () {
        if ($("form").valid()) {
            $("form.error").removeClass("error");
            $("form .invalid").removeClass("invalid");
        }
    },

    errorPlacement: function (error, element) {
        const $parent = $(element).parents(".form-group");

        if ($(element).hasClass("error")) {
            $parent.addClass("invalid");
        } else {
            $parent.removeClass("invalid");
        }
    },

    invalidHandler: function (event, validator) {
        $.each(validator.successList, function (index, item) {
            $(item).parents(".form-group").removeClass("invalid");
        });
        const errors = validator.numberOfInvalids();
        if (errors) {
            $.each(validator.errorList, function (index, item) {
                $(item.element).parents(".form-group").addClass("invalid");
            });
        }
    }
}
</code>```

Of course I can have my code inside required callbacks above but that wouldn't be a generic solution.

I want to be able to call following function many times to update (bootstrap) asterisks on the form based on required state of the fields.

```<code>appendFormControlAsterisk: function ($panel) {
    //removeFormControlAsterisk($panel);

    let $controls = $(".form-control.required");

    $controls.each(function () {
        const $label = $(this).parents(".form-group").find(">.control-label");

        $label.html($label.html() + " <span class='text-danger'>*</span>");
    });
},
</code>```

Trying to accomplish something like:

```<code>appendFormControlAsterisk: function ($panel) {
    //removeFormControlAsterisk($panel);

    let $controls = $(".form-control");

    $controls.each(function () {
        if ($(this).isRequired()) {
            const $label = $(this).parents(".form-group").find(">.control-label");

            $label.html($label.html() + " <span class='text-danger'>*</span>");
        }
    });
},
</code>```

答:
Based on examples of jQuery Validation Plugin your rules could be modified like in the below example to solve your problem.

```<code> rules: {
    CompanyName: {
      required: {
        depends: function(element) {
          return $("#ContactName").val().length === 0;
        }
      }
    },
    ContactName: {
      required: {
        depends: function(element) {
          return $("#CompanyName").val().length === 0;
        }
      }
    }
  }
</code>```

OR

```<code> rules: {
    CompanyName: {
      required: {
        depends: function(element) {
          if($("#ContactName").val().length === 0) {
              $("#ContactName").removeClass("required");
              return true;
          } else {
              return false;
          }
        }
      }
    },
    ContactName: {
      required: {
        depends: function(element) {
          if($("#CompanyName").val().length === 0) {
              $("#CompanyName").removeClass("required");
              return true;
          } else {
              return false;
          }
        }
      }
    }
  }
</code>```

Finally

An alternative method would be to use grouping.

```<code><div class="form-group">
    <label class="control-label" for="CompanyName">Company Name</label>
    <div>
        <input type="text" id="CompanyName" name="CompanyName" class="form-control required">
    </div>
</div>
<div class="form-group">
    <label class="control-label" for="ContactName">Contact Name</label>
    <div>
        <input type="text" id="ContactName" name="ContactName" class="form-control required">
    </div>
</div>
  // Use require_from_group to ensure at least one of the fields is complete
  rules: {
    ContactName: {
      require_from_group: [1, ".required"]
    },
    CompanyName: {
      require_from_group: [1, ".required"]
    }
  }
</code>```

Body:
I'm trying to show asterisks for controls which are required. The code was working fine with required class but now I have two fields, company and name. Only one of them is required based on other elements value. Is it possible to check if an input is required without validating the control or the form?

Example html structure:

    Company Name

        <input type="text" id="CompanyName" name="CompanyName" class="form-control required">

JS:

validationOptions: {
    ignore: ":disabled,:hidden",

    rules: {
        CompanyName: {
            required: function () {
                return ($("#ContactName").val().length === 0);
            }
        },
        ContactName: {
            required: function () {
                return ($("#CompanyName").val().length === 0);
            }
        }
    },

    onkeyup: function (element) {
        const $parent = $(element).parents(".form-group");

        if ($(element).valid()) {
            $parent.removeClass("invalid");
        } else {
            $parent.addClass("invalid");
        }
    },

    onfocusout: function () {
        if ($("form").valid()) {
            $("form.error").removeClass("error");
            $("form .invalid").removeClass("invalid");
        }
    },

    errorPlacement: function (error, element) {
        const $parent = $(element).parents(".form-group");

        if ($(element).hasClass("error")) {
            $parent.addClass("invalid");
        } else {
            $parent.removeClass("invalid");
        }
    },

    invalidHandler: function (event, validator) {
        $.each(validator.successList, function (index, item) {
            $(item).parents(".form-group").removeClass("invalid");
        });
        const errors = validator.numberOfInvalids();
        if (errors) {
            $.each(validator.errorList, function (index, item) {
                $(item.element).parents(".form-group").addClass("invalid");
            });
        }
    }
}

Of course I can have my code inside required callbacks above but that wouldn't be a generic solution.

I want to be able to call following function many times to update (bootstrap) asterisks on the form based on required state of the fields.

appendFormControlAsterisk: function ($panel) {
    //removeFormControlAsterisk($panel);

    let $controls = $(".form-control.required");

    $controls.each(function () {
        const $label = $(this).parents(".form-group").find(">.control-label");

        $label.html($label.html() + " *");
    });
},

Trying to accomplish something like:

appendFormControlAsterisk: function ($panel) {
    //removeFormControlAsterisk($panel);

    let $controls = $(".form-control");

    $controls.each(function () {
        if ($(this).isRequired()) {
            const $label = $(this).parents(".form-group").find(">.control-label");

            $label.html($label.html() + " *");
        }
    });
},

Body:
Based on examples of jQuery Validation Plugin your rules could be modified like in the below example to solve your problem.

 rules: {
    CompanyName: {
      required: {
        depends: function(element) {
          return $("#ContactName").val().length === 0;
        }
      }
    },
    ContactName: {
      required: {
        depends: function(element) {
          return $("#CompanyName").val().length === 0;
        }
      }
    }
  }

OR

 rules: {
    CompanyName: {
      required: {
        depends: function(element) {
          if($("#ContactName").val().length === 0) {
              $("#ContactName").removeClass("required");
              return true;
          } else {
              return false;
          }
        }
      }
    },
    ContactName: {
      required: {
        depends: function(element) {
          if($("#CompanyName").val().length === 0) {
              $("#CompanyName").removeClass("required");
              return true;
          } else {
              return false;
          }
        }
      }
    }
  }

Finally

An alternative method would be to use grouping.

<div class="form-group">
    <label class="control-label" for="CompanyName">Company Name</label>
    <div>
        <input type="text" id="CompanyName" name="CompanyName" class="form-control required">
    </div>
</div>
<div class="form-group">
    <label class="control-label" for="ContactName">Contact Name</label>
    <div>
        <input type="text" id="ContactName" name="ContactName" class="form-control required">
    </div>
</div>
  // Use require_from_group to ensure at least one of the fields is complete
  rules: {
    ContactName: {
      require_from_group: [1, ".required"]
    },
    CompanyName: {
      require_from_group: [1, ".required"]
    }
  }


问:
Getting rid of the warning message - the proper way
I am working on a legacy pro* C/C++ code and migrated the project to Visual Studio 2015. When I compile the code in VS, it is giving me a below warning message at more than 100 places.

```<code>warning C4267: '=': conversion from 'size_t' to 'unsigned short', possible loss of data
</code>```

and the corresponding code is

```<code>stmt.len = strlen((char*)stmt.arr); // VARCHAR stmt[500];
</code>```

I was planning to change the above code to

```<code>stmt.len = static_cast<unsigned short>(strlen((char *)stmt.arr));
</code>```

this will just remove the warning message. But I have to modify in more than 100 places. Is there any way to get rid of this warning message may be using some sort of macro?
Please suggest.

Thanks

答:
You can switch off the warning with

```<code>#pragma warning( disable : 4267)
</code>```

although, personally, I'd work through the errors and fix correctly. Your idea with static_cast isn't a bad one, and there is no danger of undefined behaviour with overflow as you're using unsigned types.

Finally, note that using a macro to replace a standard library function is undefined behaviour. Don't do that.

Body:
I am working on a legacy pro* C/C++ code and migrated the project to Visual Studio 2015. When I compile the code in VS, it is giving me a below warning message at more than 100 places.

warning C4267: '=': conversion from 'size_t' to 'unsigned short', possible loss of data

and the corresponding code is

stmt.len = strlen((char*)stmt.arr); // VARCHAR stmt[500];

I was planning to change the above code to

stmt.len = static_cast<unsigned short>(strlen((char *)stmt.arr));

this will just remove the warning message. But I have to modify in more than 100 places. Is there any way to get rid of this warning message may be using some sort of macro?
Please suggest.

Thanks

Body:
You can switch off the warning with

#pragma warning( disable : 4267)

although, personally, I'd work through the errors and fix correctly. Your idea with static_cast isn't a bad one, and there is no danger of undefined behaviour with overflow as you're using unsigned types.

Finally, note that using a macro to replace a standard library function is undefined behaviour. Don't do that.


问:
How do I make my Perl scripts act like normal programs on Windows?
I want my Perl scripts to behave just like any other executable (*.exe file).

When I double-click on myscript.pl I want it to execute instead of opening in a text editor.

I want to run myscript.pl instead of perl myscript.pl.

I really want to run myscript instead of myscript.pl.

I want to run program | myscript instead of program | perl myscript.pl.

I want to be able to run my script via drag & drop.

There are a number of changes you have to make on Windows to make all of
these things work. Users typically stumble upon things that don't work one at
a time; leaving them confused whether they've made an error, there's a bug in
Perl, there's a bug in Windows, or the behavior they want just isn't possible.
This question is intended to provide a single point of reference for making
everything work up front; ideally before these problems even occur.

Related questions:

How do I make Perl scripts recognize parameters in the Win32 cmd console?

Running a perl script on windows without extension

Perl execution from command line question

How can I read piped input in Perl on Windows?

Perl on Windows, file associations and I/O redirection

How do I create drag-and-drop Strawberry Perl programs?

答:
Convert your perl scripts into batch files using pl2bat once they are ready to be run by users.

The trick works through the perl -x switch which, according to perldoc perlrun, makes Perl search for the first line looking like #!.*perl.


问:
button click should only change the clicked item but it's changing all the items Angular 4

The above picture is my current display. when i click on edit button it should only convert the paragraph tag to input field of the selected row.

But in my case it's changing all the paragraph into input fields, i found some solutions but none of them is working.

```<code><div id="lists">
            <table id='mytable' cellspacing='0' cellpadding='0'>
                <tr  class="row" [ngClass]="{'selected': i === selectedIndex}"  *ngFor= 'let item of list let i = index' [attr.data-index]='i'  [ngStyle]="{'background-color': i%2 == '0' ? 'gray' : ''}">
                    <td class='default-field'>
                        <p class='para' *ngIf="showHideP">{{i+1}}. {{item}}</p>
                    </td>
                    <td class="edit-field" *ngIf="tbox" >
                        <input type="text" class="myCl" [value]="val" >
                        <!-- style='display:inline-block;' -->
                    </td>
                    <td class='btns' >

                    <input type='button' value='edit' class='edit-btn' (click)='hidePara(item,i)' *ngIf="edt">

                    <input type='button' value='save' class='save-btn' *ngIf="sbtn" (click)='hidePara1(item,i)'>
                    <input type='button' value='DELETE' class='delete-btn' (click)='deleterow(i)'>
                    </td>
                </tr>
            </table>

        </div>
</code>```

above code is html code

```<code>  export class AppComponentComponent implements OnInit
{
  list: string[];
  val: string;
  search:string;
  showHideP: boolean;
  tbox: boolean;
  sbtn: boolean;
  edt: boolean;

 constructor() {
    this.list=["Purchase a ring for my beautiful wife","get new GALAXY Note 150","Complete kevin's work ASAP","Buy 2 dozen eggs","Get milk on my way to home"];
   this.showHideP = true;
   this.tbox = false;
   this.sbtn = false;
   this.edt = true;

  }
  selectedIndex = 0;
  ngOnInit()  {

  }
  insert=function(temp)
  {
   if(temp!="")
   {
       this.list.unshift(temp);
       this.search="";
   }
   else
   {
        alert("Enter something");
   }
 }
  deleterow=function(p)
  {
     if (p > -1) {
     this.list.splice(p, 1);
   }
  }

   hidePara(item,ii){
   this.val=this.list[ii];
   this.showHideP = !this.showHideP;  //for hiding paragraph
   this.tbox = !this.tbox;  //showing text box
   this.edt=!this.edt;  //hide edt button
   this.sbtn = !this.sbtn;  //display save button

 }

  hidePara1(item,ii){

    this.showHideP = !this.showHideP;  //for hiding paragraph
    this.tbox = !this.tbox;  //showing text box
    this.edt=!this.edt;  //hide edt button
    this.sbtn = !this.sbtn;  //display save button
  }
</code>```

}

the above code is my component, when i click on edit button it shows text fields in paragraph place and save button will display and when i click on save button it changes to original condition

After adding Alexis_ni code it is working fine but it shows like this

答:
There is no need of extra variables like :

```<code>this.showHideP = true;
this.tbox = false;
this.sbtn = false;
this.edt = true;
</code>```

You can maintain this by using single array

```<code>editOn: Array<any>;

hidePara(item,ii){
    this.editOn.indexOf(ii) > -1 ? '' : this.editOn.push(ii);
}

hidePara1(item,ii){
    let index = this.editOn.indexOf(ii);
    this.editOn.splice(index,1);
}
</code>```

Template side :

```<code>*ngIf="editOn.indexOf(i) === -1"
// OR
*ngIf="editOn.indexOf(i) > -1"
</code>```

Here is the working example :

https://stackblitz.com/edit/angular-save-issue

Body:
The above picture is my current display. when i click on edit button it should only convert the paragraph tag to input field of the selected row.

But in my case it's changing all the paragraph into input fields, i found some solutions but none of them is working.

{{i+1}}. {{item}}

                        <input type="text" class="myCl" [value]="val" >

                    <input type='button' value='edit' class='edit-btn' (click)='hidePara(item,i)' *ngIf="edt">

                    <input type='button' value='save' class='save-btn' *ngIf="sbtn" (click)='hidePara1(item,i)'>
                    <input type='button' value='DELETE' class='delete-btn' (click)='deleterow(i)'>

above code is html code

  export class AppComponentComponent implements OnInit
{
  list: string[];
  val: string;
  search:string;
  showHideP: boolean;
  tbox: boolean;
  sbtn: boolean;
  edt: boolean;

 constructor() {
    this.list=["Purchase a ring for my beautiful wife","get new GALAXY Note 150","Complete kevin's work ASAP","Buy 2 dozen eggs","Get milk on my way to home"];
   this.showHideP = true;
   this.tbox = false;
   this.sbtn = false;
   this.edt = true;

  }
  selectedIndex = 0;
  ngOnInit()  {

  }
  insert=function(temp)
  {
   if(temp!="")
   {
       this.list.unshift(temp);
       this.search="";
   }
   else
   {
        alert("Enter something");
   }
 }
  deleterow=function(p)
  {
     if (p > -1) {
     this.list.splice(p, 1);
   }
  }

   hidePara(item,ii){
   this.val=this.list[ii];
   this.showHideP = !this.showHideP;  //for hiding paragraph
   this.tbox = !this.tbox;  //showing text box
   this.edt=!this.edt;  //hide edt button
   this.sbtn = !this.sbtn;  //display save button

 }

  hidePara1(item,ii){

    this.showHideP = !this.showHideP;  //for hiding paragraph
    this.tbox = !this.tbox;  //showing text box
    this.edt=!this.edt;  //hide edt button
    this.sbtn = !this.sbtn;  //display save button
  }

}

the above code is my component, when i click on edit button it shows text fields in paragraph place and save button will display and when i click on save button it changes to original condition

After adding Alexis_ni code it is working fine but it shows like this

Body:
There is no need of extra variables like :

this.showHideP = true;
this.tbox = false;
this.sbtn = false;
this.edt = true;

You can maintain this by using single array

editOn: Array<any>;

hidePara(item,ii){
    this.editOn.indexOf(ii) > -1 ? '' : this.editOn.push(ii);
}

hidePara1(item,ii){
    let index = this.editOn.indexOf(ii);
    this.editOn.splice(index,1);
}

Template side :

*ngIf="editOn.indexOf(i) === -1"
// OR
*ngIf="editOn.indexOf(i) > -1"

Here is the working example :

https://stackblitz.com/edit/angular-save-issue


问:
How to keep everything and nothing (specify in dictionary table)?
What is the proper way to say everything and nothing in a dictionary table?

For example, for key11, I keep only .txt and .doc files. How do I specify for key12, to keep every (any) filetypes, and for key13 to keep no filtypes (keep nothing)?

```<code>config = {
    ' key11': {},
    ' key12': {},
    ' key13': {},
}
config['key11']['files_to_keep'] = ('txt', 'doc')
config['key12']['files_to_keep'] = ('"*"')
config['key13']['files_to_keep'] = ()
</code>```

答:
Try to think of how it is supposed to work instead.
For instance to filter out specific file-endings we could use this:

Note that we don't need to use any extra logic (if-statements) because the string already represents it.

```<code>config = {
    'key11': {},
    'key12': {},
    'key13': {},
}

config['key11']['files_to_keep'] = ('txt', 'doc') # txt.doc
config['key12']['files_to_keep'] = ('')  # All
config['key13']['files_to_keep'] = ('*') # None as strings don't end with *

files = ['C:\\Users\\user\\Desktop\\Text1.txt',
     'C:\\Users\\user\\Desktop\\Doc1.doc',
     'C:\\Users\\user\\Desktop\\Img1.png']
</code>```

Key 11:

```<code>[i for i in files if i.endswith(config['key11']['files_to_keep'])]
</code>```

Returns:

```<code>['C:\\Users\\user\\Desktop\\Text1.txt', 'C:\\Users\\user\\Desktop\\Doc1.doc']
</code>```

While  Key 12:

```<code>[i for i in files if i.endswith(config['key11']['files_to_keep'])]
</code>```

Returns:

```<code>['C:\\Users\\user\\Desktop\\Text1.txt',
 'C:\\Users\\user\\Desktop\\Doc1.doc',
 'C:\\Users\\user\\Desktop\\Img1.png']
</code>```

And Key 13.. is empty :)

Body:
What is the proper way to say everything and nothing in a dictionary table?

For example, for key11, I keep only .txt and .doc files. How do I specify for key12, to keep every (any) filetypes, and for key13 to keep no filtypes (keep nothing)?

config = {
    ' key11': {},
    ' key12': {},
    ' key13': {},
}
config['key11']['files_to_keep'] = ('txt', 'doc')
config['key12']['files_to_keep'] = ('"*"')
config['key13']['files_to_keep'] = ()

Body:
Try to think of how it is supposed to work instead.
For instance to filter out specific file-endings we could use this:

Note that we don't need to use any extra logic (if-statements) because the string already represents it.

config = {
    'key11': {},
    'key12': {},
    'key13': {},
}

config['key11']['files_to_keep'] = ('txt', 'doc') # txt.doc
config['key12']['files_to_keep'] = ('')  # All
config['key13']['files_to_keep'] = ('*') # None as strings don't end with *

files = ['C:\\Users\\user\\Desktop\\Text1.txt',
     'C:\\Users\\user\\Desktop\\Doc1.doc',
     'C:\\Users\\user\\Desktop\\Img1.png']

Key 11:

[i for i in files if i.endswith(config['key11']['files_to_keep'])]

Returns:

['C:\\Users\\user\\Desktop\\Text1.txt', 'C:\\Users\\user\\Desktop\\Doc1.doc']

While  Key 12:

[i for i in files if i.endswith(config['key11']['files_to_keep'])]

Returns:

['C:\\Users\\user\\Desktop\\Text1.txt',
 'C:\\Users\\user\\Desktop\\Doc1.doc',
 'C:\\Users\\user\\Desktop\\Img1.png']

And Key 13.. is empty :)


问:
How to set a variable as a class method and not as a static method
I'm trying to grasp some comments that were made to me by my professor on a programming assignment.  The assignment was to write a program that calls upon another class.  This program was to take 2 investors with different starting balances and show how much interest they would collect after a 15 month period.
Just so everyone is clear, my assignment has already been graded, so any critiques or changes would NOT be helping me complete my homework, but ONLY to help me understand what I did wrong and how I can fix it for future assignments.  I received a 90% on my program for my grade.

The following comments were made about my assignment:

"Your setInterest method was to be a class method not an instance
method. Also, your call should have been

```<code>IWUnit4Ch13Investor.setInterest(rate);"
</code>```

I'm not exactly following what I did wrong or how I can fix it.  Can someone please show me what I did wrong and possibly explain why it's wrong so that I may correct my habits for future assignments and grasp how to correctly write code?

```<code>// IWUnit4Ch13.java
import java.util.*;
import java.util.Scanner;

// main class
public class IWUnit4Ch13 {

    public static void main(String[] args) {

        // Declares local variables
        double rate, INTEREST_RATE;

        // Instantiate investor1 & investor2 objects using a two parameter constructor
        IWUnit4Ch13Investor investor1 = new IWUnit4Ch13Investor(1001, 2000);
        IWUnit4Ch13Investor investor2 = new IWUnit4Ch13Investor(2001, 4000);
        Scanner input = new Scanner(System.in);

        // Receives the APR by the user
        System.out.print("Please enter the APR in the form of .05 for 5%: ");
        rate = input.nextDouble();

        // Moves the decimal 2 places to the left (used later)
        INTEREST_RATE = rate * 100;

        // Sets the interest rate using a class variable
        investor1.setInterestRate(rate);
        investor2.setInterestRate(rate);

        // Prints the header for the table
        System.out.printf("Monthly balances for one year with %.2f annual interest:\n\n", rate);
        System.out.println("Month Account #   Balance Account #   Balance");
        System.out.println("----- ---------   ------- ---------   -------");

        // Loop that prints each month on the table
        // Uses class variables to add interest and get balance for display
        for (int i = 1; i <= 15; i++) {
            investor1.addInterest();
            investor2.addInterest();
            System.out.printf("%5d %9d %9.2f %9d %9.2f\n", i, investor1.getACCOUNT_NUMBER(), investor1.getBalance(), investor2.getACCOUNT_NUMBER(), investor2.getBalance());
            }

        // Prints the calculated interest earned by both investors
        System.out.printf("\nInvestor1 earned : %.2f", investor1.getInterest());
        System.out.printf(" interest in 15 months at %.2f", INTEREST_RATE);
        System.out.print("%\n");
        System.out.printf("Investor2 earned : %.2f", investor2.getInterest());
        System.out.printf(" interest in 15 months at %.2f", INTEREST_RATE);
        System.out.print("%\n\n");

    } // end of internal main
} // end of main class
</code>```

```<code>// Creates IWUnit4Ch13Investor.java which is used in IWUnit4Ch13.java
public class IWUnit4Ch13Investor extends IWUnit4Ch13 {

    // All variables are declared private
    private static double interestRate; // class variable
    private final int ACCOUNT_NUMBER;   // declare constant ACCOUNT_NUMBER
    private double balance;             // instance variable called balance
    private double initialBalance;      // to hold the initial balance
    private double interest;            // to count how much interest was made
    private double INTEREST_RATE;       // used to convert the float interestRate to int

    // Two parameter constructor to initialize account number and balance
    public IWUnit4Ch13Investor(int acctNum, double initialBalance) {
        this.initialBalance = initialBalance;
        this.ACCOUNT_NUMBER = acctNum;
        balance = initialBalance;
    }

    // To return the balance to parent
    public double getBalance() {
        return balance;
    }

    // Class method to set the annual interest rate
    public void setInterestRate(double rate) {
        interestRate = rate;
    }

    // Method to add interest based on balance * interestRate / 12
    public void addInterest() {
        balance += balance * interestRate/12.0;
    }

    // To get account number in parent
    public int getACCOUNT_NUMBER() {
        return ACCOUNT_NUMBER;
    }

    // Used to get the amount of interested earned during 15 months
    public double getInterest() {
        interest = balance - initialBalance;
        return interest;
    }
} // end of class
</code>```

Thank you all in advance for your help.

答:
So a static variable is shared by all instances of the class.

If you want all investors to be forced to share the same interest rate, use a static variable.

Methods that only affect static variables should (https://www.ietf.org/rfc/rfc2119.txt) be declared static:

```<code>public static void setInterestRate(double rate) {
    interestRate = rate;
}

private static double interestRate;
</code>```

You would then call the static method by specifying the class name, not the instance variable.  Note that you can call the static method before you even have any instances of the class, and you only need to call it once:

```<code>Investor.setInterestRate(0.05);

Investor i1 = new Investor();
Investor i2 = new Investor();

double r1 = i1.calculateBalance();
double r2 = i2.calculateBalance();
</code>```

If you want each investor to be able to have different interest rates, do not use a static variable,  use a member variable and method:

```<code>public void setInterestRate(double rate) {
    interestRate = rate;
}

private double interestRate;
</code>```

You then call the method by specifying the instance variable:

```<code>Investor i1 = new Investor();
Investor i2 = new Investor();

i1.setInterestRate(0.04);
i2.setInterestRate(0.06);

double r1 = i1.calculateBalance();
double r2 = i2.calculateBalance();
</code>```

Also, none of that really matters because the output is wrong:

```<code>double monthly_rate = pow(10.0, log10(1.0 + yearly_rate) / 12.0) - 1.0;
</code>```

The system shall not fail

Body:
I'm trying to grasp some comments that were made to me by my professor on a programming assignment.  The assignment was to write a program that calls upon another class.  This program was to take 2 investors with different starting balances and show how much interest they would collect after a 15 month period.
Just so everyone is clear, my assignment has already been graded, so any critiques or changes would NOT be helping me complete my homework, but ONLY to help me understand what I did wrong and how I can fix it for future assignments.  I received a 90% on my program for my grade.

The following comments were made about my assignment:

"Your setInterest method was to be a class method not an instance
method. Also, your call should have been

IWUnit4Ch13Investor.setInterest(rate);"

I'm not exactly following what I did wrong or how I can fix it.  Can someone please show me what I did wrong and possibly explain why it's wrong so that I may correct my habits for future assignments and grasp how to correctly write code?

// IWUnit4Ch13.java
import java.util.*;
import java.util.Scanner;

// main class
public class IWUnit4Ch13 {

    public static void main(String[] args) {

        // Declares local variables
        double rate, INTEREST_RATE;

        // Instantiate investor1 & investor2 objects using a two parameter constructor
        IWUnit4Ch13Investor investor1 = new IWUnit4Ch13Investor(1001, 2000);
        IWUnit4Ch13Investor investor2 = new IWUnit4Ch13Investor(2001, 4000);
        Scanner input = new Scanner(System.in);

        // Receives the APR by the user
        System.out.print("Please enter the APR in the form of .05 for 5%: ");
        rate = input.nextDouble();

        // Moves the decimal 2 places to the left (used later)
        INTEREST_RATE = rate * 100;

        // Sets the interest rate using a class variable
        investor1.setInterestRate(rate);
        investor2.setInterestRate(rate);

        // Prints the header for the table
        System.out.printf("Monthly balances for one year with %.2f annual interest:\n\n", rate);
        System.out.println("Month Account #   Balance Account #   Balance");
        System.out.println("----- ---------   ------- ---------   -------");

        // Loop that prints each month on the table
        // Uses class variables to add interest and get balance for display
        for (int i = 1; i <= 15; i++) {
            investor1.addInterest();
            investor2.addInterest();
            System.out.printf("%5d %9d %9.2f %9d %9.2f\n", i, investor1.getACCOUNT_NUMBER(), investor1.getBalance(), investor2.getACCOUNT_NUMBER(), investor2.getBalance());
            }

        // Prints the calculated interest earned by both investors
        System.out.printf("\nInvestor1 earned : %.2f", investor1.getInterest());
        System.out.printf(" interest in 15 months at %.2f", INTEREST_RATE);
        System.out.print("%\n");
        System.out.printf("Investor2 earned : %.2f", investor2.getInterest());
        System.out.printf(" interest in 15 months at %.2f", INTEREST_RATE);
        System.out.print("%\n\n");

    } // end of internal main
} // end of main class

// Creates IWUnit4Ch13Investor.java which is used in IWUnit4Ch13.java
public class IWUnit4Ch13Investor extends IWUnit4Ch13 {

    // All variables are declared private
    private static double interestRate; // class variable
    private final int ACCOUNT_NUMBER;   // declare constant ACCOUNT_NUMBER
    private double balance;             // instance variable called balance
    private double initialBalance;      // to hold the initial balance
    private double interest;            // to count how much interest was made
    private double INTEREST_RATE;       // used to convert the float interestRate to int

    // Two parameter constructor to initialize account number and balance
    public IWUnit4Ch13Investor(int acctNum, double initialBalance) {
        this.initialBalance = initialBalance;
        this.ACCOUNT_NUMBER = acctNum;
        balance = initialBalance;
    }

    // To return the balance to parent
    public double getBalance() {
        return balance;
    }

    // Class method to set the annual interest rate
    public void setInterestRate(double rate) {
        interestRate = rate;
    }

    // Method to add interest based on balance * interestRate / 12
    public void addInterest() {
        balance += balance * interestRate/12.0;
    }

    // To get account number in parent
    public int getACCOUNT_NUMBER() {
        return ACCOUNT_NUMBER;
    }

    // Used to get the amount of interested earned during 15 months
    public double getInterest() {
        interest = balance - initialBalance;
        return interest;
    }
} // end of class

Thank you all in advance for your help.

Body:
So a static variable is shared by all instances of the class.

If you want all investors to be forced to share the same interest rate, use a static variable.

Methods that only affect static variables should (https://www.ietf.org/rfc/rfc2119.txt) be declared static:

public static void setInterestRate(double rate) {
    interestRate = rate;
}

private static double interestRate;

You would then call the static method by specifying the class name, not the instance variable.  Note that you can call the static method before you even have any instances of the class, and you only need to call it once:

Investor.setInterestRate(0.05);

Investor i1 = new Investor();
Investor i2 = new Investor();

double r1 = i1.calculateBalance();
double r2 = i2.calculateBalance();

If you want each investor to be able to have different interest rates, do not use a static variable,  use a member variable and method:

public void setInterestRate(double rate) {
    interestRate = rate;
}

private double interestRate;

You then call the method by specifying the instance variable:

Investor i1 = new Investor();
Investor i2 = new Investor();

i1.setInterestRate(0.04);
i2.setInterestRate(0.06);

double r1 = i1.calculateBalance();
double r2 = i2.calculateBalance();

Also, none of that really matters because the output is wrong:

double monthly_rate = pow(10.0, log10(1.0 + yearly_rate) / 12.0) - 1.0;

The system shall not fail


问:
Render JSON data using React
I have this JSON data I am trying to render as a list.

```<code>[{
    "id": "1",
    "name": "Bill"
}, {
    "id": "2",
    "name": "Sarah"
}]
</code>```

I am trying to display the data such that I pass a title of the data and the id's as parameters from Parent class to Child class and the latter prints the data as list.

```<code>export default class Parent extends Component {
  render() {
    return (
        <div>
        <Child
          title={"Group 1"}
          options={this.props.data.name}
        />
        </div>
    );
  }
}
</code>```

Here's my Child class:

```<code>export default class Child extends Component {
  render() {
    var data=this.props;
    var title=this.props.title;
    var name=this.props.name;
    return (
      <ul>
        <h4>{title}</h4>
        <div>{this.props.map(item=>
          <li>{name}</li>
        )}
        </div>
      </ul>
    );
  }
}
</code>```

What I don't understand is how to use map in the Child class to display data. I know that I shouldn't write this.props.map(item=>. I am new to React and would appreciate some help fixing this.

答:
Just pass your data as prop from parent component and you can access it in child component.

let {Component} = React;

const data = [{
    "id": "1",
    "name": "Bill"
}, {
    "id": "2",
    "name": "Sarah"
}]

class Child extends Component {
  render() {
   let {data, title} = this.props;

    return (

{title}

{data.map(item=>

{item.name}

        )}

    );
  }
}

class Parent extends Component {
  render() {
    return (

          <Child
            title={"Group 1"}
            data={this.props.data}
          />

    );
  }
}

ReactDOM.render(
  <Parent data={data} />,
  document.getElementById('app')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16.1.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.1.0/umd/react-dom.development.js"></script>
<div id="app"></div></code>```

You can also call map method inside parent component and for each element in your data render Child component. Also only li element can be direct child of ul.

let {Component} = React;
const data = [{"id": "1","name": "Bill"}, {"id": "2","name": "Sarah"}]

class Child extends Component {
  render() {
    let {name} = this.props;
    return
{name}

  }
}

class Parent extends Component {
  render() {
    return (

{"Group 1"}

{this.props.data.map(item => {
                return <Child key={item.id} {...item} />
              })}

    );
  }
}

ReactDOM.render(
  <Parent data={data} />,
  document.getElementById('app')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16.1.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.1.0/umd/react-dom.development.js"></script>
<div id="app"></div></code>```

Update: for nested children you can React.cloneElement to dynamically add child nodes.

let {Component} = React;
const data = [{ "id": "1", "name": "Bill" }, { "id": "2", "name": "Sarah", "childnodes": [{ "id": "3", "name": "Some name", "childnodes": [{ "id": "4", "name": "Last" }]}] }]

class Child extends Component {
  render() {
    let {name} = this.props;
    return

      {name}
      {this.props.children ?
{this.props.children}
 : ''}

  }
}

class Parent extends Component {
  constructor(props) {
    super(props);
    this.renderNodes = this.renderNodes.bind(this);
  }

  renderNodes(data) {
    return data.map(item => {
      let child = <Child key={item.id} {...item} />

      if(item.childnodes) {
        child = React.cloneElement(child, {
          children: this.renderNodes(item.childnodes)
        })
      }

      return child;
    })
  }

  render() {
    return (

{"Group 1"}

{this.renderNodes(this.props.data)}

    );
  }
}

ReactDOM.render(
  <Parent data={data} />,
  document.getElementById('app')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16.1.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.1.0/umd/react-dom.development.js"></script>
<div id="app"></div></code>```

Title: Render JSON data using React

Body:
I have this JSON data I am trying to render as a list.

[{
    "id": "1",
    "name": "Bill"
}, {
    "id": "2",
    "name": "Sarah"
}]

I am trying to display the data such that I pass a title of the data and the id's as parameters from Parent class to Child class and the latter prints the data as list.

export default class Parent extends Component {
  render() {
    return (

        <Child
          title={"Group 1"}
          options={this.props.data.name}
        />

    );
  }
}

Here's my Child class:

export default class Child extends Component {
  render() {
    var data=this.props;
    var title=this.props.title;
    var name=this.props.name;
    return (

{title}

{this.props.map(item=>

{name}

        )}

    );
  }
}

What I don't understand is how to use map in the Child class to display data. I know that I shouldn't write this.props.map(item=>. I am new to React and would appreciate some help fixing this.

Body:
Just pass your data as prop from parent component and you can access it in child component.

let {Component} = React;

const data = [{
    "id": "1",
    "name": "Bill"
}, {
    "id": "2",
    "name": "Sarah"
}]

class Child extends Component {
  render() {
   let {data, title} = this.props;

    return (
      <ul>
        <h4>{title}</h4>
        <div>{data.map(item=>
          <li key={item.id}>{item.name}</li>
        )}
        </div>
      </ul>
    );
  }
}

class Parent extends Component {
  render() {
    return (
        <div>
          <Child
            title={"Group 1"}
            data={this.props.data}
          />
        </div>
    );
  }
}

ReactDOM.render(
  <Parent data={data} />,
  document.getElementById('app')
);

<script src="https://unpkg.com/react@16.1.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.1.0/umd/react-dom.development.js"></script>
<div id="app"></div>

You can also call map method inside parent component and for each element in your data render Child component. Also only li element can be direct child of ul.

let {Component} = React;
const data = [{"id": "1","name": "Bill"}, {"id": "2","name": "Sarah"}]

class Child extends Component {
  render() {
    let {name} = this.props;
    return <li>{name}</li>
  }
}

class Parent extends Component {
  render() {
    return (
        <div>
          <h1>{"Group 1"}</h1>
          <ul>{this.props.data.map(item => {
                return <Child key={item.id} {...item} />
              })}
          </ul>
        </div>
    );
  }
}

ReactDOM.render(
  <Parent data={data} />,
  document.getElementById('app')
);

<script src="https://unpkg.com/react@16.1.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.1.0/umd/react-dom.development.js"></script>
<div id="app"></div>

Update: for nested children you can React.cloneElement to dynamically add child nodes.

let {Component} = React;
const data = [{ "id": "1", "name": "Bill" }, { "id": "2", "name": "Sarah", "childnodes": [{ "id": "3", "name": "Some name", "childnodes": [{ "id": "4", "name": "Last" }]}] }]

class Child extends Component {
  render() {
    let {name} = this.props;
    return <li>
      {name}
      {this.props.children ? <ul>{this.props.children}</ul> : ''}
    </li>
  }
}

class Parent extends Component {
  constructor(props) {
    super(props);
    this.renderNodes = this.renderNodes.bind(this);
  }

  renderNodes(data) {
    return data.map(item => {
      let child = <Child key={item.id} {...item} />

      if(item.childnodes) {
        child = React.cloneElement(child, {
          children: this.renderNodes(item.childnodes)
        })
      }

      return child;
    })
  }

  render() {
    return (
        <div>
          <h1>{"Group 1"}</h1>
          <ul>{this.renderNodes(this.props.data)}</ul>
        </div>
    );
  }
}

ReactDOM.render(
  <Parent data={data} />,
  document.getElementById('app')
);

<script src="https://unpkg.com/react@16.1.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.1.0/umd/react-dom.development.js"></script>
<div id="app"></div>


问:
Populate select options from database to dynamic select option using jQuery
From the database I have selected the names of the members as the select options. With jQuery, I have a dynamic Add button that adds new select field with the append function. But what could be the standard way to pass my select options generated by php in the append?

I have researched for a while but could not get it working. So any suggestions would be really helpful.

This is the page structure. It looks messy but please have a look at it. I have passed the $members as <?php echo $members; ?> in a static select that already is there from the beginning, but for the dynamic ones, I have created a variable var members and tried to pass it in the append but it is not working.

```<code><?php
   require_once 'db_connect.php';

   $members = '';
   $query = "SELECT memberID, memberName FROM members";
   $result = mysqli_query($connect, $query);
   while($row = mysqli_fetch_array($result))
   {
    $members .= '<option value="'.$row["memberID"].'">'.$row["memberName"].'</option>';
   }
   ?>
<script>
   var members = "<?php echo $members; ?>";

   $(document).ready(function() {
          var fixHelperModified = function(e, div) {
                var $originals = div.children();
                var $helper = div.clone();
                $helper.children().each(function(index) {
                   $(this).width($originals.eq(index).width())
                });
                return $helper;
             },
             updateIndex = function() {
                $('div.index').each(function(i) {
                   $(this).html(i + 1);
                });
             };
          $("#add").sortable({
             helper: fixHelperModified,
             stop: updateIndex
          }).disableSelection();
          $("#addNew").click(function() {
             $('#add').append("<div class='row rem' id='move'><div class='col-md-1 index'>1. </div><div class='col-md-9'><select name='members[]'><option value=''>Select member</option>"+members+"</select></div><div class='col-md-1'><button class='delete btn btn-warning btn-xs'>Delete</button></div></div>");
             updateIndex();
          });
          $("body").on('click', '#add .delete', function() {
             $(this).closest(".rem").remove();
             updateIndex();
          });
       });
</script>
<form method="post">
   <fieldset>
      <div class="form-group">
         <div class="col-sm-2">
            <label class="form-name">Members</label>
         </div>
         <div class="col-sm-8">
            <div class="row">
               <div id='add'>
                  <div class='row rem' id='move'>
                     <div class='col-md-1 index'>1. </div>
                     <div class='col-md-9'>
                        <select name='members[]'>
                           <option value=''>Select member</option>
                           <?php echo $members; ?>
                        </select>
                     </div>
                     <div class='col-md-1'>
                        <button class='delete btn btn-warning btn-xs'>Delete</button>
                     </div>
                  </div>
               </div>
            </div>
            <div class="row">
               <div class="form-group">
                  <div class="col-md-2">
                     <button id='addNew' type="button" href="#">Add another</button>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </fieldset>
   <input type="submit" name="submitSave" value="Submit">
</form>
</code>```

Here is a snippet of the form without the php if you need to see the jQuery in action.

    $(document).ready(function() {
       var fixHelperModified = function(e, div) {
             var $originals = div.children();
             var $helper = div.clone();
             $helper.children().each(function(index) {
                $(this).width($originals.eq(index).width())
             });
             return $helper;
          },
          updateIndex = function() {
             $('div.index').each(function(i) {
                $(this).html(i + 1);
             });
          };
       $("#add").sortable({
          helper: fixHelperModified,
          stop: updateIndex
       }).disableSelection();
       $("#addNew").click(function() {
          $('#add').append("

1.

<select name='members[]'><option value=''>Select member</option></select>

<button class='delete btn btn-warning btn-xs'>Delete</button>

");
          updateIndex();
       });
       $("body").on('click', '#add .delete', function() {
          $(this).closest(".rem").remove();
          updateIndex();
       });
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<form method="post">
   <fieldset>
      <div class="form-group">
         <div class="col-sm-2">
            <label class="form-name">Members</label>
         </div>
         <div class="col-sm-8">
            <div class="row">
               <div id='add'>
                  <div class='row rem' id='move'>
                     <div class='col-md-1 index'>1. </div>
                     <div class='col-md-9'>
                        <select name='members[]'>
                        <option value=''>Select member</option>
                        <option value='First'>First</option>
                        <option value='Second'>Second</option>
                        </select>
                     </div>
                     <div class='col-md-1'>
                        <button class='delete btn btn-warning btn-xs'>Delete</button>
                     </div>
                  </div>
               </div>
            </div>
            <div class="row">
               <div class="form-group">
                  <div class="col-md-2">
                     <button id='addNew' type="button" href="#">Add another</button>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </fieldset>
   <input type="submit" name="submitSave" value="Submit">
</form></code>```

答: I dont get you want to use jquery to add a select option from the list of already generated options(generated with php) each time a user clicks the add button?</p>

Body:
From the database I have selected the names of the members as the select options. With jQuery, I have a dynamic Add button that adds new select field with the append function. But what could be the standard way to pass my select options generated by php in the append?

I have researched for a while but could not get it working. So any suggestions would be really helpful.

This is the page structure. It looks messy but please have a look at it. I have passed the $members as <?php echo $members; ?> in a static select that already is there from the beginning, but for the dynamic ones, I have created a variable var members and tried to pass it in the append but it is not working.

<?php
   require_once 'db_connect.php';

   $members = '';
   $query = "SELECT memberID, memberName FROM members";
   $result = mysqli_query($connect, $query);
   while($row = mysqli_fetch_array($result))
   {
    $members .= '<option value="'.$row["memberID"].'">'.$row["memberName"].'</option>';
   }
   ?>

<form method="post">
   <fieldset>

            Members

1.

                        <select name='members[]'>
                           <option value=''>Select member</option>
                           <?php echo $members; ?>
                        </select>

                        <button class='delete btn btn-warning btn-xs'>Delete</button>

                     <button id='addNew' type="button" href="#">Add another</button>

   </fieldset>
   <input type="submit" name="submitSave" value="Submit">
</form>

Here is a snippet of the form without the php if you need to see the jQuery in action.

    $(document).ready(function() {
       var fixHelperModified = function(e, div) {
             var $originals = div.children();
             var $helper = div.clone();
             $helper.children().each(function(index) {
                $(this).width($originals.eq(index).width())
             });
             return $helper;
          },
          updateIndex = function() {
             $('div.index').each(function(i) {
                $(this).html(i + 1);
             });
          };
       $("#add").sortable({
          helper: fixHelperModified,
          stop: updateIndex
       }).disableSelection();
       $("#addNew").click(function() {
          $('#add').append("

1.

<select name='members[]'><option value=''>Select member</option></select>

<button class='delete btn btn-warning btn-xs'>Delete</button>

");
          updateIndex();
       });
       $("body").on('click', '#add .delete', function() {
          $(this).closest(".rem").remove();
          updateIndex();
       });
    });

<form method="post">
   <fieldset>

            Members

1.

                        <select name='members[]'>
                        <option value=''>Select member</option>
                        <option value='First'>First</option>
                        <option value='Second'>Second</option>
                        </select>

                        <button class='delete btn btn-warning btn-xs'>Delete</button>

                     <button id='addNew' type="button" href="#">Add another</button>

   </fieldset>
   <input type="submit" name="submitSave" value="Submit">
</form>


问:
App crashes in viewForHeaderInSection:
I have have a tableview integrated in my app. The code is like this

```<code>- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [sortedDates count];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    EventHeaderView *headerView = (EventHeaderView *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:@"eventHeader"];
    if(headerView == nil) {
        headerView = [[EventHeaderView alloc] initWithReuseIdentifier:@"eventHeader"];
    }

    NSString *date = [sortedDates objectAtIndex:section]; **// app crashes here**
    NSString *formatHeaderStr = [NSDate stringFromDate:[NSDate dateFromString:date withFormat:@"yyyy-MM-dd"] withFormat:@"EE, MMMM dd yyyy"];
    [headerView.dateLbl setText:formatHeaderStr];
    [headerView.addEventBtn setTag:(section+1)*100];
    [headerView.addEventBtn addTarget:self action:@selector(addEventBtnClicked:) forControlEvents:UIControlEventTouchUpInside];

    [headerView layoutSubviews];
    return headerView;
}
</code>```

The number of sections return 'sortedDates' count but still viewForHeader crashes on [sortedDates objectAtIndex:section]. It happens at other places in my code as well.

I do not understand how to fix such issues. There is very small delay in these methods being getting called one after the other but still the array seems to be empty when it reaches the viewForHeader methods.

Kindly help.

答:
If you are using objectAtIndex method make sure that your array has that many objects in it.So in your case just check

```<code>if (section >= 0 && section < [sortedArray count])
{
    NSString *date = [sortedDates objectAtIndex:section];
}
</code>```

Also check if the sortedDate object is not released accidentally.

Title: App crashes in viewForHeaderInSection:

Body:
I have have a tableview integrated in my app. The code is like this

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [sortedDates count];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    EventHeaderView *headerView = (EventHeaderView *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:@"eventHeader"];
    if(headerView == nil) {
        headerView = [[EventHeaderView alloc] initWithReuseIdentifier:@"eventHeader"];
    }

    NSString *date = [sortedDates objectAtIndex:section]; **// app crashes here**
    NSString *formatHeaderStr = [NSDate stringFromDate:[NSDate dateFromString:date withFormat:@"yyyy-MM-dd"] withFormat:@"EE, MMMM dd yyyy"];
    [headerView.dateLbl setText:formatHeaderStr];
    [headerView.addEventBtn setTag:(section+1)*100];
    [headerView.addEventBtn addTarget:self action:@selector(addEventBtnClicked:) forControlEvents:UIControlEventTouchUpInside];

    [headerView layoutSubviews];
    return headerView;
}

The number of sections return 'sortedDates' count but still viewForHeader crashes on [sortedDates objectAtIndex:section]. It happens at other places in my code as well.

I do not understand how to fix such issues. There is very small delay in these methods being getting called one after the other but still the array seems to be empty when it reaches the viewForHeader methods.

Kindly help.

Body:
If you are using objectAtIndex method make sure that your array has that many objects in it.So in your case just check

if (section >= 0 && section < [sortedArray count])
{
    NSString *date = [sortedDates objectAtIndex:section];
}

Also check if the sortedDate object is not released accidentally.