问:
Google Sheets: Determining if a time falls within a two specified times
I'm trying to find a way to determine if a time falls between two specific times - with two  different scenarios to flag. So far, I'm coming up empty (and frustrated!)

Column B has date/times such as:

```<code>February 9, 2022 09:55AM
February 9, 2022 01:15PM
February 9, 2022 09:39PM
</code>```

Flag 1: Time is between 4AM and Noon

Flag 2: Time is between 8PM and 4AM -- does this need to be broken down into two separate conditions given that it spreads over midnight?

Resulting Output in Column C:

```<code>FLAG 1
[Blank Cell - No Flag]
FLAG 2
</code>```

Appreciate any ideas - thanks to the community, as always.

CTO

答:
try:

```<code>=ARRAYFORMULA(IFERROR(IF(
 (TIMEVALUE(A1:A)>=TIMEVALUE("4:00:00"))*
 (TIMEVALUE(A1:A)< TIMEVALUE("12:00:00")), "Flag 1",IF(
 (TIMEVALUE(A1:A)>=TIMEVALUE("20:00:00"))*
 (TIMEVALUE(A1:A)<=TIMEVALUE("23:59:59"))+
 (TIMEVALUE(A1:A)>=TIMEVALUE("00:00:00"))*
 (TIMEVALUE(A1:A)< TIMEVALUE("04:00:00")), "Flag 2", ))))
</code>```

Body:
I'm trying to find a way to determine if a time falls between two specific times - with two  different scenarios to flag. So far, I'm coming up empty (and frustrated!)

Column B has date/times such as:

February 9, 2022 09:55AM
February 9, 2022 01:15PM
February 9, 2022 09:39PM

Flag 1: Time is between 4AM and Noon

Flag 2: Time is between 8PM and 4AM -- does this need to be broken down into two separate conditions given that it spreads over midnight?

Resulting Output in Column C:

FLAG 1
[Blank Cell - No Flag]
FLAG 2

Appreciate any ideas - thanks to the community, as always.

CTO

Body:
try:

=ARRAYFORMULA(IFERROR(IF(
 (TIMEVALUE(A1:A)>=TIMEVALUE("4:00:00"))*
 (TIMEVALUE(A1:A)< TIMEVALUE("12:00:00")), "Flag 1",IF(
 (TIMEVALUE(A1:A)>=TIMEVALUE("20:00:00"))*
 (TIMEVALUE(A1:A)<=TIMEVALUE("23:59:59"))+
 (TIMEVALUE(A1:A)>=TIMEVALUE("00:00:00"))*
 (TIMEVALUE(A1:A)< TIMEVALUE("04:00:00")), "Flag 2", ))))


来源: stackexchange

问:
Global Object in singleton
In the Singleton pattern why is that we have to use a static object and not a global object?

I tried the following

```<code>class Singleton;
Singleton*  instance1 = NULL;

class Singleton
{
private :
       Singleton()
       {
       }
       //static Singleton* instance1;

public:
        static Singleton* getinstance()

 if(instance1== NULL)
       {
       instance1 = new Singleton();
       }

 return instance1;

 void Dispaly()
       {
       }
 ~Singleton()
       {
       }
};
</code>```

When I compile this code I get the error "multiple definition of instance1"

Can anyone please give a plausible reason for this?

答:
To answer your direct question:

The reason you get the error message is because you are defining a variable in a header file (well, that's my guess, anyway).  So every time you #include that header file, the variable will get re-defined.

In summary, there's almost never a good reason for defining variables in header files.

[Side note: as others have explained, this is a very bad implementation of the singleton pattern.]

ContentLicense: CC BY-SA 3.0

Title: Global Object in singleton

Body:
In the Singleton pattern why is that we have to use a static object and not a global object?

I tried the following

class Singleton;
Singleton*  instance1 = NULL;

class Singleton
{
private :
       Singleton()
       {
       }
       //static Singleton* instance1;

public:
        static Singleton* getinstance()

 if(instance1== NULL)
       {
       instance1 = new Singleton();
       }

 return instance1;

 void Dispaly()
       {
       }
 ~Singleton()
       {
       }
};

When I compile this code I get the error "multiple definition of instance1"

Can anyone please give a plausible reason for this?


问:
Discord.js How to add roles when a user joins if the bot is in multiple servers
My bot is currently part of multiple server and Im trying to get it to add a role to a user when they join one of the servers, I have done stuff like
if(bot.guild.id === [SERVER ID])  and I've tried different forms of the bot.on command to no avail.
the current code is

```<code>bot.on('guildMemberAdd', guildMember => {id
    let welcomerole = guildMember.guild.roles.find(role => role.name === 'Nomad');

    guildMember.roles.add(welcomerole);
    guildMember.guild.channels.get([SERVER_ID]).send("Welcome to the server")
})
</code>```

But as per usual it does not work.
I'm not sure if there is a function im missing in the bot.on section of the block, or if the issue is something else. Note I am running Discord.js 11.6, so these functions do or should work with the version. (there is a reason).
Is there is a way to have it so the bot only adds the role to one of the servers that its a part of.

答: Just update to Discord.js V13, v11 is many years out of date and new docs solutions won't work with it.

ContentLicense: CC BY-SA 4.0

Body:
My bot is currently part of multiple server and Im trying to get it to add a role to a user when they join one of the servers, I have done stuff like
if(bot.guild.id === [SERVER ID])  and I've tried different forms of the bot.on command to no avail.
the current code is

bot.on('guildMemberAdd', guildMember => {id
    let welcomerole = guildMember.guild.roles.find(role => role.name === 'Nomad');

    guildMember.roles.add(welcomerole);
    guildMember.guild.channels.get([SERVER_ID]).send("Welcome to the server")
})

But as per usual it does not work.
I'm not sure if there is a function im missing in the bot.on section of the block, or if the issue is something else. Note I am running Discord.js 11.6, so these functions do or should work with the version. (there is a reason).
Is there is a way to have it so the bot only adds the role to one of the servers that its a part of.


问:
Jquery phone number validation start from+30
** Jquery phone number validation **
Jquery phone number validation using regular expression.

valid phone number:- +30344343434,
ragex not working and error show:-
Uncaught SyntaxError: Invalid regular expression: /^(+30)[0-9]{9}$/: Nothing to repeat

```<code>$.validator.addMethod("PhoneValidation", (function(e) {
        let regex =  /^(+30)[0-9]{9}$/.test(e);
        return(regex);
    }), PHONE_VALIDATE);
</code>```

suggest valid regex.

答:
You can try this

```<code>$.validator.addMethod("PhoneValidation", function (value) {
       return /^(\+30)(30|31|32|33|34|35|36|37|38|39)[0-9]{7}$/.test(value);
}, "Please enter valid number.");
</code>```

put \ before starting +30 in the first bracket
And
in the second bracket, put pair with 3 which you want to validate

Body:
** Jquery phone number validation **
Jquery phone number validation using regular expression.

valid phone number:- +30344343434,
ragex not working and error show:-
Uncaught SyntaxError: Invalid regular expression: /^(+30)[0-9]{9}$/: Nothing to repeat

$.validator.addMethod("PhoneValidation", (function(e) {
        let regex =  /^(+30)[0-9]{9}$/.test(e);
        return(regex);
    }), PHONE_VALIDATE);

suggest valid regex.

Body:
You can try this

$.validator.addMethod("PhoneValidation", function (value) {
       return /^(\+30)(30|31|32|33|34|35|36|37|38|39)[0-9]{7}$/.test(value);
}, "Please enter valid number.");

put \ before starting +30 in the first bracket
And
in the second bracket, put pair with 3 which you want to validate


问:
Error in Angular 8 reactive form file upload
I am trying to upload file in Angular 8 but getting below error and not able to figure it out

```<code>ERROR DOMException: "An attempt was made to use an object that is not, or is no longer, usable"
</code>```

above error comes when I select a file. Below is my approach

Component.ts

import { Component, OnInit } from '@angular/core';
import {FormArray,FormBuilder,FormGroup,FormControl, Validators, NgForm} from "@angular/forms";
import { ApiService } from '../apis/commonapis';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
  userForm : FormGroup;
  constructor(private fb : FormBuilder,private service : ApiService) { }

  ngOnInit() {
    this.newForm();
  }
  newForm = function(){
    this.userForm = this.fb.group({
      email : ['',Validators.compose([Validators.required])],
      photo : ['',Validators.compose([Validators.required])]
    })
  }
  PostData(form: NgForm) {
    //console.log(form);
    var formData = new FormData();
    formData.append('photo', this.userForm.get('photo').value);
    console.log(formData);
    /*this.service.PostApi("http://localhost:1900/addUser",formData).subscribe(res=>{
                console.log(res);
                location.reload();
            });
     */
  }

  onFileSelect(event) { // here is some error
    if (event.target.files.length > 0) {
      const file = event.target.files[0];
      this.userForm.get('photo').setValue(file);
    }
  }
}
```

<p>template file</p>

<pre class="lang-html prettyprint-override"><code><form [formGroup]="userForm" (ngSubmit)="PostData(userForm)" enctype="multipart/form-data">
        <div class="form-group row">
                <label for="email" class="col-sm-2 col-form-label">Email</label>
                <div class="col-sm-9">
                        <input type="text"  formControlName='email' class="form-control" required>
                </div>
        </div>

        <div class="form-group row">
                <label for="photo" class="col-sm-2 col-form-label">Photo</label>
                <div class="col-sm-9">
                        <input type="file"  formControlName='photo' class="form-control" required  (change)="onFileSelect($event)">
                </div>
        </div>

        <div class="form-group row">

                <div class="col-sm-10">
                        <input type="submit"  value='submit' class="form-control">
                </div>
        </div>

</form>
</code>```

I have searched for above error and it says this error comes when DOM is not loaded but here element is already loaded than why this error?

答:
I came to a similar problem. Just like Passionate Code mentioned in the comment, the solution was to remove formControlName from <input>. It seems to me that the problem arises from the fact, that we are initializing the FormControl with an empty string and then we are trying to enter the File type object, meybe that some inner type validation is throwing the occuring exception. In my opinion, the best option is to skip the formControlName directive usage and write some custom validation.

Change this:

```<code><div class="col-sm-9">
    <input type="text" formControlName='email' class="form-control" required>
</div>
</code>```

to this:

```<code><div class="col-sm-9">
    <input type="text" class="form-control" required>
</div>
</code>```

Body:
I am trying to upload file in Angular 8 but getting below error and not able to figure it out

ERROR DOMException: "An attempt was made to use an object that is not, or is no longer, usable"

above error comes when I select a file. Below is my approach

Component.ts

import { Component, OnInit } from '@angular/core';
import {FormArray,FormBuilder,FormGroup,FormControl, Validators, NgForm} from "@angular/forms";
import { ApiService } from '../apis/commonapis';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
  userForm : FormGroup;
  constructor(private fb : FormBuilder,private service : ApiService) { }

  ngOnInit() {
    this.newForm();
  }
  newForm = function(){
    this.userForm = this.fb.group({
      email : ['',Validators.compose([Validators.required])],
      photo : ['',Validators.compose([Validators.required])]
    })
  }
  PostData(form: NgForm) {
    //console.log(form);
    var formData = new FormData();
    formData.append('photo', this.userForm.get('photo').value);
    console.log(formData);
    /*this.service.PostApi("http://localhost:1900/addUser",formData).subscribe(res=>{
                console.log(res);
                location.reload();
            });
     */
  }

  onFileSelect(event) { // here is some error
    if (event.target.files.length > 0) {
      const file = event.target.files[0];
      this.userForm.get('photo').setValue(file);
    }
  }
}

template file

<form [formGroup]="userForm" (ngSubmit)="PostData(userForm)" enctype="multipart/form-data">

                Email

                        <input type="text"  formControlName='email' class="form-control" required>

                Photo

                        <input type="file"  formControlName='photo' class="form-control" required  (change)="onFileSelect($event)">

                        <input type="submit"  value='submit' class="form-control">

</form>

I have searched for above error and it says this error comes when DOM is not loaded but here element is already loaded than why this error?

Body:
I came to a similar problem. Just like Passionate Code mentioned in the comment, the solution was to remove formControlName from <input>. It seems to me that the problem arises from the fact, that we are initializing the FormControl with an empty string and then we are trying to enter the File type object, meybe that some inner type validation is throwing the occuring exception. In my opinion, the best option is to skip the formControlName directive usage and write some custom validation.

Change this:

<div class="col-sm-9">
    <input type="text" formControlName='email' class="form-control" required>
</div>

to this:

<div class="col-sm-9">
    <input type="text" class="form-control" required>
</div>


问:
long time cron in App Engine
I want to rewrite a webapp to Python and to use App Engine but I have several cron scripts that can be long running. Some time ago I used App Engine and wanted to know if there are now methods to run these scripts because App Engine has its limits.
If you want to get an idea of one of the scripts there is one that calculates the karma users based on what has been done on the website, so there are mathematical calculations, many executions SQL... and can take much time.

Thanks!

答:
Well, you won't be running any SQL queries, because AppEngine doesn't use SQL.

Two new options for running expensive calculations are backends and MapReduce - which you choose depends on exactly what you want to achieve.

Title: long time cron in App Engine


问:
Testing OnPush components in Angular 2
I am having trouble testing a component with OnPush change detection strategy.

The test goes like this

```<code>it('should show edit button for featured only for owners', () => {
    let selector = '.edit-button';

    component.isOwner = false;
    fixture.detectChanges();

    expect(fixture.debugElement.query(By.css(selector))).toBeFalsy();

    component.isOwner = true;
    fixture.detectChanges();

    expect(fixture.debugElement.query(By.css(selector))).toBeTruthy();
});
</code>```

If I use Default strategy it works as expected, but with OnPush the change to isOwner is not rerendered by the call to detectChanges. Am I missing something?

答:
It doesn't work because the changeDetectorRef in your fixture isn't the same as in your component. Taken from the issue in Angular:

"...changeDetectorRef on a ComponentRef points to the change detector of the root (host) view of a dynamically created component. Then, inside the host view we've got the actual component view, but the component view is OnPush thus we never refresh it!" - source

Option A. One way to solve this is to use the components injector to get the real changeDetectionRef:

describe('MyComponent', () => {
  let fixture;
  let component;

  beforeEach(() => {
    TestBed.configureTestingModule({ ... }).compileComponents();
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('does something', () => {
    // set the property here
    component.property = 'something';

    // do a change detection on the real changeDetectionRef
    fixture.componentRef.injector.get(ChangeDetectorRef).detectChanges();

    expect(...).toBe(...);
  });
});
```
<p>You could also just use the initial binding to an @Input (which initially triggers changedetection for an OnPush strategy):</p>
<p><strong>Option B1:</strong></p>
<pre class="lang-js prettyprint-override"><code>describe('MyComponent', () => {
  let fixture;
  let component;

  beforeEach(() => {
    TestBed.configureTestingModule({ ... }).compileComponents();
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
  });

  it('does something', () => {
    // set the property here
    component.property = 'something';

    // do the first (and only) change detection here
    fixture.detectChanges();

    expect(...).toBe(...);
  });
});
</code>```

or for example:

Option B2:

describe('MyComponent', () => {
  let fixture;
  let component;

  it('does something', () => {
    // set the property here
    setup({ property: 'something' });
    expect(...).toBe(...);
  });

  function setup(props: { property? } = {}) {
    TestBed.configureTestingModule({ ... }).compileComponents();
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;

    Object.getOwnPropertyNames(props).forEach((propertyName) => {
      component[propertyName] = props[propertyName];
    });

    // do the first (and only) change detection here
    fixture.detectChanges();
  }
});
```

Title: Testing OnPush components in Angular 2

Body:
I am having trouble testing a component with OnPush change detection strategy.

The test goes like this

it('should show edit button for featured only for owners', () => {
    let selector = '.edit-button';

    component.isOwner = false;
    fixture.detectChanges();

    expect(fixture.debugElement.query(By.css(selector))).toBeFalsy();

    component.isOwner = true;
    fixture.detectChanges();

    expect(fixture.debugElement.query(By.css(selector))).toBeTruthy();
});

If I use Default strategy it works as expected, but with OnPush the change to isOwner is not rerendered by the call to detectChanges. Am I missing something?

Body:
It doesn't work because the changeDetectorRef in your fixture isn't the same as in your component. Taken from the issue in Angular:

"...changeDetectorRef on a ComponentRef points to the change detector of the root (host) view of a dynamically created component. Then, inside the host view we've got the actual component view, but the component view is OnPush thus we never refresh it!" - source

Option A. One way to solve this is to use the components injector to get the real changeDetectionRef:

describe('MyComponent', () => {
  let fixture;
  let component;

  beforeEach(() => {
    TestBed.configureTestingModule({ ... }).compileComponents();
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('does something', () => {
    // set the property here
    component.property = 'something';

    // do a change detection on the real changeDetectionRef
    fixture.componentRef.injector.get(ChangeDetectorRef).detectChanges();

    expect(...).toBe(...);
  });
});

You could also just use the initial binding to an @Input (which initially triggers changedetection for an OnPush strategy):

Option B1:

describe('MyComponent', () => {
  let fixture;
  let component;

  beforeEach(() => {
    TestBed.configureTestingModule({ ... }).compileComponents();
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
  });

  it('does something', () => {
    // set the property here
    component.property = 'something';

    // do the first (and only) change detection here
    fixture.detectChanges();

    expect(...).toBe(...);
  });
});

or for example:

Option B2:

describe('MyComponent', () => {
  let fixture;
  let component;

  it('does something', () => {
    // set the property here
    setup({ property: 'something' });
    expect(...).toBe(...);
  });

  function setup(props: { property? } = {}) {
    TestBed.configureTestingModule({ ... }).compileComponents();
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;

    Object.getOwnPropertyNames(props).forEach((propertyName) => {
      component[propertyName] = props[propertyName];
    });

    // do the first (and only) change detection here
    fixture.detectChanges();
  }
});


问:
Link active effect not working while loading in new page
After click in page link, this jQuery doesn't remove active class from unclicked link and also not implementing this class in clicked item. It seems not working for page load. Is there any solution for it.

$(document).ready(function () {
  $('a').click(function() {
    $('a').removeClass('active');
    $(this).addClass('active');
  })
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.active {
  color: red
}</code>```

  Page 1
  Page 2

```

答:
I found the solution via this jQuery. This issue happened for page loading.</p>
```<code>jQuery(function($) {
    var path = window.location.href;
    $('a').each(function() {
        if (this.href === path) {
            $(this).addClass('active');
        }
    });
});
</code>```

Body:
After click in page link, this jQuery doesn't remove active class from unclicked link and also not implementing this class in clicked item. It seems not working for page load. Is there any solution for it.

$(document).ready(function () {
  $('a').click(function() {
    $('a').removeClass('active');
    $(this).addClass('active');
  })
});

.active {
  color: red
}

  Page 1
  Page 2

Body:
I found the solution via this jQuery. This issue happened for page loading.

jQuery(function($) {
    var path = window.location.href;
    $('a').each(function() {
        if (this.href === path) {
            $(this).addClass('active');
        }
    });
});


问:
Loading Model only once in fastAPI
I have a Deep learning model and i want to load that model only once when my api start.
Right now model is loading for every request made in my api service with the test image, and it is taking fair bit of time to print an output.

I tried loading my model with fastapi @app.on_event('startup')

```<code>main.py
@app.on_event('startup')
def init_data():
    print("init call")
    model = load_model(model_path)
    return model
</code>```

and I want to import this model variable to another python file classification.py

```<code>#classification.py
pred = model.predict(image)
</code>```

I am not sure if this is the correct way to do this. Any help regarding this will be appreciated.

Thanks

答:
So what you need, it is just to encapsulate this in some functions and pass the model along.

# main.py
import classification
# Other imports...

model = load_model(model_path)
# Model is global so loaded once.

# ...

@app.get('/whatever/page')
def predict(image):
    global model   # We make sure model is not local
    # We call classification's predict function
    result = classification.predict(image, model)

    #...
```
<pre class="lang-py prettyprint-override"><code>#classification.py
# import ...

# The function predict takes the model as a param, and the image to predict.
def predict(image, model):
    pred = model.predict(image)
    # ...
    return pred
</code>```

You should do this better with typing of the parameters, etc.  but that gives an idea of the dataflow. Another approach would be to load the model in the root of classification.py so you don't need to pass it along. That will be executed only once when imported the first time.

Title: Loading Model only once in fastAPI

Body:
I have a Deep learning model and i want to load that model only once when my api start.
Right now model is loading for every request made in my api service with the test image, and it is taking fair bit of time to print an output.

I tried loading my model with fastapi @app.on_event('startup')

main.py
@app.on_event('startup')
def init_data():
    print("init call")
    model = load_model(model_path)
    return model

and I want to import this model variable to another python file classification.py

#classification.py
pred = model.predict(image)

I am not sure if this is the correct way to do this. Any help regarding this will be appreciated.

Thanks

Body:
So what you need, it is just to encapsulate this in some functions and pass the model along.

# main.py
import classification
# Other imports...

model = load_model(model_path)
# Model is global so loaded once.

# ...

@app.get('/whatever/page')
def predict(image):
    global model   # We make sure model is not local
    # We call classification's predict function
    result = classification.predict(image, model)

    #...

#classification.py
# import ...

# The function predict takes the model as a param, and the image to predict.
def predict(image, model):
    pred = model.predict(image)
    # ...
    return pred

You should do this better with typing of the parameters, etc.  but that gives an idea of the dataflow. Another approach would be to load the model in the root of classification.py so you don't need to pass it along. That will be executed only once when imported the first time.


问:
how to create sum and inner sum of group by in pandas data frame
I have the below data frame

```<code>       sector__description            industry__description     weight
           REAL ESTATE                      REAL ESTATE       0.564507
              INDUSTRIALS              INDUSTRIAL PRODUCTS    0.894072
               TECHNOLOGY   TECH HARDWARE & SEMICONDUCTORS    3.633277
          CLOSED END FUND                   FUND_OBJECTIVE    2.276752
              FINANCIALS               FINANCIAL SERVICES     1.145301
                  ENERGY                        OIL & GAS     3.099118
               TECHNOLOGY   TECH HARDWARE & SEMICONDUCTORS    0.987115
               FINANCIALS                          BANKING    6.034223
              HEALTH CARE                      HEALTH CARE    1.134993
                UTILITIES                        UTILITIES    1.345726
             HEALTH CARE                      HEALTH CARE     1.117600
         CLOSED END FUND                  CLOSED END FUND     0.063387
             FINANCIALS                        INSURANCE      1.275847
        CONSUMER STAPLES         CONSUMER STAPLE PRODUCTS     0.634256
              FINANCIALS                        INSURANCE     15.541616
              FINANCIALS                        INSURANCE     4.777598
             REAL ESTATE                      REAL ESTATE     0.647987
            MONEY MARKET                     MONEY MARKET     2.634138
            MONEY MARKET                     MONEY MARKET     2.637100
             REAL ESTATE                      REAL ESTATE     0.788146
        CONSUMER STAPLES     RETAIL & WHOLESALE - STAPLES     1.754561
              FINANCIALS                          BANKING     2.146774
  CONSUMER DISCRETIONARY  CONSUMER DISCRETIONARY SERVICES     3.579005
</code>```

from this I need a list like below for all the sectors

[ {'sector': 'FINANCIALS' , weight: 'total sum of all financials', sub:[{'sector': 'FINANCIAL SERVICES' , weight: 'total sum of all financial services'},{'sector': 'INSURANCE' , weight: 'total sum of all insurance'}, {'sector': 'BANKING' , weight: 'total sum of all banking']}, .....   ]

答:
Use list comprehension for your custom format with aggregate sum per both levels:

```<code>out = [{'sector': k,
        'weight': v['weight'].sum(),
        'sub': v.groupby('industry__description')['weight']
                .sum()
                .rename_axis('sector')
                .reset_index().to_dict(orient='records')}
       for k, v in df.groupby('sector__description')]
</code>```

```<code>print (out)

[
   {
      "sector":"CLOSED END FUND",
      "weight":2.340139,
      "sub":[
         {
            "sector":"CLOSED END FUND",
            "weight":0.063387
         },
         {
            "sector":"FUND_OBJECTIVE",
            "weight":2.276752
         }
      ]
   },
   {
      "sector":"CONSUMER DISCRETIONARY",
      "weight":3.579005,
      "sub":[
         {
            "sector":"CONSUMER DISCRETIONARY SERVICES",
            "weight":3.579005
         }
      ]
   },
   {
      "sector":"CONSUMER STAPLES",
      "weight":2.388817,
      "sub":[
         {
            "sector":"CONSUMER STAPLE PRODUCTS",
            "weight":0.634256
         },
         {
            "sector":"RETAIL & WHOLESALE - STAPLES",
            "weight":1.754561
         }
      ]
   },
   {
      "sector":"ENERGY",
      "weight":3.099118,
      "sub":[
         {
            "sector":"OIL & GAS",
            "weight":3.099118
         }
      ]
   },
   {
      "sector":"FINANCIALS",
      "weight":30.921359,
      "sub":[
         {
            "sector":"BANKING",
            "weight":8.180997
         },
         {
            "sector":"FINANCIAL SERVICES",
            "weight":1.145301
         },
         {
            "sector":"INSURANCE",
            "weight":21.595061
         }
      ]
   },
   {
      "sector":"HEALTH CARE",
      "weight":2.252593,
      "sub":[
         {
            "sector":"HEALTH CARE",
            "weight":2.252593
         }
      ]
   },
   {
      "sector":"INDUSTRIALS",
      "weight":0.894072,
      "sub":[
         {
            "sector":"INDUSTRIAL PRODUCTS",
            "weight":0.894072
         }
      ]
   },
   {
      "sector":"MONEY MARKET",
      "weight":5.271238,
      "sub":[
         {
            "sector":"MONEY MARKET",
            "weight":5.271238
         }
      ]
   },
   {
      "sector":"REAL ESTATE",
      "weight":2.0006399999999998,
      "sub":[
         {
            "sector":"REAL ESTATE",
            "weight":2.0006399999999998
         }
      ]
   },
   {
      "sector":"TECHNOLOGY",
      "weight":4.620392,
      "sub":[
         {
            "sector":"TECH HARDWARE & SEMICONDUCTORS",
            "weight":4.620392
         }
      ]
   },
   {
      "sector":"UTILITIES",
      "weight":1.345726,
      "sub":[
         {
            "sector":"UTILITIES",
            "weight":1.345726
         }
      ]
   }
]
</code>```

EDIT:

```<code>out = [{'n': k,
        'v': v['weight'].sum(),
        'sub': v.groupby('industry__description')['weight']
                .sum()
                .sort_values()
                .rename_axis('n')
                .reset_index(name='v')
                .to_dict(orient='records')}
       for k, v in df.groupby('sector__description')]

print (out)
</code>```

Body:
I have the below data frame

       sector__description            industry__description     weight
           REAL ESTATE                      REAL ESTATE       0.564507
              INDUSTRIALS              INDUSTRIAL PRODUCTS    0.894072
               TECHNOLOGY   TECH HARDWARE & SEMICONDUCTORS    3.633277
          CLOSED END FUND                   FUND_OBJECTIVE    2.276752
              FINANCIALS               FINANCIAL SERVICES     1.145301
                  ENERGY                        OIL & GAS     3.099118
               TECHNOLOGY   TECH HARDWARE & SEMICONDUCTORS    0.987115
               FINANCIALS                          BANKING    6.034223
              HEALTH CARE                      HEALTH CARE    1.134993
                UTILITIES                        UTILITIES    1.345726
             HEALTH CARE                      HEALTH CARE     1.117600
         CLOSED END FUND                  CLOSED END FUND     0.063387
             FINANCIALS                        INSURANCE      1.275847
        CONSUMER STAPLES         CONSUMER STAPLE PRODUCTS     0.634256
              FINANCIALS                        INSURANCE     15.541616
              FINANCIALS                        INSURANCE     4.777598
             REAL ESTATE                      REAL ESTATE     0.647987
            MONEY MARKET                     MONEY MARKET     2.634138
            MONEY MARKET                     MONEY MARKET     2.637100
             REAL ESTATE                      REAL ESTATE     0.788146
        CONSUMER STAPLES     RETAIL & WHOLESALE - STAPLES     1.754561
              FINANCIALS                          BANKING     2.146774
  CONSUMER DISCRETIONARY  CONSUMER DISCRETIONARY SERVICES     3.579005

from this I need a list like below for all the sectors

[ {'sector': 'FINANCIALS' , weight: 'total sum of all financials', sub:[{'sector': 'FINANCIAL SERVICES' , weight: 'total sum of all financial services'},{'sector': 'INSURANCE' , weight: 'total sum of all insurance'}, {'sector': 'BANKING' , weight: 'total sum of all banking']}, .....   ]

Body:
Use list comprehension for your custom format with aggregate sum per both levels:

out = [{'sector': k,
        'weight': v['weight'].sum(),
        'sub': v.groupby('industry__description')['weight']
                .sum()
                .rename_axis('sector')
                .reset_index().to_dict(orient='records')}
       for k, v in df.groupby('sector__description')]

print (out)

[
   {
      "sector":"CLOSED END FUND",
      "weight":2.340139,
      "sub":[
         {
            "sector":"CLOSED END FUND",
            "weight":0.063387
         },
         {
            "sector":"FUND_OBJECTIVE",
            "weight":2.276752
         }
      ]
   },
   {
      "sector":"CONSUMER DISCRETIONARY",
      "weight":3.579005,
      "sub":[
         {
            "sector":"CONSUMER DISCRETIONARY SERVICES",
            "weight":3.579005
         }
      ]
   },
   {
      "sector":"CONSUMER STAPLES",
      "weight":2.388817,
      "sub":[
         {
            "sector":"CONSUMER STAPLE PRODUCTS",
            "weight":0.634256
         },
         {
            "sector":"RETAIL & WHOLESALE - STAPLES",
            "weight":1.754561
         }
      ]
   },
   {
      "sector":"ENERGY",
      "weight":3.099118,
      "sub":[
         {
            "sector":"OIL & GAS",
            "weight":3.099118
         }
      ]
   },
   {
      "sector":"FINANCIALS",
      "weight":30.921359,
      "sub":[
         {
            "sector":"BANKING",
            "weight":8.180997
         },
         {
            "sector":"FINANCIAL SERVICES",
            "weight":1.145301
         },
         {
            "sector":"INSURANCE",
            "weight":21.595061
         }
      ]
   },
   {
      "sector":"HEALTH CARE",
      "weight":2.252593,
      "sub":[
         {
            "sector":"HEALTH CARE",
            "weight":2.252593
         }
      ]
   },
   {
      "sector":"INDUSTRIALS",
      "weight":0.894072,
      "sub":[
         {
            "sector":"INDUSTRIAL PRODUCTS",
            "weight":0.894072
         }
      ]
   },
   {
      "sector":"MONEY MARKET",
      "weight":5.271238,
      "sub":[
         {
            "sector":"MONEY MARKET",
            "weight":5.271238
         }
      ]
   },
   {
      "sector":"REAL ESTATE",
      "weight":2.0006399999999998,
      "sub":[
         {
            "sector":"REAL ESTATE",
            "weight":2.0006399999999998
         }
      ]
   },
   {
      "sector":"TECHNOLOGY",
      "weight":4.620392,
      "sub":[
         {
            "sector":"TECH HARDWARE & SEMICONDUCTORS",
            "weight":4.620392
         }
      ]
   },
   {
      "sector":"UTILITIES",
      "weight":1.345726,
      "sub":[
         {
            "sector":"UTILITIES",
            "weight":1.345726
         }
      ]
   }
]

EDIT:

out = [{'n': k,
        'v': v['weight'].sum(),
        'sub': v.groupby('industry__description')['weight']
                .sum()
                .sort_values()
                .rename_axis('n')
                .reset_index(name='v')
                .to_dict(orient='records')}
       for k, v in df.groupby('sector__description')]

print (out)


答:
If you include this header in multiple files, you will get a copy of the pointer in each file.

That's probably what the linker is complaining about.

Title: Global Object in singleton


问:
Java SimpleDateFormat Cannot format given Object as a Date
I am trying to convert string to date using date format and used the following code but its shows an error.

```<code>      public static Date ConvertStringtodate(String Date) throws ParseException {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date Teststart = dateFormat.parse(Date);
            return Teststart;
        }

        public static void main(String[]agrs) throws ParseException {
            System.out.println(ConvertStringtodate("2022.02.10 17:54:55"));
        }
</code>```

Here is the error

Exception in thread "main" java.lang.IllegalArgumentException: Cannot
format given Object as a Date     at
java.text.DateFormat.format(DateFormat.java:310)  at
java.text.Format.format(Format.java:157)

答: At the main method, you are sending date as "2022.02.10 17:54:55". However, you wrote format of the pattern as "yyyy-MM-dd hh:mm:ss". Change the pattern at the SimpleDateFormat constructor as "yyyy.MM.dd HH:mm:ss".</p>

Body:
I am trying to convert string to date using date format and used the following code but its shows an error.

      public static Date ConvertStringtodate(String Date) throws ParseException {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date Teststart = dateFormat.parse(Date);
            return Teststart;
        }

        public static void main(String[]agrs) throws ParseException {
            System.out.println(ConvertStringtodate("2022.02.10 17:54:55"));
        }

Here is the error

Exception in thread "main" java.lang.IllegalArgumentException: Cannot
format given Object as a Date     at
java.text.DateFormat.format(DateFormat.java:310)  at
java.text.Format.format(Format.java:157)


问:
Optional appsettings.local.json in (new format) visual studio project
My app uses appsettings.json for some settings. If appsettings.local.json is present, that should override appsettings.json for whatever settings it contains. So far, no problem.

But I use git for version control. Obviously, I don't want other users pulling down my local settings. So I git ignore appsettings.json.

Furthermore, there are a lot of projects in the solution. They share the same settings. So there is an appsettings.json at the solution level, and all the projects include it as a link.

Still fine, except for one thing. In order to be usable, I have to copy appsettings.local.json over to the output directory. But it shouldn't be in version control. So if someone clones the solution fresh they won't have it. That ought to be fine, but it isn't. VS. says "this file should be linked, but where the heck is it?" build error.

How can I deal with that?

答:
For .NET 6, you can use this.

Also make sure, you git ignore appsettings.local.json to avoid check-in sensitive information like password and secrets.

```<code>var builder = WebApplication.CreateBuilder(args);

// Add configurations
builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
{
    config.Sources.Clear();

    var env = hostingContext.HostingEnvironment;

    config.SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) //load base settings
            .AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: true) //load local settings
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) //load environment settings
            .AddEnvironmentVariables();

    if (args != null)
    {
        config.AddCommandLine(args);
    }
});
</code>```

Body:
For .NET 6, you can use this.

Also make sure, you git ignore appsettings.local.json to avoid check-in sensitive information like password and secrets.

var builder = WebApplication.CreateBuilder(args);

// Add configurations
builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
{
    config.Sources.Clear();

    var env = hostingContext.HostingEnvironment;

    config.SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) //load base settings
            .AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: true) //load local settings
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) //load environment settings
            .AddEnvironmentVariables();

    if (args != null)
    {
        config.AddCommandLine(args);
    }
});


问:
TypeError: Cannot read properties of undefined (reading 'pathname')
TypeError: Cannot read properties of undefined (reading 'pathname')

What is the problem?
My code

```<code>import {BrowserRouter as Routes, Route, Router} from "react-router-dom";

const App = () => {
return (
      <div className={stl.container}>
          <Header/>
          <Nav/>

          <Router>
              <Routes>
                  <Route path='/messages'  element={<Messages/>}/>
                  <Route path='/profile' element={<ProfileContent/>}/>
              </Routes>
          </Router>

      </div>

 );
}
</code>```

答: The issue is due to  you cannot pass an 'undefined' or 'null' value to the attribute, like in my case, I could have added a null-check, but I chose to add a "/" before it, as shown

Body:
TypeError: Cannot read properties of undefined (reading 'pathname')

What is the problem?
My code

import {BrowserRouter as Routes, Route, Router} from "react-router-dom";

const App = () => {
return (

          <Router>
              <Routes>
                  <Route path='/messages'  element={<Messages/>}/>
                  <Route path='/profile' element={<ProfileContent/>}/>
              </Routes>
          </Router>

 );
}


问:
looping through arrays of arrays
I have an arrays of arrays (some thing like graph), How to iterate all arrays?

```<code>var parentArray = [
 [[1,2,3],[4,5,6],[7,8,9]],
 [[10,11,12],[13,14,15],[16,17,18]],
 [[19,20,21],[22,23,24],[26,27,28]]
];
</code>```

Its just an example array, actual can contains any number of array and then arrays. How to print all those numbers? Its similar to html objects DOM

答:
One option would be to use recursion which works with any number of dephts. See traverse(), it's not tested but should give a rough idea:

```<code>String.prototype.lpad = function(padString, length) {
    var str = this;
    while (str.length < length)
        str = padString + str;
    return str;
}

var level = 0;

function traverse(obj) {
   if (obj instanceof Array) { level++; for(var i in obj) traverse(obj[i]); level--; }
   else console.log(''.lpad('-', level) + obj);
}
</code>```

Title: looping through arrays of arrays

Body:
I have an arrays of arrays (some thing like graph), How to iterate all arrays?

var parentArray = [
 [[1,2,3],[4,5,6],[7,8,9]],
 [[10,11,12],[13,14,15],[16,17,18]],
 [[19,20,21],[22,23,24],[26,27,28]]
];

Its just an example array, actual can contains any number of array and then arrays. How to print all those numbers? Its similar to html objects DOM

Body:
One option would be to use recursion which works with any number of dephts. See traverse(), it's not tested but should give a rough idea:

String.prototype.lpad = function(padString, length) {
    var str = this;
    while (str.length < length)
        str = padString + str;
    return str;
}

var level = 0;

function traverse(obj) {
   if (obj instanceof Array) { level++; for(var i in obj) traverse(obj[i]); level--; }
   else console.log(''.lpad('-', level) + obj);
}


问:
Window form does not close
Hey guys i am new to the Windows application.

I have a form on which Login button click event i have shown to other Forms. Example like i have a login page after user authentication other two Forms shown. But i want after authentication of user Login Form should be close, But others two remain open.

Following is code, my Login Form name is LogIn.cs

```<code>private void btnLogIn_Click(object sender, EventArgs e)
{
    if(ValidateUser())
    {
       //Form1

        DetailForm form = new DetailForm(txtUserName.Text.ToString());
        form.Show();

        //Form2

        Progressbar progress = new Progressbar();
        progress.Show();
    }
}
</code>```

please write some code

答:
The problem is that the Main message loop of your application is in the LogIn form, it means that if you stop this message loop, your application stops.

Personally I won't let the LogIn form own the main message loop of your app. I wouldn't open the DetailForm and the ProgressBar from the LogIn form, it doesn't make much sense. I'd make some parent class which controls all of them.

If you do want the LogIn form to be the main of your app but hide it once the user logs in, you could either use Hide(), or run the two child windows in seperate Threads or Processes (not Highly recommended).

Title: Window form does not close

Body:
Hey guys i am new to the Windows application.

I have a form on which Login button click event i have shown to other Forms. Example like i have a login page after user authentication other two Forms shown. But i want after authentication of user Login Form should be close, But others two remain open.

Following is code, my Login Form name is LogIn.cs

private void btnLogIn_Click(object sender, EventArgs e)
{
    if(ValidateUser())
    {
       //Form1

        DetailForm form = new DetailForm(txtUserName.Text.ToString());
        form.Show();

        //Form2

        Progressbar progress = new Progressbar();
        progress.Show();
    }
}

please write some code


问:
Java WebSocket session resulting to null after onOpen
I am using websockets for the first time on a javafx project, when I start the program the session is set to the local variable session, but after when I call the sendMessage function the session is back to null. Below please find my client class

```<code>package myclient;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javax.websocket.ClientEndpoint;
import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

@ClientEndpoint
public class Client extends Application {
    private static final Logger LOGGER = Logger.getLogger(Client.class.getName());
    private Session session;

    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        System.out.println("Opened Session " + this.session);
    }

    @OnClose
    public void onClose(){
        System.out.println("Closed Session " + this.session);
    }

    @OnMessage
    public void onMessage(String msg){
        System.out.println("Websocket message received! " + msg);
    }

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLClient.fxml"));

        Scene scene = new Scene(root);

        connectToWebSocket();
        stage.setScene(scene);
        stage.show();
    }

    private void connectToWebSocket() {
        System.out.println("Client WebSocket initialized>>  " + this.session);
      WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        try {
            URI uri = URI.create("ws://localhost:8080/Server/endpoint");
            container.connectToServer(this, uri);
        }
        catch (DeploymentException | IOException ex) {
            LOGGER.log(Level.SEVERE, null, ex);
            System.exit(-1);
        }
    }

    public void sendMessage(String message) throws IOException{
        if(this.session != null){
                System.out.println(message + ", " + this.session);
                this.session.getBasicRemote().sendText(message);
        }
        else {
            System.out.println("Session is null");
        }
    }

    public static void main(String[] args) {
        launch(args);
    }

}
</code>```

Any suggestions?

Thanks in advance

答:
I think I now do know the answer to this.

You are probably using tomcat or some other server for this. When you see "tomcat" in this answer, please insert the name of your actually used server.

When a connection to your websocket is opened, tomcat will create an instance of the websocket (your Client) class by itself. This means, the onOpen-Method will be called and it will look as if it was you who created the instance, who opened the connection, when really you did not. Tomcat did.

This in turn means, that when you call sendMessage on your Client instance, the session will be null, because this object never connected anywhere.

Oh, and you don't have access to the connected instance that was created by tomcat.

One way of fixing this would be to do all the work inside the onOpen-Method, however that is not practical. You may want to put the work in another method and call it from onOpen. That way, the instance created by tomcat will do the necessary work.

In my project I needed to poll on an MQTT-Topic and render the data on a website (university assignment). I did the polling in a separate class, resulting in hard to debug errors whenever trying to send received data with my sendMessage-method.

I hope this answer does clear this up a little, if not for you, maybe at least for future generations having the same university assignment...

Body:
I am using websockets for the first time on a javafx project, when I start the program the session is set to the local variable session, but after when I call the sendMessage function the session is back to null. Below please find my client class

package myclient;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javax.websocket.ClientEndpoint;
import javax.websocket.ContainerProvider;
import javax.websocket.DeploymentException;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

@ClientEndpoint
public class Client extends Application {
    private static final Logger LOGGER = Logger.getLogger(Client.class.getName());
    private Session session;

    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        System.out.println("Opened Session " + this.session);
    }

    @OnClose
    public void onClose(){
        System.out.println("Closed Session " + this.session);
    }

    @OnMessage
    public void onMessage(String msg){
        System.out.println("Websocket message received! " + msg);
    }

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("FXMLClient.fxml"));

        Scene scene = new Scene(root);

        connectToWebSocket();
        stage.setScene(scene);
        stage.show();
    }

    private void connectToWebSocket() {
        System.out.println("Client WebSocket initialized>>  " + this.session);
      WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        try {
            URI uri = URI.create("ws://localhost:8080/Server/endpoint");
            container.connectToServer(this, uri);
        }
        catch (DeploymentException | IOException ex) {
            LOGGER.log(Level.SEVERE, null, ex);
            System.exit(-1);
        }
    }

    public void sendMessage(String message) throws IOException{
        if(this.session != null){
                System.out.println(message + ", " + this.session);
                this.session.getBasicRemote().sendText(message);
        }
        else {
            System.out.println("Session is null");
        }
    }

    public static void main(String[] args) {
        launch(args);
    }

}

Any suggestions?

Thanks in advance


问:
How do we insert \n every n-character or/and after n-th space in a string in R?
On SO I found a solution which helps to insert a value/character every n-th character in a string:

(?=(?:.{n})+$)

But it will be more reasonable to insert a value (for example, tabulation sign or \n) every n-th space, so the word won't be splitted. What are the possible ways to editing this regex?

I did my cluster analysis and now I want to attach labels to a dendrogram. Consider that the labels are very long strings like:

```<code>tibble(
   id = d2022_1,
   label = "A very long label for the dendro that should be splitted so it will look nicely in the picture"
)
</code>```

And I would like to have it tabulated/splited by rows, so I want to insert \n:

A very long label for the dendro\nthat should be splitted so\nit will look nicely in the picture

答:
You're reinventing the wheel here. R includes the strwrap function that can split a long string at appropriate word boundaries. This gives a more consistent line length than creating a break after n spaces.

For example, suppose I wanted a line break at most every 12 characters. I can do:

string <- "The big fat cat sat flat upon the mat"

strwrap(string, width = 12)
#> [1] "The big fat" "cat sat"     "flat upon"   "the mat"
```
<p>If you want newlines instead of split strings, just paste the result using collapse:</p>
<pre class="lang-r prettyprint-override"><code>paste(strwrap(string, width = 12), collapse = "\n")
[1] "The big fat\ncat sat\nflat upon\nthe mat"
</code>```

EDIT

Using the newly added example:

df <- tibble(
  id = "d2022_1",
  label = rep("A very long label for the dendro that should be splitted so it will look nicely in the picture", 2)
)

df
#> # A tibble: 2 x 2
#>   id      label
#>   <chr>   <chr>
#> 1 d2022_1 A very long label for the dendro that should be splitted so it will look nic~
#> 2 d2022_1 A very long label for the dendro that should be splitted so it will look nic~

df %>% mutate(label = sapply(label, function(x) paste(strwrap(x, 20), collapse = "\n")))
#> # A tibble: 2 x 2
#>   id      label
#>   <chr>   <chr>
#> 1 d2022_1 "A very long label\nfor the dendro that\nshould be splitted\nso it will look~
#> 2 d2022_1 "A very long label\nfor the dendro that\nshould be splitted\nso it will look~
```

Body:
On SO I found a solution which helps to insert a value/character every n-th character in a string:

(?=(?:.{n})+$)

But it will be more reasonable to insert a value (for example, tabulation sign or \n) every n-th space, so the word won't be splitted. What are the possible ways to editing this regex?

I did my cluster analysis and now I want to attach labels to a dendrogram. Consider that the labels are very long strings like:

tibble(
   id = d2022_1,
   label = "A very long label for the dendro that should be splitted so it will look nicely in the picture"
)

And I would like to have it tabulated/splited by rows, so I want to insert \n:

A very long label for the dendro\nthat should be splitted so\nit will look nicely in the picture

Body:
You're reinventing the wheel here. R includes the strwrap function that can split a long string at appropriate word boundaries. This gives a more consistent line length than creating a break after n spaces.

For example, suppose I wanted a line break at most every 12 characters. I can do:

string <- "The big fat cat sat flat upon the mat"

strwrap(string, width = 12)
#> [1] "The big fat" "cat sat"     "flat upon"   "the mat"

If you want newlines instead of split strings, just paste the result using collapse:

paste(strwrap(string, width = 12), collapse = "\n")
[1] "The big fat\ncat sat\nflat upon\nthe mat"

EDIT

Using the newly added example:

df <- tibble(
  id = "d2022_1",
  label = rep("A very long label for the dendro that should be splitted so it will look nicely in the picture", 2)
)

df
#> # A tibble: 2 x 2
#>   id      label
#>   <chr>   <chr>
#> 1 d2022_1 A very long label for the dendro that should be splitted so it will look nic~
#> 2 d2022_1 A very long label for the dendro that should be splitted so it will look nic~

df %>% mutate(label = sapply(label, function(x) paste(strwrap(x, 20), collapse = "\n")))
#> # A tibble: 2 x 2
#>   id      label
#>   <chr>   <chr>
#> 1 d2022_1 "A very long label\nfor the dendro that\nshould be splitted\nso it will look~
#> 2 d2022_1 "A very long label\nfor the dendro that\nshould be splitted\nso it will look~


问:
How can update a object state in inputs ? (React js Hooks)
I'm new in React and I saw a lot of topics about updateo bject state but in my case I continue with erros.

I have a object useSate and I want update every time my input changes.
I have tried the spread operator.

My state :

```<code>const [inputs, setInputs] = useState({
    topic: {
      coins: 0,
      money: 0,
      cash: 0,
    }
 })
</code>```

my handle funtion :

```<code>const handleMoney = (e) => {
      setInputs(prevState =>({
        inputs:{
          ...prevState.inputs,
          coins: e.target.value
        }
      }))
}
</code>```

And my form ( is from react boostrap):

```<code>           <Form.Control
             min={0}
             type="number"
             value={inputs.coins}
             onChange={handleMoney }
           />
</code>```

答:
Here is code click to see .If its help please mark as answer</p>
```<code>  const [state, setState] = useState({
    toggle: false,
    topic: {
      coins: 0,
      money: 0,
      cash: 0,
    }
  });

  const onHandleChange = (e) => {
    const { name, value } = e.target;
    setState(pre => ({
      ...pre,
      topic: {
        ...pre.topic,
        [name]: value
      }
    }))
  }

  return (
    <div className="App">
      <p>Coins : {state.topic.coins} </p>
      <p>Money : {state.topic.money} </p>
      <p>Cash : {state.topic.cash} </p>
      <input type="number" name='coins' onChange={onHandleChange} value={state.topic.coins} />
      <input type="number" name='money' onChange={onHandleChange} value={state.topic.money} />
      <input type="number" name='cash' onChange={onHandleChange} value={state.topic.cash} />
    </div>
  );
</code>```

Body:
I'm new in React and I saw a lot of topics about updateo bject state but in my case I continue with erros.

I have a object useSate and I want update every time my input changes.
I have tried the spread operator.

My state :

const [inputs, setInputs] = useState({
    topic: {
      coins: 0,
      money: 0,
      cash: 0,
    }
 })

my handle funtion :

const handleMoney = (e) => {
      setInputs(prevState =>({
        inputs:{
          ...prevState.inputs,
          coins: e.target.value
        }
      }))
}

And my form ( is from react boostrap):

           <Form.Control
             min={0}
             type="number"
             value={inputs.coins}
             onChange={handleMoney }
           />

Body:
Here is code click to see .If its help please mark as answer

  const [state, setState] = useState({
    toggle: false,
    topic: {
      coins: 0,
      money: 0,
      cash: 0,
    }
  });

  const onHandleChange = (e) => {
    const { name, value } = e.target;
    setState(pre => ({
      ...pre,
      topic: {
        ...pre.topic,
        [name]: value
      }
    }))
  }

  return (
    <div className="App">
      <p>Coins : {state.topic.coins} </p>
      <p>Money : {state.topic.money} </p>
      <p>Cash : {state.topic.cash} </p>
      <input type="number" name='coins' onChange={onHandleChange} value={state.topic.coins} />
      <input type="number" name='money' onChange={onHandleChange} value={state.topic.money} />
      <input type="number" name='cash' onChange={onHandleChange} value={state.topic.cash} />
    </div>
  );


问:
How do I convert docker-compose configuration to dockerfile
I am a bit confused I was trying to convert dockercompose of elastic kibana to dockerfile. But networking part and connectivity part is bit confusing for me. Can anyone help me with conversion and a bit of explanation.

Thanks a lot!

```<code>version: "3.0"

services:
  elasticsearch:
    container_name: es-container
    image: docker.elastic.co/elasticsearch/elasticsearch:6.5.4
    environment:
      - xpack.security.enabled=true
      - "discovery.type=single-node"
    networks:
      - es-net
    ports:
      - 9200:9200
  kibana:
    container_name: kb-container
    image: docker.elastic.co/kibana/kibana:6.5.4
    environment:
      - ELASTICSEARCH_HOSTS=http://es-container:9200
    networks:
      - es-net
    depends_on:
      - elasticsearch
    ports:
      - 5601:5601

networks:
  es-net:
    driver: bridge
</code>```

答:
In that docker-compose.yml file, the only thing that could be built into an image at all are the environment variables, and there's not much benefit to hard-coding your deployment configuration like this.  In particular you cannot force the eventual container name or manually specify the eventual networking configuration in an image.

If you're looking for a compact self-contained description of what to run that you can redistribute, the docker-compose.yml is it.  Don't try to send around images, or focus on trying to have a single container; instead, distribute the docker-compose.yml file as the way to run your application.  I'd consider Compose a standard enough tool that anyone who has Docker already has it and knows how to run docker-compose up -d.

# How to run this application on a different system
# (with Docker and Compose preinstalled):
here$ scp docker-compose.yml there:
here$ ssh there
there$ sudo docker-compose up -d
```

Body:
I am a bit confused I was trying to convert dockercompose of elastic kibana to dockerfile. But networking part and connectivity part is bit confusing for me. Can anyone help me with conversion and a bit of explanation.

Thanks a lot!

version: "3.0"

services:
  elasticsearch:
    container_name: es-container
    image: docker.elastic.co/elasticsearch/elasticsearch:6.5.4
    environment:
      - xpack.security.enabled=true
      - "discovery.type=single-node"
    networks:
      - es-net
    ports:
      - 9200:9200
  kibana:
    container_name: kb-container
    image: docker.elastic.co/kibana/kibana:6.5.4
    environment:
      - ELASTICSEARCH_HOSTS=http://es-container:9200
    networks:
      - es-net
    depends_on:
      - elasticsearch
    ports:
      - 5601:5601

networks:
  es-net:
    driver: bridge


问:
How to code a BAT file to always run as admin mode?
I have this line inside my BAT file:

```<code>"Example1Server.exe"
</code>```

I would like to execute this in Administrator mode. How to modify the bat code to run this as admin?

Is this correct? Do I need to put the quotes?

```<code>runas /user:Administrator invis.vbs Example1Server.exe
</code>```

答:
I Tested @Sire's answer on Windows 11, and it works like a charm. It's worth mentioning that using cmd /k - as @Sire has used - will keep the Administrator CMD open after it finishes running. Using cmd /c instead will close the window when it's over with the batch file.

set "params=%*"
cd /d "%~dp0" && ( if exist "%temp%\getadmin.vbs" del "%temp%\getadmin.vbs" ) && fsutil dirty query %systemdrive% 1>nul 2>nul || (  echo Set UAC = CreateObject^("Shell.Application"^) : UAC.ShellExecute "cmd.exe", "/c cd ""%~sdp0"" && %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs" && "%temp%\getadmin.vbs" && exit /B )
```

Body:
I have this line inside my BAT file:

"Example1Server.exe"

I would like to execute this in Administrator mode. How to modify the bat code to run this as admin?

Is this correct? Do I need to put the quotes?

runas /user:Administrator invis.vbs Example1Server.exe


问:
How can I use "react-owl-carousel-rtl"?
I want to install react-owl-carousel-rtl
I followed the instructions at https://www.npmjs.com/package/react-owl-carousel-rtl

But still it does not work for me because of the direction: rtl

This is the code I wrote-

```<code>import OwlCarousel from "react-owl-carousel";
import "owl.carousel / dist / assets / owl.carousel.css";
import "owl.carousel / dist / assets / owl.theme.default.css";

<OwlCarousel loop={false} rtlClass="owl-rtl" margin={10}>
  <div>
    <h4>1</h4>
  </div>
  <div>
    <h4>2</h4>
  </div>
  <div>
    <h4>3</h4>
  </div>
  <div>
    <h4>4</h4>
  </div>
  <div>
    <h4>5</h4>
  </div>
</OwlCarousel>
</code>```

Regards

答:
I ran into this problem and unfortunately, the documentation was wrong!

so you need to change the import and add rtl property like this:

```<code>import OwlCarousel from "react-owl-carousel-rtl";
import "owl.carousel/dist/assets/owl.carousel.css";
import "owl.carousel/dist/assets/owl.theme.default.css";

<OwlCarousel loop={false} rtlClass="owl-rtl" margin={10} rtl={true}>
  <div>
    <h4>1</h4>
  </div>
  <div>
    <h4>2</h4>
  </div>
  <div>
    <h4>3</h4>
  </div>
  <div>
    <h4>4</h4>
  </div>
  <div>
    <h4>5</h4>
  </div>
</OwlCarousel>
</code>```

that worked for me :)

Title: How can I use "react-owl-carousel-rtl"?

Body:
I want to install react-owl-carousel-rtl
I followed the instructions at https://www.npmjs.com/package/react-owl-carousel-rtl

But still it does not work for me because of the direction: rtl

This is the code I wrote-

import OwlCarousel from "react-owl-carousel";
import "owl.carousel / dist / assets / owl.carousel.css";
import "owl.carousel / dist / assets / owl.theme.default.css";

<OwlCarousel loop={false} rtlClass="owl-rtl" margin={10}>

1

2

3

4

5

</OwlCarousel>

Regards

Body:
I ran into this problem and unfortunately, the documentation was wrong!

so you need to change the import and add rtl property like this:

import OwlCarousel from "react-owl-carousel-rtl";
import "owl.carousel/dist/assets/owl.carousel.css";
import "owl.carousel/dist/assets/owl.theme.default.css";

<OwlCarousel loop={false} rtlClass="owl-rtl" margin={10} rtl={true}>
  <div>
    <h4>1</h4>
  </div>
  <div>
    <h4>2</h4>
  </div>
  <div>
    <h4>3</h4>
  </div>
  <div>
    <h4>4</h4>
  </div>
  <div>
    <h4>5</h4>
  </div>
</OwlCarousel>

that worked for me :)


问:
Executing a timeout prior to the defined delay
Say I have the following JavaScript code (in global context):

```<code>var t = setTimeout(f, a); // f is an arbitrary function, a an arbitrary timeout
</code>```

One can now cancel the set timeout:

```<code>clearTimeout(t);
</code>```

But is it also possible to execute the timeout prior to it normally firing?

E.g.:

```<code>var func = getFunctionFromTimeout(t); // Does a function like this exists?
clearTimeout(t);
func();
</code>```

or

```<code>executeAndClearTimeout(t); // Does this one?
</code>```

答:
On the server side, node.js setTimeout provides more of a object than an id.  This is undocumented territory, I think.

Of course, using these internals might be hazardous in the sense that they could change as node develops.

```<code>node
> function x(){ console.log("hello"); }
> z = setTimeout(x,100000)
{ _idleTimeout: 100000,
  _onTimeout: [Function: x],
  _idlePrev:
   { repeat: 100,
     _idleNext: [Circular],
     _idlePrev: [Circular],
     callback: [Function] },
  _idleNext:
   { repeat: 100,
     _idleNext: [Circular],
     _idlePrev: [Circular],
     callback: [Function] },
  _idleStart: Thu, 18 Aug 2011 11:11:48 GMT }
>
</code>```

looks like you could just save z._onTimeout, clear the Timeout, and call _onTimeout  --- but as I said, might break some day.

Also, nodeJS timeouts dont always fire when they should, but can be aligned to your CPUHZ grid.... if you are running linux with 100hz, you get 10ms resolution.  I've seen them fire either early or late, in comparison with timers provided by hrtime.

Body:
Say I have the following JavaScript code (in global context):

var t = setTimeout(f, a); // f is an arbitrary function, a an arbitrary timeout

One can now cancel the set timeout:

clearTimeout(t);

But is it also possible to execute the timeout prior to it normally firing?

E.g.:

var func = getFunctionFromTimeout(t); // Does a function like this exists?
clearTimeout(t);
func();

or

executeAndClearTimeout(t); // Does this one?

Body:
On the server side, node.js setTimeout provides more of a object than an id.  This is undocumented territory, I think.

Of course, using these internals might be hazardous in the sense that they could change as node develops.

node
> function x(){ console.log("hello"); }
> z = setTimeout(x,100000)
{ _idleTimeout: 100000,
  _onTimeout: [Function: x],
  _idlePrev:
   { repeat: 100,
     _idleNext: [Circular],
     _idlePrev: [Circular],
     callback: [Function] },
  _idleNext:
   { repeat: 100,
     _idleNext: [Circular],
     _idlePrev: [Circular],
     callback: [Function] },
  _idleStart: Thu, 18 Aug 2011 11:11:48 GMT }
>

looks like you could just save z._onTimeout, clear the Timeout, and call _onTimeout  --- but as I said, might break some day.

Also, nodeJS timeouts dont always fire when they should, but can be aligned to your CPUHZ grid.... if you are running linux with 100hz, you get 10ms resolution.  I've seen them fire either early or late, in comparison with timers provided by hrtime.


问:
how to sort item of alphanumeric type of string using sort method in kotlin
This is my data

```<code>val data = ArrayList<Product>()
        data.add(Product(it=1,type = "Ait 45"))
        data.add(Product(it=2,type = "Ait 35"))
        data.add(Product(it=3,type = "Ait 65"))
        data.add(Product(it=4,type = "Ait 325"))
        data.add(Product(it=5,type = "Ait 42"))
</code>```

I am trying sort data based on type in descending order which is string type

expected output after sort

data should  =  {(it=2,type = "Ait 35"),(it=5,type = "Ait 42"),(it=1,type = "Ait 45"),(it=3,type = "Ait 65"),(it=4,type = "Ait 325")}

Please help me how to sort item using sort method in kotlin

答:
You can use List<T>.sortedBy() function from the standard library which returns a new list with the sorted elements or MutableList<T>.sortBy() which sorts the elements in-place (moves the current list's items around to sort them).

Both of these functions sortedBy and sortBy have their sortedByDescending and sortByDescending counterparts.

Note that the following code will sort the strings by text, if you want to sort by the integer value contained into the "type" string you'd need to convert that value into an integer by manipulating the string contents.

data class Product(val it: Int,val type: String)

fun main() {
    val data = ArrayList<Product>()
    data.add(Product(it=1,type = "Ait 45"))
    data.add(Product(it=2,type = "Ait 35"))
    data.add(Product(it=3,type = "Ait 65"))
    data.add(Product(it=4,type = "Ait 325"))
    data.add(Product(it=5,type = "Ait 42"))
    println(data.sortedBy { it.type})
    println(data.sortedByDescending { it.type})
}
```

See the code in action inside the Kotlin playground

Body:
This is my data

val data = ArrayList<Product>()
        data.add(Product(it=1,type = "Ait 45"))
        data.add(Product(it=2,type = "Ait 35"))
        data.add(Product(it=3,type = "Ait 65"))
        data.add(Product(it=4,type = "Ait 325"))
        data.add(Product(it=5,type = "Ait 42"))

I am trying sort data based on type in descending order which is string type

expected output after sort

data should  =  {(it=2,type = "Ait 35"),(it=5,type = "Ait 42"),(it=1,type = "Ait 45"),(it=3,type = "Ait 65"),(it=4,type = "Ait 325")}

Please help me how to sort item using sort method in kotlin

Body:
You can use List<T>.sortedBy() function from the standard library which returns a new list with the sorted elements or MutableList<T>.sortBy() which sorts the elements in-place (moves the current list's items around to sort them).

Both of these functions sortedBy and sortBy have their sortedByDescending and sortByDescending counterparts.

Note that the following code will sort the strings by text, if you want to sort by the integer value contained into the "type" string you'd need to convert that value into an integer by manipulating the string contents.

data class Product(val it: Int,val type: String)

fun main() {
    val data = ArrayList<Product>()
    data.add(Product(it=1,type = "Ait 45"))
    data.add(Product(it=2,type = "Ait 35"))
    data.add(Product(it=3,type = "Ait 65"))
    data.add(Product(it=4,type = "Ait 325"))
    data.add(Product(it=5,type = "Ait 42"))
    println(data.sortedBy { it.type})
    println(data.sortedByDescending { it.type})
}

See the code in action inside the Kotlin playground


问:
Excel formula to count non empty cells in a column for distinct values in an other column
I have a list of members in Excel with their date of deaths (date of death not populated, if member is still alive). For one member there can be more lines because there can be more benefit lines associated. I would like to count the number of distinct members who are dead.
An example of my list

As a result, I would like to get 2, the count of distinct dead members in my list.

答:
Excel 2021 supports the dynamic array functions.

You can compose FILTER, UNIQUE and COUNT functions.

IF your IDs are in column A and the dates are in column B.

FILTER out items in column A, when the column B is Truthy (non-empty).

Apply the UNIQUE function.

Apply the COUNT function.

The following formula will produce the count of unique IDs with non-empty dates:

```<code>=COUNT(UNIQUE(FILTER(A:A,B:B)))
</code>```

Body:
Excel 2021 supports the dynamic array functions.

You can compose FILTER, UNIQUE and COUNT functions.

IF your IDs are in column A and the dates are in column B.

FILTER out items in column A, when the column B is Truthy (non-empty).

Apply the UNIQUE function.

Apply the COUNT function.

The following formula will produce the count of unique IDs with non-empty dates:

=COUNT(UNIQUE(FILTER(A:A,B:B)))


问:
How to manipulate API results in JavaScript?
I am learning to use an API and I need some help.

I chose yahoo finance API and I'm trying to interpret the results. For this, I want to just access some of the data and display it on screen. I don't really know how I should do this. What is the correct method?

var configuration = {
  method: "GET",
  headers: {
    "x-rapidapi-host": "yh-finance.p.rapidapi.com",
    "x-rapidapi-key": "9ac5b9a91dmshc51815b4efc8942p149234jsnb64a2f32b56d",
  },
};
var url =
  "https://yh-finance.p.rapidapi.com/stock/v2/get-chart?interval=1d&symbol=AMRN&range=1d&region=US";

var name = document.querySelector("stock-name");
var price = document.querySelector("stock-price");
var high = document.querySelector("stock-high");
var currency = document.querySelector("stock-currency");

fetch(url, configuration)
  .then(function (response) {
    if (response.status !== 200) {
      console.log(
        "Looks like there was a problem. Status Code: " + response.status
      );
      return;
    }

    // Examine the text in the response
    response.json().then(function (data) {
      console.log(data);
      displayData(data);
    });
  })
  .catch(function (err) {
    console.log("Fetch Error :-S", err);
  });

//displaying some data from API
function displayData(stockData) {
  name.innerHTML = "Stock name:" + Object.keys(stockData.meta.symbol);
  price.innetHTML = "Stock's price:" + stockData.priceHint;
  high.innerHTML = "Stock's high:" + stockData.indicators.quote[0].high[0];
  currency.innerHTML = "Stock's currecy:" + stockData.meta.currency;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> </div>
      <div><h3 id = "stock-name"></h3>
        <h3 id = "stock-price"></h3>
        <h3  id = "stock-high"></h3>
        <h3 id = "stock-currency"></h3>
      </div></code>```

I am not a fan of Jquery.

I tried accessing the data from API in the console with:

```<code>console.log(Object.keys(stockData.chart.result[0].meta));

console.log(Object.values(stockData.chart.result[0].meta));
</code>```

to see if I can access it like this, but I can't access one element, like meta[x], only the whole array.

Does anyone know where can I learn more about manipulating data from API? I couldn't find any good information...

答:
you can simple make following changes in you JS file :

```<code>const configuration = {
    method: "GET",
    headers: {
      "x-rapidapi-host": "yh-finance.p.rapidapi.com",
      "x-rapidapi-key": "9ac5b9a91dmshc51815b4efc8942p149234jsnb64a2f32b56d",
    },
  };

const url =
  "https://yh-finance.p.rapidapi.com/stock/v2/get-chart?interval=1d&symbol=AMRN&range=1d&region=US";

const name = document.querySelector("#stock-name");
const price = document.querySelector("#stock-price");
const high = document.querySelector("#stock-high");
const currency = document.querySelector("#stock-currency");

fetch(url, configuration)
  .then(function (response) {
    if (response.status !== 200) {
      console.log(
        "Looks like there was a problem. Status Code: " + response.status
      );
      return;
    }

    // Examine the text in the response
    response.json().then(function (data) {
      console.log(data);
      displayData(data);
    });
  })
  .catch(function (err) {
    console.log("Fetch Error :-S", err);
  });

//displaying some data from API
function displayData(stockData) {
  let metadata = stockData.chart.result[0].meta;
  let indicators =  stockData.chart.result[0].indicators;
  name.innerText = "Stock name:" + metadata.symbol;
  price.innerText = "Stock's price:" + metadata.priceHint;
  high.innerText = "Stock's high:" + indicators.quote[0].high[0];
  currency.innerText = "Stock's currecy:" + metadata.currency;
}

</code>```

here you can choose between innerHTML and innerText, as you just wanted to inject the values I have used the innerText.

Body:
I am learning to use an API and I need some help.

I chose yahoo finance API and I'm trying to interpret the results. For this, I want to just access some of the data and display it on screen. I don't really know how I should do this. What is the correct method?

var configuration = {
  method: "GET",
  headers: {
    "x-rapidapi-host": "yh-finance.p.rapidapi.com",
    "x-rapidapi-key": "9ac5b9a91dmshc51815b4efc8942p149234jsnb64a2f32b56d",
  },
};
var url =
  "https://yh-finance.p.rapidapi.com/stock/v2/get-chart?interval=1d&symbol=AMRN&range=1d&region=US";

var name = document.querySelector("stock-name");
var price = document.querySelector("stock-price");
var high = document.querySelector("stock-high");
var currency = document.querySelector("stock-currency");

fetch(url, configuration)
  .then(function (response) {
    if (response.status !== 200) {
      console.log(
        "Looks like there was a problem. Status Code: " + response.status
      );
      return;
    }

    // Examine the text in the response
    response.json().then(function (data) {
      console.log(data);
      displayData(data);
    });
  })
  .catch(function (err) {
    console.log("Fetch Error :-S", err);
  });

//displaying some data from API
function displayData(stockData) {
  name.innerHTML = "Stock name:" + Object.keys(stockData.meta.symbol);
  price.innetHTML = "Stock's price:" + stockData.priceHint;
  high.innerHTML = "Stock's high:" + stockData.indicators.quote[0].high[0];
  currency.innerHTML = "Stock's currecy:" + stockData.meta.currency;
}

I am not a fan of Jquery.

I tried accessing the data from API in the console with:

console.log(Object.keys(stockData.chart.result[0].meta));

console.log(Object.values(stockData.chart.result[0].meta));

to see if I can access it like this, but I can't access one element, like meta[x], only the whole array.

Does anyone know where can I learn more about manipulating data from API? I couldn't find any good information...

Body:
you can simple make following changes in you JS file :

const configuration = {
    method: "GET",
    headers: {
      "x-rapidapi-host": "yh-finance.p.rapidapi.com",
      "x-rapidapi-key": "9ac5b9a91dmshc51815b4efc8942p149234jsnb64a2f32b56d",
    },
  };

const url =
  "https://yh-finance.p.rapidapi.com/stock/v2/get-chart?interval=1d&symbol=AMRN&range=1d&region=US";

const name = document.querySelector("#stock-name");
const price = document.querySelector("#stock-price");
const high = document.querySelector("#stock-high");
const currency = document.querySelector("#stock-currency");

fetch(url, configuration)
  .then(function (response) {
    if (response.status !== 200) {
      console.log(
        "Looks like there was a problem. Status Code: " + response.status
      );
      return;
    }

    // Examine the text in the response
    response.json().then(function (data) {
      console.log(data);
      displayData(data);
    });
  })
  .catch(function (err) {
    console.log("Fetch Error :-S", err);
  });

//displaying some data from API
function displayData(stockData) {
  let metadata = stockData.chart.result[0].meta;
  let indicators =  stockData.chart.result[0].indicators;
  name.innerText = "Stock name:" + metadata.symbol;
  price.innerText = "Stock's price:" + metadata.priceHint;
  high.innerText = "Stock's high:" + indicators.quote[0].high[0];
  currency.innerText = "Stock's currecy:" + metadata.currency;
}

here you can choose between innerHTML and innerText, as you just wanted to inject the values I have used the innerText.


答:
You can benefit from SUMPRODUCT:

```<code>=SUMPRODUCT((A2:A9&B2:B9<>"")/COUNTIFS(A2:A9;A2:A9&"";B2:B9;B2:B9&"");--(B2:B9<>""))
</code>```

Title: Excel formula to count non empty cells in a column for distinct values in an other column

Body:
I have a list of members in Excel with their date of deaths (date of death not populated, if member is still alive). For one member there can be more lines because there can be more benefit lines associated. I would like to count the number of distinct members who are dead.
An example of my list

As a result, I would like to get 2, the count of distinct dead members in my list.

Body:
You can benefit from SUMPRODUCT:

=SUMPRODUCT((A2:A9&B2:B9<>"")/COUNTIFS(A2:A9;A2:A9&"";B2:B9;B2:B9&"");--(B2:B9<>""))


问:
Font awesome icons are running perfectly in local but not in production in next js
In the Next JS font awesome icons are working perfectly on localhost, but when deployed to vercel it's not appearing. I've the separate font css file along with all fonts and linked it in _app.js

My _app.js file

```<code>import "../styles/style.css";
import "../styles/fontawesome.css";
import "../styles/all.min.css";
import "../styles/bootstrap.min.css";
// import 'bootstrap/dist/css/bootstrap.min.css'
import "../styles/default.css";
import "../styles/meanmenu.css";
import "../styles/not-logged-responsive.css";
import "../styles/responsive.css";
import "../styles/nprogress.css";
import Router from 'next/router';
import NProgress from 'nprogress';

function MyApp({ Component, pageProps }) {

  return <Component {...pageProps} />;
}

export default MyApp;
</code>```

答:
I assume you've followed the official docs and added config.autoAddCss = false and everything.

The next problem can be related to Webpack. Check your package.json and see if there's something like

```<code>"sideEffects": true
// or
"sideEffects": [
   "*.css"
]
</code>```

Font-Awesome icon loading is based on side effects and require something like:

```<code>"sideEffects": [
   "*.css",
   "your-file-with-fa-imports.js"
]
</code>```

By your-file-with-fa-imports.js I mean a file where you have

```<code>// ^
import {library} from "@fortawesome/fontawesome-svg-core"
import {faUser} from "@fortawesome/free-solid-svg-icons"

library.add(faUser)
</code>```

The above lines may vary, respectful to the way you load FA6 icons and how your NextjS is configured. But now you have a direction, at least.

Body:
In the Next JS font awesome icons are working perfectly on localhost, but when deployed to vercel it's not appearing. I've the separate font css file along with all fonts and linked it in _app.js

My _app.js file

import "../styles/style.css";
import "../styles/fontawesome.css";
import "../styles/all.min.css";
import "../styles/bootstrap.min.css";
// import 'bootstrap/dist/css/bootstrap.min.css'
import "../styles/default.css";
import "../styles/meanmenu.css";
import "../styles/not-logged-responsive.css";
import "../styles/responsive.css";
import "../styles/nprogress.css";
import Router from 'next/router';
import NProgress from 'nprogress';

function MyApp({ Component, pageProps }) {

  return <Component {...pageProps} />;
}

export default MyApp;

Body:
I assume you've followed the official docs and added config.autoAddCss = false and everything.

The next problem can be related to Webpack. Check your package.json and see if there's something like

"sideEffects": true
// or
"sideEffects": [
   "*.css"
]

Font-Awesome icon loading is based on side effects and require something like:

"sideEffects": [
   "*.css",
   "your-file-with-fa-imports.js"
]

By your-file-with-fa-imports.js I mean a file where you have

// ^
import {library} from "@fortawesome/fontawesome-svg-core"
import {faUser} from "@fortawesome/free-solid-svg-icons"

library.add(faUser)

The above lines may vary, respectful to the way you load FA6 icons and how your NextjS is configured. But now you have a direction, at least.


问:
Problem inserting into an SQL Server Database with Java
I have a problem because I can't insert into an sql server database:

driver:[Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]

```<code>public int sendCabecera(String tpv, Date date, String time, int NumPers, int CodOfi) {

    java.sql.DatabaseMetaData dm = null;
    int result = 0;

    try {
        connection = this.getConnection();
        if (connection != null) {
            dm = connection.getMetaData();

            Statement select = connection.createStatement();

            String sql="INSERT INTO TCabecerasSolicitudes(CodigoTPV, FechaYHora, Hora, NumeroPersonas, CodigoOficina) VALUES ('001','17/08/2011 16:00','De 16 a 17',0, '001');";

            select.execute(sql);

//{.... catch ... etc }
</code>```

Well I have tried all execute update and execute alone and I always het the same error:
"Cannot insert NULL" this is the first comlumn which is a primary key and normally auto-increment so I just ignore it but it doesn't work why???

Thanks a lot in advance,

EDIT: problem solved I turned out the key in question was not autoincrement

答:
It seems most likely that you have a column in your TCabecerasSolicitudes table that is defined as NOT NULL but which is not listed in your insert statement (ie not one of CodigoTPV, FechaYHora, Hora, NumeroPersonas, CodigoOficina).

Because you have not provided a value for that column in your query and it's NOT NULL, the statement is exploding.

Body:
I have a problem because I can't insert into an sql server database:

driver:[Microsoft][SQLServer 2000 Driver for JDBC][SQLServer]

public int sendCabecera(String tpv, Date date, String time, int NumPers, int CodOfi) {

    java.sql.DatabaseMetaData dm = null;
    int result = 0;

    try {
        connection = this.getConnection();
        if (connection != null) {
            dm = connection.getMetaData();

            Statement select = connection.createStatement();

            String sql="INSERT INTO TCabecerasSolicitudes(CodigoTPV, FechaYHora, Hora, NumeroPersonas, CodigoOficina) VALUES ('001','17/08/2011 16:00','De 16 a 17',0, '001');";

            select.execute(sql);

//{.... catch ... etc }

Well I have tried all execute update and execute alone and I always het the same error:
"Cannot insert NULL" this is the first comlumn which is a primary key and normally auto-increment so I just ignore it but it doesn't work why???

Thanks a lot in advance,

EDIT: problem solved I turned out the key in question was not autoincrement


问:
CSS box-shadow inset gap between border when collapsed border
I have a table with border-collapse: collapse set, and the result is an odd gap between the the box-shadow inset and the border, which gets bigger with bigger border widths.  How do I avoid this weirdness?  This is on Chrome, by the way.

HTML:

```<code><table class="theTable">
  <tr>
    <td class="weirdGap">
      unexpected gap
      <br>
      unexpected gap
    </td>
  </tr>
</table>
</code>```

CSS:

```<code>.theTable {
  border-collapse: collapse;

}

.weirdGap {
  box-shadow: inset 0 0 6px red;
  border: 5px solid blue;
}
</code>```

Here's the jsFiddle
http://jsfiddle.net/ukhgK/11/

答:
This problem still persists, so here’s a work-around that might work depending on your needs: Instead of border-collapse: collapse; create all borders of the table using box-shadow:

```<code>box-shadow:
    inset 1px 0 black,
    inset 0 1px black,
    1px 0 0 0 black,
    0 1px 0 0 black,
    1px 1xp 0 0 black;
</code>```

This leads to the borders on the right on bottom protruding out from the cell’s box whereas the borders on the top and left stay within the box. With cell-spacing: 0, borders of neighboring boxes fall on-top of each other, creating a similar effect to border-collapse: collapse. You can now use additional box shadows to achieve the effects you want, just remember that you need to repeat all existing shadows you want to keep. (I.e. if you have box-shadow properties on the same cell from two different rules, they’re not combined automatically and you need to write the rule that combines them manually.)

Body:
I have a table with border-collapse: collapse set, and the result is an odd gap between the the box-shadow inset and the border, which gets bigger with bigger border widths.  How do I avoid this weirdness?  This is on Chrome, by the way.

HTML:

      unexpected gap

      unexpected gap

CSS:

.theTable {
  border-collapse: collapse;

}

.weirdGap {
  box-shadow: inset 0 0 6px red;
  border: 5px solid blue;
}

Here's the jsFiddle
http://jsfiddle.net/ukhgK/11/

Body:
This problem still persists, so here’s a work-around that might work depending on your needs: Instead of border-collapse: collapse; create all borders of the table using box-shadow:

box-shadow:
    inset 1px 0 black,
    inset 0 1px black,
    1px 0 0 0 black,
    0 1px 0 0 black,
    1px 1xp 0 0 black;

This leads to the borders on the right on bottom protruding out from the cell’s box whereas the borders on the top and left stay within the box. With cell-spacing: 0, borders of neighboring boxes fall on-top of each other, creating a similar effect to border-collapse: collapse. You can now use additional box shadows to achieve the effects you want, just remember that you need to repeat all existing shadows you want to keep. (I.e. if you have box-shadow properties on the same cell from two different rules, they’re not combined automatically and you need to write the rule that combines them manually.)


问:
"There was an error parsing the body" error on requesting endpoint in FastAPI
I have implemented a endpoint in FastAPI and I am testing it from Postman. But whenever I send request I get this error "There was an error parsing the body", while searching for the error I found a solution somewhere that I need to have python-multipart installed, this package is already installed but I am still facing this error.
Following is my code:

```<code>@router.put('/user')
def update_user(user_data: dict):
    from crain.uma import update_user
    user_id = user_data['id']
    update_user(user_id, user_data)
    return {"message": "DONE"}

</code>```

The endpoint except a dict like this:

```<code>user_data =    {
      "username":"admin",
      "id":"2d06aa3b-c25a-4499-948a-86341ac4adc5",
      "email":null,
      "firstName":"admin",
      "lastName":"admin",
      "createdTimestamp":1638268009973
   },
</code>```

答:
in postman switch to raw data (currently you are in form-data).

then insert your desired payload:

{
      "username":"admin",
      "id":"2d06aa3b-c25a-4499-948a-86341ac4adc5",
      "email":null,
      "firstName":"admin",
      "lastName":"admin",
      "createdTimestamp":1638268009973
}
```
<p>and fire the request.</p>
<p>BTW, when you say</p>
<blockquote>
<p>The endpoint except a dict like this:</p>
</blockquote>
```user_data = {
      "username":"admin",
      "id":"2d06aa3b-c25a-4499-948a-86341ac4adc5",
      "email":null,
      "firstName":"admin",
      "lastName":"admin",
      "createdTimestamp":1638268009973
},
```

you actually mean the endpoint expect only the dictionary part, because user_data is simply a variable name in your python code, completely unrelated to any request configuration.

the reason i specify it is because you wrote it as a key you the postman's request form-data (the picture you uploaded)

Body:
I have implemented a endpoint in FastAPI and I am testing it from Postman. But whenever I send request I get this error "There was an error parsing the body", while searching for the error I found a solution somewhere that I need to have python-multipart installed, this package is already installed but I am still facing this error.
Following is my code:

@router.put('/user')
def update_user(user_data: dict):
    from crain.uma import update_user
    user_id = user_data['id']
    update_user(user_id, user_data)
    return {"message": "DONE"}

The endpoint except a dict like this:

user_data =    {
      "username":"admin",
      "id":"2d06aa3b-c25a-4499-948a-86341ac4adc5",
      "email":null,
      "firstName":"admin",
      "lastName":"admin",
      "createdTimestamp":1638268009973
   },

Body:
in postman switch to raw data (currently you are in form-data).

then insert your desired payload:

{
      "username":"admin",
      "id":"2d06aa3b-c25a-4499-948a-86341ac4adc5",
      "email":null,
      "firstName":"admin",
      "lastName":"admin",
      "createdTimestamp":1638268009973
}

and fire the request.

BTW, when you say

The endpoint except a dict like this:

user_data = {
      "username":"admin",
      "id":"2d06aa3b-c25a-4499-948a-86341ac4adc5",
      "email":null,
      "firstName":"admin",
      "lastName":"admin",
      "createdTimestamp":1638268009973
},

you actually mean the endpoint expect only the dictionary part, because user_data is simply a variable name in your python code, completely unrelated to any request configuration.

the reason i specify it is because you wrote it as a key you the postman's request form-data (the picture you uploaded)


问:
DAX Duplicate Count in measure with Previous Date
I Need a DAX measure where date wise only duplicate values will return. The date will search always previous + Current Date. Ex: on date 2/2/2022, it will check both 2/1/2022 and 2/2/2022 and return only duplicate count.

Below Data set Count of on 2/2/2022 Duplicate will return 4. which is highlighted in

Total Output will be:

I already write a DAX but it just return unique count not only duplicate:

```<code>CALCULATE(DISTINCTCOUNT(data[Wrap-up]),DATESINPERIOD(data[Date],MAX(data[Date]),-2,DAY))
</code>```

答:
```<code>MyMeasure :=
VAR ThisDate =
    MAX( data[Date] )
VAR MyTable =
    SUMMARIZE(
        FILTER( ALL( data ), data[Date] <= ThisDate && data[Date] >= ThisDate - 1 ),
        data[Wrap-up],
        "MyCount", COUNTROWS( data )
    )
RETURN
    SUMX( MyTable, IF( [MyCount] > 1, [MyCount] ) )
</code>```

Body:
I Need a DAX measure where date wise only duplicate values will return. The date will search always previous + Current Date. Ex: on date 2/2/2022, it will check both 2/1/2022 and 2/2/2022 and return only duplicate count.

Below Data set Count of on 2/2/2022 Duplicate will return 4. which is highlighted in

Total Output will be:

I already write a DAX but it just return unique count not only duplicate:

CALCULATE(DISTINCTCOUNT(data[Wrap-up]),DATESINPERIOD(data[Date],MAX(data[Date]),-2,DAY))