问:
warning: incompatible pointer types passing 'char *' to parameter of type 'FILE *' (aka 'struct __sFILE *')

I am trying to execute my code but I seem to get this incompatible warning.

```<code>int Read_Data_File(void)
{
    FILE *ptr_file;
    char *end = "0.0.0.0 none";
    char *buf;
    int endLoop = 0;

    ptr_file = fopen("CS222_Inet.txt", "r");

    if (!ptr_file)
        return 1;

    int i = 0;

    while (!feof(ptr_file)){
        addr[i]=(struct address_t *)malloc(sizeof(struct address_t));
        fscanf(ptr_file,"%s",buf);
        if(!(strcmp(buf, end) == 0)){
            fscanf(buf,"%d %d %d %d %s", &addr[i]->IP1, &addr[i]->IP2,  &addr[i]->IP3, &addr[i]->IP4, addr[i]->name);
            n++;
        }
        i++;
    }

    fclose(ptr_file);
    return 0;
}
</code>```

I want this program to read the file and also store my structure type into my buf pointer.

Warning Output:

```<code>project.c:65:11: warning: incompatible pointer types passing 'char *' to
      parameter of type 'FILE *' (aka 'struct __sFILE *')
      [-Wincompatible-pointer-types]
                        fscanf(buf,"%d %d %d %d %s", &addr[i]->IP1, &add...
                               ^~~
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/usr/include/stdio.h:250:30: note:
      passing argument to parameter here
int      fscanf(FILE * __restrict, const char * __restrict, ...) __scanf...
                                 ^
</code>```

答:
Like the error says: fscanf expects its first argument to be a FILE *, whereas you're passing it a character buffer.
If you want to parse a character buffer using the scanf family of functions, use sscanf

Body:
I am trying to execute my code but I seem to get this incompatible warning.

int Read_Data_File(void)
{
    FILE *ptr_file;
    char *end = "0.0.0.0 none";
    char *buf;
    int endLoop = 0;

    ptr_file = fopen("CS222_Inet.txt", "r");

    if (!ptr_file)
        return 1;

    int i = 0;

    while (!feof(ptr_file)){
        addr[i]=(struct address_t *)malloc(sizeof(struct address_t));
        fscanf(ptr_file,"%s",buf);
        if(!(strcmp(buf, end) == 0)){
            fscanf(buf,"%d %d %d %d %s", &addr[i]->IP1, &addr[i]->IP2,  &addr[i]->IP3, &addr[i]->IP4, addr[i]->name);
            n++;
        }
        i++;
    }

    fclose(ptr_file);
    return 0;
}

I want this program to read the file and also store my structure type into my buf pointer.

Warning Output:

project.c:65:11: warning: incompatible pointer types passing 'char *' to
      parameter of type 'FILE *' (aka 'struct __sFILE *')
      [-Wincompatible-pointer-types]
                        fscanf(buf,"%d %d %d %d %s", &addr[i]->IP1, &add...
                               ^~~
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/usr/include/stdio.h:250:30: note:
      passing argument to parameter here
int      fscanf(FILE * __restrict, const char * __restrict, ...) __scanf...
                                 ^


来源: stackexchange

问:
Pass a div just created by ngFor to a function in Angular
I am producing some divs using ngFor:

```<code><div  *ngFor='let img of images'>
</code>```

I want to pass the div just produced to a function. At first, I tried to just pass a number to the function

```<code><div  *ngFor='let img of images' (being)="ToRunEachTime(img)">
</code>```

where being is a directive like:

```<code>@Directive({
  selector: '[being]'
})

export class beingDirective {
  @Output() being: EventEmitter<any> = new EventEmitter<any>();
  constructor() {}
  ngOnInit() {
     this.being.emit('anything');
  }
}
</code>```

This code works well and I am able to pass img (which is a number) each time to the function ToRunEachTime. However, I wish to pass the whole div which is just created by *ngFor to this function. I tried:

```<code><div  *ngFor='let img of images' (being)="ToRunEachTime($event)">
</code>```

but the function

```<code>ToRunEachTime(event: Event){
var currentdiv= <HTMLDivElement>event.target;
}
</code>```

gives me undefined. Any Help is appreciated!

答:
In your directive you are emitting a string which does not contain the target property

```<code>export class beingDirective {
  @Output() being: EventEmitter<any> = new EventEmitter<any>();
  constructor(private el:ElementRef,private renderer:Renderer2) {}
  ngOnInit() {
     this.being.emit(this.el.nativeElement);
  }
}
</code>```

If you are looking to emit any Browser event you should be adding a HostListener as below and emit that event

```<code>@HostListener('mouseover', ['$event']) onClick(event) {
     this.being.emit(event);
}
</code>```

This will give you the target element. Updated the demo.

LIVE DEMO

ContentLicense: CC BY-SA 3.0

Body:
I am producing some divs using ngFor:

I want to pass the div just produced to a function. At first, I tried to just pass a number to the function

where being is a directive like:

@Directive({
  selector: '[being]'
})

export class beingDirective {
  @Output() being: EventEmitter<any> = new EventEmitter<any>();
  constructor() {}
  ngOnInit() {
     this.being.emit('anything');
  }
}

This code works well and I am able to pass img (which is a number) each time to the function ToRunEachTime. However, I wish to pass the whole div which is just created by *ngFor to this function. I tried:

but the function

ToRunEachTime(event: Event){
var currentdiv= <HTMLDivElement>event.target;
}

gives me undefined. Any Help is appreciated!

Body:
In your directive you are emitting a string which does not contain the target property

export class beingDirective {
  @Output() being: EventEmitter<any> = new EventEmitter<any>();
  constructor(private el:ElementRef,private renderer:Renderer2) {}
  ngOnInit() {
     this.being.emit(this.el.nativeElement);
  }
}

If you are looking to emit any Browser event you should be adding a HostListener as below and emit that event

@HostListener('mouseover', ['$event']) onClick(event) {
     this.being.emit(event);
}

This will give you the target element. Updated the demo.

LIVE DEMO


问:
RAII and factory design pattern?
Let's say I have Foo class:

```<code>struct Resource {
  void block();
  void unblock();
};
struct Foo {
   static Foo create() {
      Resource resource;
      resource.block();
      return Foo{resource};
    }
   ~Foo() { resource.unblock(); }
   void f() {}
private:
   Resource resource;
   Foo(Resource resource): resource(resource) {}
};
</code>```

Am I right and there is no guarantee that ~Foo will be called only once in such block?

```<code>{
   Foo foo = Foo::create();
   foo.f();
}
</code>```

If there is no guarantee, is it possible to fix somehow if using c++11 and move semantic? For example not call unblock_resource in moved foo, but I am not sure is there guarantee to use move constructor/operator= in return from Foo::create?

答:
Not sure about how this is related to the factory pattern, but to answer your question "Am I right and there is no guarantee that ~Foo will be called only once in such block?":

Avoiding copying/moving objects used as return values (i.e. return value optimization, especially named return value optimization) is permitted, but not guaranteed:

Under the following circumstances, the compilers are permitted, but
  not required to omit the copy- and move- (since C++11)construction of
  class objects even if the copy/move (since C++11) constructor and the
  destructor have observable side-effects. This is an optimization: even
  when it takes place and the copy-/move-constructor is not called, it
  still must be present and accessible (as if no optimization happened
  at all), otherwise the program is ill-formed:

If a function returns a class type by value, and the return
  statement's expression is the name of a non-volatile object with
  automatic storage duration, which isn't a function parameter, or a
  catch clause parameter, and which has the same type (ignoring
  top-level cv-qualification) as the return type of the function, then
  copy/move (since C++11) is omitted. When that local object is
  constructed, it is constructed directly in the storage where the
  function's return value would otherwise be moved or copied to. This
  variant of copy elision is known as NRVO, "named return value
  optimization".

One way could be to control locking/unlocking resources in the move constructor and the destructor, just as you mentioned in your question.

Another way could be to make use of shared_ptr, such that creation and deletion of your Foo-object is managed by an RAII-style shared_ptr wrapper. There is just one tricky thing if you want to keep the Foo-constructor private, since make_shared cannot deal with private constructors. To overcome this, you could declare a public constructor taking a parameter of a private data type as parameter. A little bit ugly, and maybe a little bit clumsy due to the shared_ptr-wrapper. But maybe it's at least some inspiration:

```<code>struct Foo {
private:

    struct private_dummy {};

public:
    static shared_ptr<Foo> create() {
        shared_ptr<Foo> foo = make_shared<Foo>(private_dummy{});
        return foo;
    }
    ~Foo() { cout << "deleted."; }
    Foo(struct private_dummy x) { cout << "created."; }
};

void test() {

    shared_ptr<Foo> foo = Foo::create();

}

int main() {

    test();

    //Foo notOK();
}
</code>```

Title: RAII and factory design pattern?

Body:
Let's say I have Foo class:

struct Resource {
  void block();
  void unblock();
};
struct Foo {
   static Foo create() {
      Resource resource;
      resource.block();
      return Foo{resource};
    }
   ~Foo() { resource.unblock(); }
   void f() {}
private:
   Resource resource;
   Foo(Resource resource): resource(resource) {}
};

Am I right and there is no guarantee that ~Foo will be called only once in such block?

{
   Foo foo = Foo::create();
   foo.f();
}

If there is no guarantee, is it possible to fix somehow if using c++11 and move semantic? For example not call unblock_resource in moved foo, but I am not sure is there guarantee to use move constructor/operator= in return from Foo::create?

Body:
Not sure about how this is related to the factory pattern, but to answer your question "Am I right and there is no guarantee that ~Foo will be called only once in such block?":

Avoiding copying/moving objects used as return values (i.e. return value optimization, especially named return value optimization) is permitted, but not guaranteed:

Under the following circumstances, the compilers are permitted, but
  not required to omit the copy- and move- (since C++11)construction of
  class objects even if the copy/move (since C++11) constructor and the
  destructor have observable side-effects. This is an optimization: even
  when it takes place and the copy-/move-constructor is not called, it
  still must be present and accessible (as if no optimization happened
  at all), otherwise the program is ill-formed:

If a function returns a class type by value, and the return
  statement's expression is the name of a non-volatile object with
  automatic storage duration, which isn't a function parameter, or a
  catch clause parameter, and which has the same type (ignoring
  top-level cv-qualification) as the return type of the function, then
  copy/move (since C++11) is omitted. When that local object is
  constructed, it is constructed directly in the storage where the
  function's return value would otherwise be moved or copied to. This
  variant of copy elision is known as NRVO, "named return value
  optimization".

One way could be to control locking/unlocking resources in the move constructor and the destructor, just as you mentioned in your question.

Another way could be to make use of shared_ptr, such that creation and deletion of your Foo-object is managed by an RAII-style shared_ptr wrapper. There is just one tricky thing if you want to keep the Foo-constructor private, since make_shared cannot deal with private constructors. To overcome this, you could declare a public constructor taking a parameter of a private data type as parameter. A little bit ugly, and maybe a little bit clumsy due to the shared_ptr-wrapper. But maybe it's at least some inspiration:

struct Foo {
private:

    struct private_dummy {};

public:
    static shared_ptr<Foo> create() {
        shared_ptr<Foo> foo = make_shared<Foo>(private_dummy{});
        return foo;
    }
    ~Foo() { cout << "deleted."; }
    Foo(struct private_dummy x) { cout << "created."; }
};

void test() {

    shared_ptr<Foo> foo = Foo::create();

}

int main() {

    test();

    //Foo notOK();
}


问:
How to make SSL/HTTPS certificates on Gitlab Auto DevOps with GKE and kube-lego
The instructions say to install it, but doesn't suggest which method will work, in what order or with which load balancer. I keep getting useless test certificates installed on my deployments.</p>

答:
It sounds like you are getting the default chart from helm, which is slightly different than the instructions you will find on the kube-lego Github. The helm chart uses Let's Encrypt's staging server by default. Also if you are not familiar with helm it can be quite tricky to undo the remnants that the kube-lego helm chart leaves behind, specially as tiller likes to keep the old installation history.

Here's a brief overview of setting up Gitlab Auto Devops with Google Kubernetes Engine. I should mention that you can skip up to step 13 if you use the Gitlab GKE wizard introduced in 10.1, but it won't really tell you what's happening or how to debug when things go wrong, also the wizard is a one way process.

In Gitlab under integrations you'll find a Kubernetes integration button

You can also find this under CI/ CD -> cluster

The API URL is the endpoint ip prefixed by https://

The "CA Certificate" it asks for is service account CA, not the same as the cluster CA

To connect to gitlab you'll need to create a k8s service account and get the CA and token for it. Do so by using gcloud to authenticate kubectl. GCE makes it easy by doing this for you through the "connect" button in k8s engine

https://kubernetes.io/docs/admin/authentication/#service-account-tokens

All commands must be run with a custom namespace, it will not work with default

kubectl create namespace (NS)

kubectl create serviceaccount (NAME)  --namespace=(NS)

This will create two tokens in your configs/secrets, a default one and you service account one

kubectl get -o json serviceaccounts (NAME)  --namespace=(NS)

kubectl get -o json secret (secrets-name-on-prev-result) --namespace=(NS)

To decode the base64 values echo them to base64 -d, for example

Echo mybase64stringasdfasdf= | base64 -d

To install helm, use the installation script method

https://docs.helm.sh/using_helm/#from-script

Init helm and update it's repo

helm init

helm repo update

Install nginx-ingress, its ingress with nginx. You could use the Google load balancer as well, but it's not as portable.

helm install stable/nginx-ingress

Make a wild card subdomain with an A record pointing to the IP address set up by ingress

In Gitlab, Make auto devops use your newly setup wildcard subdomain, if its "*.x" on "me.com" you should enter "x.me.com" in the auto devops settings.

Now install kube lego

helm install --name lego-main \
--set config.LEGO_EMAIL=CHANGEMENOW@example.com \
--set config.LEGO_URL=https://acme-v01.api.letsencrypt.org/directory \
stable/kube-lego

Helm installations are called charts, equal to a k8s container installation

If you wish to delete a release, you must purge it, otherwise tiller will keep a history, with:

helm delete --purge my-release-name

You can find the release names and their associated chart in

helm list

Troubleshooting

Order doesn't seem to matter too much. attaching to a pod can be a useful way of debugging problems, such as a bad email address. The Ideal order however is probably, nginx-ingress, then kube-lego, then gitlab. I did make it work with gitlab first, then nginx-ingress, then kube-lego.

I heard from Sid that they are working to make this easier... let's hope so.

ContentLicense: CC BY-SA 4.0


问:
What should I return from service layers or almost any method
The one thing that can still get me is what to return from methods? I know that you should be as specific as possible(ie don't return object if you need to return an int)

However it's cases like this

I have a service layer that contains business logic.  Say I have a method called CreateAnEvent()

Basically it saves an event to the database and if successful it will return a string with "saved to database"

Now what happens if I first need to check if this event meets some business rules.

Can't be less than today's date.

Can't be greater than one week from today.

Can't be created on a Friday.

Something like that where I need to first do some business checks that could either lead to validation errors or maybe some sort of other error(maybe even an exception) or a success message still gets me what I should be returning.

So lets go first with validation. Say the user fails all these validation rules what now? I am returning a string so this won't be pretty I going to have to use csv to return all the errors and parse them out.

So that just seems very bad.

I could first have a separate method called Validate() but now I have to remember to call this before I call CreateAnEvent(). So I don't think this is that great.

I am using ViewModels in my mvc project so maybe I should pass the entire viewModel to the service layer and then return this ViewModel.

In this view model I could have a collection of Errors that I could add all these errors to as well as a string to contain a success message.

Once it gets returned just do a check first for errors if count is zero then assume success msg is filled.

I am not returning the most specific type back but it would solve my problem. However I don't think the service layer should know anything about a viewModel.

I know some people do the validation in the viewmodel but I consider that more for basic non business logic rules like is a field blank or not. I don't think I should be doing testing like I described above in a viewmodel.

So the last option I can think of is send in the Domain Model(that would be in a viewmModel since there is a good chance I would be using it in the view) and in this Domain Model I would add a string for success messages and a collection for errors.

I would then return this domain model.

So it basically same idea as using ViewModels but this time extracting out the domain model and using it.

So is this the best way to do it or are there better ways?

答:
I prefer to separate my validation logic into classes of their own. The reason for this is entities can have various layers of validation. My validator classes implement the following interface:

```<code>public interface IValidator<T>
{
    bool IsValid(T entity);
    IEnumerable<string> BrokenRules(T entity);
}
</code>```

I then inject this validator into my service. The service can then return a boolean if the method succeeds / fails. On failures the additional information contained in the 'BrokenRules' enumerable is available. I have documented this in a blog post:

http://blog.bobcravens.com/2010/09/the-repository-pattern-part-2/

Let me know if you have any questions. Hope this helps.

Bob

ContentLicense: CC BY-SA 2.5

Body:
I prefer to separate my validation logic into classes of their own. The reason for this is entities can have various layers of validation. My validator classes implement the following interface:

public interface IValidator<T>
{
    bool IsValid(T entity);
    IEnumerable<string> BrokenRules(T entity);
}

I then inject this validator into my service. The service can then return a boolean if the method succeeds / fails. On failures the additional information contained in the 'BrokenRules' enumerable is available. I have documented this in a blog post:

http://blog.bobcravens.com/2010/09/the-repository-pattern-part-2/

Let me know if you have any questions. Hope this helps.

Bob


问:
Motor PI regulator structure code

I am actually working on a robot project base on freeRTOS. I faced some problems with PI controller which controls robot's wheels speed.

```<code>#define To 100 // 100 ms
   #define Te 5  // 5 ms
   #define Kp 0.01
   #define Ti 10  //0.1*To
   #define Ki 0.05/10   //Te/ti

   void corrNum(int consigneVitesse) // takes speed as parameter
   {
        int eL,eR = 0; errors left and right
         float cdeL = 0 ;
         float UpL = 0 ;
         int dutyL = 0 ;
         float cdeR = 0 ;
    float UpR = 0 ;
    int dutyR = 0 ;
    float UiL= 0 ;
    float UiR = 0 ;
    if(consigneVitesse)
    {
            tickL = quadEncoder_GetSpeedL();
            tickR = quadEncoder_GetSpeedR();
            eL = (int)(consigneVitesse - tickL);
            eR = (int)(consigneVitesse - tickR);
            UpL = Kp*eL ;
            UpR = Kp*eR ;
            UiL= UiL + Kp*Ki*eL ;
            UiR= UiR + Kp*Ki*eR ;
            UiL_prev = UiL ;
            UiR_prev = UiR ;
            cdeL = UpL + UiL ;
            cdeR = UpR + UiR ;
            dutyL = cdeL < 100 && cdeL > -100 ? (int)cdeL +100 : 200 ;
            dutyR = cdeR < 100 && cdeR > -100 ? (int)cdeR +100 : 200 ;
            motorLeft_SetDuty(dutyL);
            motorRight_SetDuty(dutyR);
            HAL_Delay(5); // sampling period 5 ms
            term_printf("MOTOR LEFT ::::::> CMD : %d SPEED : %d Err : %d    DUTY : %d\n\r",consigneVitesse,tickL,eL,dutyL`enter code here`);
            term_printf("MOTOR RIGHT ::::::> CMD : %d SPEED : %d Err : %d  DUTY : %d \n\r",consigneVitesse,tickR,eR,dutyR);;
            tickL = 0 ;
            tickR = 0;
    }
    else
    {
        motorLeft_SetDuty(100);
        motorRight_SetDuty(100);
    }

}`
</code>```

The prblem is that when the error reaches 0.0 instead of being steady is starts oscillating .

答:
It is not clear how you are using FreeRTOS in this solution - there are no FreeRTOS calls in the fragment, and the non-RTOS HAL_delay() and the terminal output in the time critical control loop will not help - you can output only 57 characters in 5ms - you do not have time to output text.

Your error signal is calculated incorrectly the encoder provided relative position not speed; you have to calculate speed from change of position over time.

You should dedicate a task to the control loop and use RTOS timing to ensure efficient and accurate scheduling.  The task should run at sufficiently high priority relative to other tasks to ensure jitter free timing.

The following should be regarded as pseudo-code; I am not familiar with the FreeRTOS API, so the OS calls are not real, and I have not dealt with instantiating the task itself and and have not dealt with scaling and other subtleties for which you have not provided sufficient information - it is the suggested controller structure that you should take from this - not the actual code verbatim:

```<code>typedef enum
{
  LEFT = 0,
  RIGHT = 1
} tMotorId

volatile static struct
{
  float integral ;
  int speed ;
  int previous_position ;
} motor_ctrl_data[2] = {{0,0},{0,0}} ;

void setSpeed( tMotorId id, int speed )
{
  motor_ctrl_data[id] = speed ;
}

void motor_ctrl_task()
{
  // Configure RTOS time for 5ms update period
  OS_TIMER timer = creatTimer( 5 ) ;
  startTimer( timer ) ;

  // Get initial encoder counts
  motor_ctrl_data[LEFT].previous_position = getEncoder(LEFT) ;
  motor_ctrl_data[RIGHT].previous_position = getEncoder(RIGHT) ;

  // PI control loop
  for(;;)
  {
    // Loop update timer wait
    waitTimer( timer ) ;

    // For each motor
    for( int m = 0; m < 2; m++ )
    {
      // Calculate speed
      int speed = getEncoder[m] - motor_ctrl_data[m].previous_position ;

      // Calculate speed error
      int error = motor_ctrl_data[m].speed - speed[m] ;

      // Calculate error integral
      motor_ctrl_data[m].integral += error[m] ;

      motorDuty( LEFT, Kp * error +  Ki * motor_ctrl_data[m].integral ) ;
    }
  }
}
</code>```

This does not on its own of course solve the oscillation, but is at least a controller structure capable of control given appropriate coefficients.  To tune the loop set Ki = 0 and increase Kp until the motor moves as fast as possible but without oscillation.  This will not get you to the target speed because on target the error will be zero, so Kp alone cannot work.  Then start to increase Ki until the target speed is met. With even a small Ki the target speed will eventually be met but the dynamic response will be laggy.  Too much and you will get overshoot or oscillation.

Depending on the dynamic response of the motor you may need other tweaks such as integral limiting or dead-band compensation.  You may even benefit from a differential term, but for simple speed controllers this is generally unnecessary and often hard to tune.

If you need to output debug data, have the loop write debug data to shared variables (in motor_ctrl_data for example if using the structure suggested above) and print them asynchronously from a lower priority task at a rate that the terminal output can sustain.

The article "PID Without a PhD" by Tim Wescott may be a useful read.

Title: Motor PI regulator structure code

Body:
I am actually working on a robot project base on freeRTOS. I faced some problems with PI controller which controls robot's wheels speed.

#define To 100 // 100 ms
   #define Te 5  // 5 ms
   #define Kp 0.01
   #define Ti 10  //0.1*To
   #define Ki 0.05/10   //Te/ti

   void corrNum(int consigneVitesse) // takes speed as parameter
   {
        int eL,eR = 0; errors left and right
         float cdeL = 0 ;
         float UpL = 0 ;
         int dutyL = 0 ;
         float cdeR = 0 ;
    float UpR = 0 ;
    int dutyR = 0 ;
    float UiL= 0 ;
    float UiR = 0 ;
    if(consigneVitesse)
    {
            tickL = quadEncoder_GetSpeedL();
            tickR = quadEncoder_GetSpeedR();
            eL = (int)(consigneVitesse - tickL);
            eR = (int)(consigneVitesse - tickR);
            UpL = Kp*eL ;
            UpR = Kp*eR ;
            UiL= UiL + Kp*Ki*eL ;
            UiR= UiR + Kp*Ki*eR ;
            UiL_prev = UiL ;
            UiR_prev = UiR ;
            cdeL = UpL + UiL ;
            cdeR = UpR + UiR ;
            dutyL = cdeL < 100 && cdeL > -100 ? (int)cdeL +100 : 200 ;
            dutyR = cdeR < 100 && cdeR > -100 ? (int)cdeR +100 : 200 ;
            motorLeft_SetDuty(dutyL);
            motorRight_SetDuty(dutyR);
            HAL_Delay(5); // sampling period 5 ms
            term_printf("MOTOR LEFT ::::::> CMD : %d SPEED : %d Err : %d    DUTY : %d\n\r",consigneVitesse,tickL,eL,dutyL`enter code here`);
            term_printf("MOTOR RIGHT ::::::> CMD : %d SPEED : %d Err : %d  DUTY : %d \n\r",consigneVitesse,tickR,eR,dutyR);;
            tickL = 0 ;
            tickR = 0;
    }
    else
    {
        motorLeft_SetDuty(100);
        motorRight_SetDuty(100);
    }

}`

The prblem is that when the error reaches 0.0 instead of being steady is starts oscillating .

Body:
It is not clear how you are using FreeRTOS in this solution - there are no FreeRTOS calls in the fragment, and the non-RTOS HAL_delay() and the terminal output in the time critical control loop will not help - you can output only 57 characters in 5ms - you do not have time to output text.

Your error signal is calculated incorrectly the encoder provided relative position not speed; you have to calculate speed from change of position over time.

You should dedicate a task to the control loop and use RTOS timing to ensure efficient and accurate scheduling.  The task should run at sufficiently high priority relative to other tasks to ensure jitter free timing.

The following should be regarded as pseudo-code; I am not familiar with the FreeRTOS API, so the OS calls are not real, and I have not dealt with instantiating the task itself and and have not dealt with scaling and other subtleties for which you have not provided sufficient information - it is the suggested controller structure that you should take from this - not the actual code verbatim:

typedef enum
{
  LEFT = 0,
  RIGHT = 1
} tMotorId

volatile static struct
{
  float integral ;
  int speed ;
  int previous_position ;
} motor_ctrl_data[2] = {{0,0},{0,0}} ;

void setSpeed( tMotorId id, int speed )
{
  motor_ctrl_data[id] = speed ;
}

void motor_ctrl_task()
{
  // Configure RTOS time for 5ms update period
  OS_TIMER timer = creatTimer( 5 ) ;
  startTimer( timer ) ;

  // Get initial encoder counts
  motor_ctrl_data[LEFT].previous_position = getEncoder(LEFT) ;
  motor_ctrl_data[RIGHT].previous_position = getEncoder(RIGHT) ;

  // PI control loop
  for(;;)
  {
    // Loop update timer wait
    waitTimer( timer ) ;

    // For each motor
    for( int m = 0; m < 2; m++ )
    {
      // Calculate speed
      int speed = getEncoder[m] - motor_ctrl_data[m].previous_position ;

      // Calculate speed error
      int error = motor_ctrl_data[m].speed - speed[m] ;

      // Calculate error integral
      motor_ctrl_data[m].integral += error[m] ;

      motorDuty( LEFT, Kp * error +  Ki * motor_ctrl_data[m].integral ) ;
    }
  }
}

This does not on its own of course solve the oscillation, but is at least a controller structure capable of control given appropriate coefficients.  To tune the loop set Ki = 0 and increase Kp until the motor moves as fast as possible but without oscillation.  This will not get you to the target speed because on target the error will be zero, so Kp alone cannot work.  Then start to increase Ki until the target speed is met. With even a small Ki the target speed will eventually be met but the dynamic response will be laggy.  Too much and you will get overshoot or oscillation.

Depending on the dynamic response of the motor you may need other tweaks such as integral limiting or dead-band compensation.  You may even benefit from a differential term, but for simple speed controllers this is generally unnecessary and often hard to tune.

If you need to output debug data, have the loop write debug data to shared variables (in motor_ctrl_data for example if using the structure suggested above) and print them asynchronously from a lower priority task at a rate that the terminal output can sustain.

The article "PID Without a PhD" by Tim Wescott may be a useful read.


问:
How to fix my C++ fighting game with Run-Time Check Error?
I have been receiving an issue that I do not understand. The issue is:

Run-Time Check Failure #3 - The variable 'win' is being used without being initialized.

I am struggling to comprehend where my error is within the code. From what I understand the run time error comes from win not being initialized meaning it hasn't been used or set, however, it clearly is set in the fightScene() function.

```<code>#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include "Character.h"
#include "Item.h"
#include "Blacksmith.h"

using namespace std;

void startup();
void createCharacter();
void existCharacter();
void secondFighter();
void fightScene();
int fightMoves(int att, int sp, int num);
void roundWon();
void characterLost();
void use_bar();
void newlines();
void changeCase(string &convert);
void bSmith();

Character existingCharacter[4] = { Character("Shabu", 10, 10, 10, 0, "Empty"), Character("Calil", 15, 15, 15, 0, "Empty"), Character("Goltero", 20, 20, 20, 0, "Empty"), Character("Balrogg", 30, 30, 30, 0, "Empty") };
Character cCharacter[2] = { Character(), Character() };
Character cCharacterSave("Empty", 20, 0, 0, 100, "Empty");
Item bars(0, 0, 0);
int timesWon = 0;
int purposeIgnore = 0;
char repeat = 'y';

int main() {
    startup();
    while (repeat == 'y' || repeat == 'Y') {
        fightScene();
        if (repeat == 'y' || repeat == 'Y')
            secondFighter();
    }
    return 0;
}

void startup() {
    int playerChoice;
    cout << "**************************" << endl;
    cout << "*      Loading Game      *" << endl;
    cout << "**************************" << endl;
    cout << "Which Would You Prefer?" << endl;
    cout << "1: New Character..." << endl;
    cout << "2: Load Character..." << endl;

    do {
        cout << "Enter Selection: ";
        cin >> playerChoice;
    } while (playerChoice <= 0 || playerChoice >= 3);
    if (playerChoice == 1)
        createCharacter();
    else if (playerChoice == 2)
        existCharacter();
    return;
}

void createCharacter() {
    string Name;
    string inventory;
    int h, att, sp, gc;

    cout << "***************************" << endl;
    cout << "*   Creating New Player   *" << endl;
    cout << "***************************" << endl;
    cout << "What Shall We Call You?" << endl;
    cout << "Enter Name Here: ";

    cin >> Name;
    changeCase(Name);

    cout << Name << ", let's set your stats!" << endl;
    cout << "Set your ATTACK between 1 - 10" << endl;

    do {
        cout << "Enter Attack Here: ";
        cin >> att;
    } while (att <= 0 || att >= 11);

    cout << "Set your SPEED between 1 - 10" << endl;

    do {
        cout << "Enter Speed Here: ";
        cin >> sp;
    } while (sp <= 0 || sp >= 11);

    h = 20;
    gc = 100;

    cout << "The HEALTH stat wil increase over time, but as of now, " << Name << ", has " << h << " health!" << endl;
    cout << Name << " you have been granted " << gc << " gold!" << endl;

    cCharacter[0] = Character(Name, h, att, sp, gc, inventory);
    cin.ignore();
    return;
}

void existCharacter() {
    string characterChoice;

    cout << "***********************" << endl;
    cout << "*   Existing Player   *" << endl;
    cout << "***********************" << endl;

    for (int i = 0, j = 1; i >= 0 && i <= 3; i++, j++) {
        cout << j << ": " << existingCharacter[i].getName();
        cout << "\t" << "Health: " << existingCharacter[i].getHealth();
        cout << "\t" << "Attack: " << existingCharacter[i].getAttack();
        cout << "\t" << "Speed: " << existingCharacter[i].getSpeed();
    }

    cout << "Enter Selection: ";

    cin.ignore();
    getline(cin, characterChoice);
    changeCase(characterChoice);

    if (characterChoice == "1" || characterChoice == "Shabu") {
        cCharacter[0] = existingCharacter[0]; cCharacterSave.setHealth(existingCharacter[0].getHealth());
    }
    else if (characterChoice == "2" || characterChoice == "Calil") {
        cCharacter[0] = existingCharacter[1]; cCharacterSave.setHealth(existingCharacter[1].getHealth());
    }
    else if (characterChoice == "3" || characterChoice == "Goltero") {
        cCharacter[0] = existingCharacter[2]; cCharacterSave.setHealth(existingCharacter[2].getHealth());
    }
    else if (characterChoice == "4" || characterChoice == "Balrogg") {
        cCharacter[0] = existingCharacter[3]; cCharacterSave.setHealth(existingCharacter[3].getHealth());
    }
    else {
        cout << "Program Failure....Invaid Input!" << endl;
    }
    secondFighter();
    return;
}

void secondFighter() {
    string cFighter;

    cout << "***************" << endl;
    cout << "*   Fighter   *" << endl;
    cout << "***************" << endl;
    cout << "Choose Who To Fight!" << endl;

    for (int i = 0, j = 1; i >= 0 && i <= 3; i++, j++) {
        cout << j << ": " << existingCharacter[i].getName();
        cout << "\t" << "Health: " << existingCharacter[i].getHealth();
        cout << "\t" << "Strength: " << existingCharacter[i].getAttack();
        cout << "\t" << "Speed: " << existingCharacter[i].getSpeed();
        cout << endl;
    }

    cout << "Enter Selection: ";
    if (purposeIgnore >= 1)
        cin.ignore();

    getline(cin, cFighter);
    changeCase(cFighter);

    if (cFighter == "1" || cFighter == "Shabu")
        cCharacter[1] = existingCharacter[0];
    else if (cFighter == "2" || cFighter == "Calil")
        cCharacter[1] = existingCharacter[1];
    else if (cFighter == "3" || cFighter == "Goltero")
        cCharacter[1] = existingCharacter[2];
    else if (cFighter == "4" || cFighter == "Balrogg")
        cCharacter[1] = existingCharacter[3];
    else { cout << "Invalid Input! Program Failure....Please Close and Restart" << endl; }

    return;
}

void fightScene() {
    int fight_choice;
    int i = 0;
    int j = 5;
    bool win;

    if (timesWon >= 1)
        j = 6;

    while (cCharacter[0].getHealth() > 0 && cCharacter[1].getHealth() > 0) {
        newlines();

        cout << "\t\t" << cCharacter[0].getName() << " choose ";

        if (i == 0)
            cout << "an attack.";

        else
            cout << "another attack.";

        do {
            cout << "\n\n\t\t<1. Punch / 2. Kick>\n\t\t<3. Slam / 4. Drop kick>";

            if (j == 6)
                cout << "\n\t\t<5. Items>";

            cout << endl << "\t\t";
            cin >> fight_choice;
        } while (fight_choice <= 0 || fight_choice >= j);

        if (fight_choice == 1) {
            cCharacter[1].setHealth(cCharacter[1].getHealth() - fightMoves(cCharacter[0].getAttack(), cCharacter[0].getSpeed(), 1));
            cout << "\n\t\tYou Punched " << cCharacter[1].getName() << ", his health is now: ";

            if (cCharacter[1].getHealth() <= 0)
            {
                cout << "0" << endl << endl; cCharacter[1].setHealth(-1);
            }

            else
                cout << cCharacter[1].getHealth() << endl << endl;
        }

        else if (fight_choice == 2) {
            cCharacter[1].setHealth(cCharacter[1].getHealth() - fightMoves(cCharacter[0].getAttack(), cCharacter[0].getSpeed(), 2));
            cout << "\n\t\tYou Kicked " << cCharacter[1].getName() << ", his health is now: ";

            if (cCharacter[1].getHealth() <= 0)
            {
                cout << "0" << endl << endl; cCharacter[1].setHealth(-1);
            }

            else
                cout << cCharacter[1].getHealth() << endl << endl;
        }

        else if (fight_choice == 3) {
            cCharacter[1].setHealth(cCharacter[1].getHealth() - fightMoves(cCharacter[0].getAttack(), cCharacter[0].getSpeed(), 3));
            cout << "\n\t\tYou Slamed " << cCharacter[1].getName() << " on the ground, his health is now: ";

            if (cCharacter[1].getHealth() <= 0)

            {
                cout << "0" << endl << endl; cCharacter[1].setHealth(-1);
            }

            else
                cout << cCharacter[1].getHealth() << endl << endl;
        }

        else if (fight_choice == 4) {
            cCharacter[1].setHealth(cCharacter[1].getHealth() - fightMoves(cCharacter[0].getAttack(), cCharacter[0].getSpeed(), 4));
            cout << "\n\t\tYou Drop Kicked " << cCharacter[1].getName() << ", his health is now: ";

            if (cCharacter[1].getHealth() <= 0)
            {
                cout << "0" << endl << endl; cCharacter[1].setHealth(-1);
            }

            else
                cout << cCharacter[1].getHealth() << endl << endl;
        }

        else if (timesWon >= 1 && fight_choice == 5) { // Bars
            use_bar();
        }

        // Second fighter attack

        srand(time(NULL));
        int ran_pick = rand() % 5 + 1;

        if (cCharacter[1].getHealth() < 0) {
            ran_pick = 0;
            win = 1;
        }

        else if (cCharacter[1].getHealth() > 0) {
            cout << "\n\t\t<" << cCharacter[1].getName() << "'s turn>" << endl;
            win = 0;
        }

        if (ran_pick == 0)
            continue;

        else if (ran_pick == 1) {
            cCharacter[0].setHealth(cCharacter[0].getHealth() - fightMoves(cCharacter[1].getAttack(), cCharacter[1].getSpeed(), 1));
            cout << "\n\t\t" << cCharacter[1].getName() << " punched you! Your health is now: ";

            if (cCharacter[0].getHealth() <= 0)
            {
                cout << "0" << endl << endl; cCharacter[0].setHealth(-1);
            }

            else
                cout << cCharacter[0].getHealth() << endl << endl;
        }

        else if (ran_pick == 2) {
            cCharacter[0].setHealth(cCharacter[0].getHealth() - fightMoves(cCharacter[1].getAttack(), cCharacter[1].getSpeed(), 2));
            cout << "\n\t\t" << cCharacter[1].getName() << " kicked you! Your health is now: ";

            if (cCharacter[0].getHealth() <= 0)
            {
                cout << "0" << endl << endl; cCharacter[0].setHealth(-1);
            }

            else
                cout << cCharacter[0].getHealth() << endl << endl;
        }

        else if (ran_pick == 3) {
            cCharacter[0].setHealth(cCharacter[0].getHealth() - fightMoves(cCharacter[1].getAttack(), cCharacter[1].getSpeed(), 3));
            cout << "\n\t\t" << cCharacter[1].getName() << " slammed you on the ground! Your health is now: ";

            if (cCharacter[0].getHealth() <= 0)
            {
                cout << "0" << endl << endl; cCharacter[0].setHealth(-1);
            }

            else
                cout << cCharacter[0].getHealth() << endl << endl;
        }

        else if (ran_pick == 4) {
            cCharacter[0].setHealth(cCharacter[0].getHealth() - fightMoves(cCharacter[1].getAttack(), cCharacter[1].getSpeed(), 4));
            cout << "\n\t\t" << cCharacter[1].getName() << " drop kicked you! Your health is now: ";

            if (cCharacter[0].getHealth() <= 0)
            {
                cout << "0" << endl << endl; cCharacter[0].setHealth(-1);
            }

            else
                cout << cCharacter[0].getHealth() << endl << endl;
        }

        else if (ran_pick == 5)
            cout << "\t\t" << cCharacter[1].getName() << " missed you! Your health is still: " << cCharacter[0].getHealth() << endl << endl;

        if (cCharacter[0].getHealth() > 0) {
            cout << "\n\t\t";
            system("PAUSE"); // Lets them read the attacks
        }

        i++; // Increases i to change some wording
    }

    if (win == 1)
        roundWon();

    else
        characterLost();

    return;
}

int fightMoves(int st, int sp, int num) {
    srand(time(NULL));
    int rand_num;
    int addition;

    switch (num) {
    case 1: {
        rand_num = rand() % 40 + 1;
        addition = (st + sp) / rand_num;
        cout << "\n\t\tDamage inflicted: " << addition;
        return addition; break;
    }
    case 2: {
        rand_num = rand() % 20 + 1;
        addition = (st + sp) / rand_num;
        cout << "\n\t\tDamage inflicted: " << addition;
        return addition; break;
    }
    case 3: {
        rand_num = rand() % 30 + 1;
        addition = (st + sp) / rand_num;
        cout << "\n\t\tDamage inflicted: " << addition;
        return addition; break;
    }
    case 4: {
        rand_num = rand() % 30 + 1;
        addition = (st + sp) / rand_num;
        cout << "\n\t\tDamage inflicted: " << addition;
        return addition; break;
    }
    }
}

int start()
{
    while (repeat == 'y' || repeat == 'Y') {
        fightScene();
        if (repeat == 'y' || repeat == 'Y')
            secondFighter();
    }
    return 0;
}

void roundWon() {
    srand(time(NULL));
    timesWon++;
    purposeIgnore++;
    cCharacter[0].setHealth(cCharacterSave.getHealth());
    cCharacter[1].setHealth(100);
    int item_won = rand() % 3 + 1;

    cout << "\t\tYou won!";
    cout << "\n\n\t\tYou have been rewarded ";

    if (item_won == 1) {
        cout << "a small protein bar! (+20 health)";
        bars.bar_small++;
    }

    else if (item_won == 2) {
        cout << "a medium protein bar! (+30 health)";
        bars.bar_medium++;
    }

    else if (item_won == 3) {
        cout << "a large protein bar! (+40 health)";
        bars.bar_large++;
    }

    cout << "\n\n\t\tItems can be used in game at the cost of a turn.";

    cout << "\n\n\t\t";
    system("PAUSE"); // Lets them read

    int ability_gain[3] = { rand() % 10 + 1, rand() % 10 + 1, rand() % 10 + 1 };

    cCharacter[0].setHealth(ability_gain[0] += cCharacter[0].getHealth());
    cCharacterSave.setHealth(cCharacter[0].getHealth());
    cCharacter[0].setAttack(ability_gain[1] += cCharacter[0].getAttack());
    cCharacter[0].setSpeed(ability_gain[2] += cCharacter[0].getSpeed());

    cout << "\n\t\tYour health is now: " << cCharacter[0].getHealth();
    cout << "\n\t\tYour strength is now: " << cCharacter[0].getAttack();
    cout << "\n\t\tYour speed is now: " << cCharacter[0].getSpeed();

    cout << "\n\n\t\tWould you like to fight another person? (y/n) ";
    cin >> repeat;

    return;
}

void characterLost() {
    cCharacter[0].setHealth(cCharacterSave.getHealth());
    cCharacter[1].setHealth(100);
    purposeIgnore++;

    cout << "\n\n\t\tYou have lost.";
    cout << "\n\t\tWould you like to fight another person? (y/n) ";
    cin >> repeat;

    return;
}

void use_bar() {
    int choose_bar;
    char another_bar;

    do {
        cout << "\n\n\t\tWhich bar would you like to use? ";
        cout << "\n\t\t 1: Small Bar: " << bars.bar_small;
        cout << "\n\t\t 2: Medium Bar: " << bars.bar_medium;
        cout << "\n\t\t 3: Large bar: " << bars.bar_large;

        do {
            cout << "\n\n\t\tI choose: ";
            cin >> choose_bar;
        } while (choose_bar <= 0 || choose_bar >= 4);

        if (choose_bar == 1 && bars.bar_small >= 1) {
            cCharacter[0].setHealth(cCharacter[0].getHealth() + 20);
            bars.bar_small--;
            cout << "\n\n\t\tYour health is now: " << cCharacter[0].getHealth();
        }

        else if (choose_bar == 2 && bars.bar_medium >= 1) {
            cCharacter[0].setHealth(cCharacter[0].getHealth() + 30);
            bars.bar_medium--;
            cout << "\n\n\t\tYour health is now: " << cCharacter[0].getHealth();
        }

        else if (choose_bar == 3 && bars.bar_large >= 1) {
            cCharacter[0].setHealth(cCharacter[0].getHealth() + 40);
            bars.bar_large--;
            cout << "\n\n\t\tYour health is now: " << cCharacter[0].getHealth();
        }

        else
            cout << "\n\t\tNot enough bars!";

        cout << "\n\n\t\tWould you like to use another bar? (y/n) ";
        cin >> another_bar;
    } while (another_bar == 'y' || another_bar == 'Y');

    return;
}

void newlines() {
    cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
}

void changeCase(string &convert) {
    for (int i = 0; convert[i]; i++) {
        if (isupper(convert[i]))
            convert[i] = tolower(convert[i]);
        else
            continue;
    }

    convert.at(0) = toupper(convert.at(0));

    return;
}

void bSmith()
{
    Blacksmith shopKeeper; //The shop keeper

    int responce; //Menu navigation
    cout << "*******************************" << endl;
    cout << "*  Welcome to the Blacksmith  *" << endl;
    cout << "*******************************" << "\n" << endl;

    cout << "*****************************" << endl;
    cout << "*     1: Purchase Items     *\n";
    cout << "*       2: Sell Items       *\n";
    cout << "*    3: List Your Items     *\n";
    cout << "*        4: Currency        *\n";
    cout << "*          5: Exit          *\n";
    cout << "*****************************" << endl;
    do
    {
        cout << "Enter Option Here: ";
        cin >> responce;

        switch (responce)
        {
        case 1:
            shopKeeper.buyItem(cCharacter[0]);
            cout << endl;
            break;

        case 2:
            cout << "*****************************" << endl;
            cout << "*       Items To Sell       *" << endl;
            cout << "*****************************" << endl;
            shopKeeper.sellItem(cCharacter[0]);
            cout << endl;
            break;

        case 3:
            cout << "*****************************" << endl;
            cout << "*    Character Inventory    *" << endl;
            cout << "*****************************" << endl;
            cCharacter[0].listInv();
            cout << endl;
            break;

        case 4:
            cout << "*****************************" << endl;
            cout << "*   Current Gold Currency   *" << endl;
            cout << "*****************************" << endl;
            cout << "\t" << cCharacter[0].getCurrency() << endl;
            cout << endl;
            break;

        case 5:
            cout << "*****************************" << endl;
            cout << "*    Thanks for shopping    *" << endl;
            cout << "*****************************" << endl;
            return;

        default:
            cout << "Please enter valid data." << "\n";
            break;
        }
        cout << "*****************************" << endl;
        cout << "*     1: Purchase Items     *\n";
        cout << "*       2: Sell Items       *\n";
        cout << "*    3: List Your Items     *\n";
        cout << "*        4: Currency        *\n";
        cout << "*          5: Exit          *\n";
        cout << "*****************************" << endl;
    } while (responce != 5);

    return;
}
</code>```

答:
All I can see that sets  win is this part of the code,

```<code>    if (cCharacter[1].getHealth() < 0) {
        ran_pick = 0;
        win = 1;
    }

    else if (cCharacter[1].getHealth() > 0) {
        cout << "\n\t\t<" << cCharacter[1].getName() << "'s turn>" << endl;
        win = 0;
    }
</code>```

However, if cCharacter[1].getHealth()==0, win will be left unset.

Body:
I have been receiving an issue that I do not understand. The issue is:

Run-Time Check Failure #3 - The variable 'win' is being used without being initialized.

I am struggling to comprehend where my error is within the code. From what I understand the run time error comes from win not being initialized meaning it hasn't been used or set, however, it clearly is set in the fightScene() function.

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include "Character.h"
#include "Item.h"
#include "Blacksmith.h"

using namespace std;

void startup();
void createCharacter();
void existCharacter();
void secondFighter();
void fightScene();
int fightMoves(int att, int sp, int num);
void roundWon();
void characterLost();
void use_bar();
void newlines();
void changeCase(string &convert);
void bSmith();

Character existingCharacter[4] = { Character("Shabu", 10, 10, 10, 0, "Empty"), Character("Calil", 15, 15, 15, 0, "Empty"), Character("Goltero", 20, 20, 20, 0, "Empty"), Character("Balrogg", 30, 30, 30, 0, "Empty") };
Character cCharacter[2] = { Character(), Character() };
Character cCharacterSave("Empty", 20, 0, 0, 100, "Empty");
Item bars(0, 0, 0);
int timesWon = 0;
int purposeIgnore = 0;
char repeat = 'y';

int main() {
    startup();
    while (repeat == 'y' || repeat == 'Y') {
        fightScene();
        if (repeat == 'y' || repeat == 'Y')
            secondFighter();
    }
    return 0;
}

void startup() {
    int playerChoice;
    cout << "**************************" << endl;
    cout << "*      Loading Game      *" << endl;
    cout << "**************************" << endl;
    cout << "Which Would You Prefer?" << endl;
    cout << "1: New Character..." << endl;
    cout << "2: Load Character..." << endl;

    do {
        cout << "Enter Selection: ";
        cin >> playerChoice;
    } while (playerChoice <= 0 || playerChoice >= 3);
    if (playerChoice == 1)
        createCharacter();
    else if (playerChoice == 2)
        existCharacter();
    return;
}

void createCharacter() {
    string Name;
    string inventory;
    int h, att, sp, gc;

    cout << "***************************" << endl;
    cout << "*   Creating New Player   *" << endl;
    cout << "***************************" << endl;
    cout << "What Shall We Call You?" << endl;
    cout << "Enter Name Here: ";

    cin >> Name;
    changeCase(Name);

    cout << Name << ", let's set your stats!" << endl;
    cout << "Set your ATTACK between 1 - 10" << endl;

    do {
        cout << "Enter Attack Here: ";
        cin >> att;
    } while (att <= 0 || att >= 11);

    cout << "Set your SPEED between 1 - 10" << endl;

    do {
        cout << "Enter Speed Here: ";
        cin >> sp;
    } while (sp <= 0 || sp >= 11);

    h = 20;
    gc = 100;

    cout << "The HEALTH stat wil increase over time, but as of now, " << Name << ", has " << h << " health!" << endl;
    cout << Name << " you have been granted " << gc << " gold!" << endl;

    cCharacter[0] = Character(Name, h, att, sp, gc, inventory);
    cin.ignore();
    return;
}

void existCharacter() {
    string characterChoice;

    cout << "***********************" << endl;
    cout << "*   Existing Player   *" << endl;
    cout << "***********************" << endl;

    for (int i = 0, j = 1; i >= 0 && i <= 3; i++, j++) {
        cout << j << ": " << existingCharacter[i].getName();
        cout << "\t" << "Health: " << existingCharacter[i].getHealth();
        cout << "\t" << "Attack: " << existingCharacter[i].getAttack();
        cout << "\t" << "Speed: " << existingCharacter[i].getSpeed();
    }

    cout << "Enter Selection: ";

    cin.ignore();
    getline(cin, characterChoice);
    changeCase(characterChoice);

    if (characterChoice == "1" || characterChoice == "Shabu") {
        cCharacter[0] = existingCharacter[0]; cCharacterSave.setHealth(existingCharacter[0].getHealth());
    }
    else if (characterChoice == "2" || characterChoice == "Calil") {
        cCharacter[0] = existingCharacter[1]; cCharacterSave.setHealth(existingCharacter[1].getHealth());
    }
    else if (characterChoice == "3" || characterChoice == "Goltero") {
        cCharacter[0] = existingCharacter[2]; cCharacterSave.setHealth(existingCharacter[2].getHealth());
    }
    else if (characterChoice == "4" || characterChoice == "Balrogg") {
        cCharacter[0] = existingCharacter[3]; cCharacterSave.setHealth(existingCharacter[3].getHealth());
    }
    else {
        cout << "Program Failure....Invaid Input!" << endl;
    }
    secondFighter();
    return;
}

void secondFighter() {
    string cFighter;

    cout << "***************" << endl;
    cout << "*   Fighter   *" << endl;
    cout << "***************" << endl;
    cout << "Choose Who To Fight!" << endl;

    for (int i = 0, j = 1; i >= 0 && i <= 3; i++, j++) {
        cout << j << ": " << existingCharacter[i].getName();
        cout << "\t" << "Health: " << existingCharacter[i].getHealth();
        cout << "\t" << "Strength: " << existingCharacter[i].getAttack();
        cout << "\t" << "Speed: " << existingCharacter[i].getSpeed();
        cout << endl;
    }

    cout << "Enter Selection: ";
    if (purposeIgnore >= 1)
        cin.ignore();

    getline(cin, cFighter);
    changeCase(cFighter);

    if (cFighter == "1" || cFighter == "Shabu")
        cCharacter[1] = existingCharacter[0];
    else if (cFighter == "2" || cFighter == "Calil")
        cCharacter[1] = existingCharacter[1];
    else if (cFighter == "3" || cFighter == "Goltero")
        cCharacter[1] = existingCharacter[2];
    else if (cFighter == "4" || cFighter == "Balrogg")
        cCharacter[1] = existingCharacter[3];
    else { cout << "Invalid Input! Program Failure....Please Close and Restart" << endl; }

    return;
}

void fightScene() {
    int fight_choice;
    int i = 0;
    int j = 5;
    bool win;

    if (timesWon >= 1)
        j = 6;

    while (cCharacter[0].getHealth() > 0 && cCharacter[1].getHealth() > 0) {
        newlines();

        cout << "\t\t" << cCharacter[0].getName() << " choose ";

        if (i == 0)
            cout << "an attack.";

        else
            cout << "another attack.";

        do {
            cout << "\n\n\t\t<1. Punch / 2. Kick>\n\t\t<3. Slam / 4. Drop kick>";

            if (j == 6)
                cout << "\n\t\t<5. Items>";

            cout << endl << "\t\t";
            cin >> fight_choice;
        } while (fight_choice <= 0 || fight_choice >= j);

        if (fight_choice == 1) {
            cCharacter[1].setHealth(cCharacter[1].getHealth() - fightMoves(cCharacter[0].getAttack(), cCharacter[0].getSpeed(), 1));
            cout << "\n\t\tYou Punched " << cCharacter[1].getName() << ", his health is now: ";

            if (cCharacter[1].getHealth() <= 0)
            {
                cout << "0" << endl << endl; cCharacter[1].setHealth(-1);
            }

            else
                cout << cCharacter[1].getHealth() << endl << endl;
        }

        else if (fight_choice == 2) {
            cCharacter[1].setHealth(cCharacter[1].getHealth() - fightMoves(cCharacter[0].getAttack(), cCharacter[0].getSpeed(), 2));
            cout << "\n\t\tYou Kicked " << cCharacter[1].getName() << ", his health is now: ";

            if (cCharacter[1].getHealth() <= 0)
            {
                cout << "0" << endl << endl; cCharacter[1].setHealth(-1);
            }

            else
                cout << cCharacter[1].getHealth() << endl << endl;
        }

        else if (fight_choice == 3) {
            cCharacter[1].setHealth(cCharacter[1].getHealth() - fightMoves(cCharacter[0].getAttack(), cCharacter[0].getSpeed(), 3));
            cout << "\n\t\tYou Slamed " << cCharacter[1].getName() << " on the ground, his health is now: ";

            if (cCharacter[1].getHealth() <= 0)

            {
                cout << "0" << endl << endl; cCharacter[1].setHealth(-1);
            }

            else
                cout << cCharacter[1].getHealth() << endl << endl;
        }

        else if (fight_choice == 4) {
            cCharacter[1].setHealth(cCharacter[1].getHealth() - fightMoves(cCharacter[0].getAttack(), cCharacter[0].getSpeed(), 4));
            cout << "\n\t\tYou Drop Kicked " << cCharacter[1].getName() << ", his health is now: ";

            if (cCharacter[1].getHealth() <= 0)
            {
                cout << "0" << endl << endl; cCharacter[1].setHealth(-1);
            }

            else
                cout << cCharacter[1].getHealth() << endl << endl;
        }

        else if (timesWon >= 1 && fight_choice == 5) { // Bars
            use_bar();
        }

        // Second fighter attack

        srand(time(NULL));
        int ran_pick = rand() % 5 + 1;

        if (cCharacter[1].getHealth() < 0) {
            ran_pick = 0;
            win = 1;
        }

        else if (cCharacter[1].getHealth() > 0) {
            cout << "\n\t\t<" << cCharacter[1].getName() << "'s turn>" << endl;
            win = 0;
        }

        if (ran_pick == 0)
            continue;

        else if (ran_pick == 1) {
            cCharacter[0].setHealth(cCharacter[0].getHealth() - fightMoves(cCharacter[1].getAttack(), cCharacter[1].getSpeed(), 1));
            cout << "\n\t\t" << cCharacter[1].getName() << " punched you! Your health is now: ";

            if (cCharacter[0].getHealth() <= 0)
            {
                cout << "0" << endl << endl; cCharacter[0].setHealth(-1);
            }

            else
                cout << cCharacter[0].getHealth() << endl << endl;
        }

        else if (ran_pick == 2) {
            cCharacter[0].setHealth(cCharacter[0].getHealth() - fightMoves(cCharacter[1].getAttack(), cCharacter[1].getSpeed(), 2));
            cout << "\n\t\t" << cCharacter[1].getName() << " kicked you! Your health is now: ";

            if (cCharacter[0].getHealth() <= 0)
            {
                cout << "0" << endl << endl; cCharacter[0].setHealth(-1);
            }

            else
                cout << cCharacter[0].getHealth() << endl << endl;
        }

        else if (ran_pick == 3) {
            cCharacter[0].setHealth(cCharacter[0].getHealth() - fightMoves(cCharacter[1].getAttack(), cCharacter[1].getSpeed(), 3));
            cout << "\n\t\t" << cCharacter[1].getName() << " slammed you on the ground! Your health is now: ";

            if (cCharacter[0].getHealth() <= 0)
            {
                cout << "0" << endl << endl; cCharacter[0].setHealth(-1);
            }

            else
                cout << cCharacter[0].getHealth() << endl << endl;
        }

        else if (ran_pick == 4) {
            cCharacter[0].setHealth(cCharacter[0].getHealth() - fightMoves(cCharacter[1].getAttack(), cCharacter[1].getSpeed(), 4));
            cout << "\n\t\t" << cCharacter[1].getName() << " drop kicked you! Your health is now: ";

            if (cCharacter[0].getHealth() <= 0)
            {
                cout << "0" << endl << endl; cCharacter[0].setHealth(-1);
            }

            else
                cout << cCharacter[0].getHealth() << endl << endl;
        }

        else if (ran_pick == 5)
            cout << "\t\t" << cCharacter[1].getName() << " missed you! Your health is still: " << cCharacter[0].getHealth() << endl << endl;

        if (cCharacter[0].getHealth() > 0) {
            cout << "\n\t\t";
            system("PAUSE"); // Lets them read the attacks
        }

        i++; // Increases i to change some wording
    }

    if (win == 1)
        roundWon();

    else
        characterLost();

    return;
}

int fightMoves(int st, int sp, int num) {
    srand(time(NULL));
    int rand_num;
    int addition;

    switch (num) {
    case 1: {
        rand_num = rand() % 40 + 1;
        addition = (st + sp) / rand_num;
        cout << "\n\t\tDamage inflicted: " << addition;
        return addition; break;
    }
    case 2: {
        rand_num = rand() % 20 + 1;
        addition = (st + sp) / rand_num;
        cout << "\n\t\tDamage inflicted: " << addition;
        return addition; break;
    }
    case 3: {
        rand_num = rand() % 30 + 1;
        addition = (st + sp) / rand_num;
        cout << "\n\t\tDamage inflicted: " << addition;
        return addition; break;
    }
    case 4: {
        rand_num = rand() % 30 + 1;
        addition = (st + sp) / rand_num;
        cout << "\n\t\tDamage inflicted: " << addition;
        return addition; break;
    }
    }
}

int start()
{
    while (repeat == 'y' || repeat == 'Y') {
        fightScene();
        if (repeat == 'y' || repeat == 'Y')
            secondFighter();
    }
    return 0;
}

void roundWon() {
    srand(time(NULL));
    timesWon++;
    purposeIgnore++;
    cCharacter[0].setHealth(cCharacterSave.getHealth());
    cCharacter[1].setHealth(100);
    int item_won = rand() % 3 + 1;

    cout << "\t\tYou won!";
    cout << "\n\n\t\tYou have been rewarded ";

    if (item_won == 1) {
        cout << "a small protein bar! (+20 health)";
        bars.bar_small++;
    }

    else if (item_won == 2) {
        cout << "a medium protein bar! (+30 health)";
        bars.bar_medium++;
    }

    else if (item_won == 3) {
        cout << "a large protein bar! (+40 health)";
        bars.bar_large++;
    }

    cout << "\n\n\t\tItems can be used in game at the cost of a turn.";

    cout << "\n\n\t\t";
    system("PAUSE"); // Lets them read

    int ability_gain[3] = { rand() % 10 + 1, rand() % 10 + 1, rand() % 10 + 1 };

    cCharacter[0].setHealth(ability_gain[0] += cCharacter[0].getHealth());
    cCharacterSave.setHealth(cCharacter[0].getHealth());
    cCharacter[0].setAttack(ability_gain[1] += cCharacter[0].getAttack());
    cCharacter[0].setSpeed(ability_gain[2] += cCharacter[0].getSpeed());

    cout << "\n\t\tYour health is now: " << cCharacter[0].getHealth();
    cout << "\n\t\tYour strength is now: " << cCharacter[0].getAttack();
    cout << "\n\t\tYour speed is now: " << cCharacter[0].getSpeed();

    cout << "\n\n\t\tWould you like to fight another person? (y/n) ";
    cin >> repeat;

    return;
}

void characterLost() {
    cCharacter[0].setHealth(cCharacterSave.getHealth());
    cCharacter[1].setHealth(100);
    purposeIgnore++;

    cout << "\n\n\t\tYou have lost.";
    cout << "\n\t\tWould you like to fight another person? (y/n) ";
    cin >> repeat;

    return;
}

void use_bar() {
    int choose_bar;
    char another_bar;

    do {
        cout << "\n\n\t\tWhich bar would you like to use? ";
        cout << "\n\t\t 1: Small Bar: " << bars.bar_small;
        cout << "\n\t\t 2: Medium Bar: " << bars.bar_medium;
        cout << "\n\t\t 3: Large bar: " << bars.bar_large;

        do {
            cout << "\n\n\t\tI choose: ";
            cin >> choose_bar;
        } while (choose_bar <= 0 || choose_bar >= 4);

        if (choose_bar == 1 && bars.bar_small >= 1) {
            cCharacter[0].setHealth(cCharacter[0].getHealth() + 20);
            bars.bar_small--;
            cout << "\n\n\t\tYour health is now: " << cCharacter[0].getHealth();
        }

        else if (choose_bar == 2 && bars.bar_medium >= 1) {
            cCharacter[0].setHealth(cCharacter[0].getHealth() + 30);
            bars.bar_medium--;
            cout << "\n\n\t\tYour health is now: " << cCharacter[0].getHealth();
        }

        else if (choose_bar == 3 && bars.bar_large >= 1) {
            cCharacter[0].setHealth(cCharacter[0].getHealth() + 40);
            bars.bar_large--;
            cout << "\n\n\t\tYour health is now: " << cCharacter[0].getHealth();
        }

        else
            cout << "\n\t\tNot enough bars!";

        cout << "\n\n\t\tWould you like to use another bar? (y/n) ";
        cin >> another_bar;
    } while (another_bar == 'y' || another_bar == 'Y');

    return;
}

void newlines() {
    cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
}

void changeCase(string &convert) {
    for (int i = 0; convert[i]; i++) {
        if (isupper(convert[i]))
            convert[i] = tolower(convert[i]);
        else
            continue;
    }

    convert.at(0) = toupper(convert.at(0));

    return;
}

void bSmith()
{
    Blacksmith shopKeeper; //The shop keeper

    int responce; //Menu navigation
    cout << "*******************************" << endl;
    cout << "*  Welcome to the Blacksmith  *" << endl;
    cout << "*******************************" << "\n" << endl;

    cout << "*****************************" << endl;
    cout << "*     1: Purchase Items     *\n";
    cout << "*       2: Sell Items       *\n";
    cout << "*    3: List Your Items     *\n";
    cout << "*        4: Currency        *\n";
    cout << "*          5: Exit          *\n";
    cout << "*****************************" << endl;
    do
    {
        cout << "Enter Option Here: ";
        cin >> responce;

        switch (responce)
        {
        case 1:
            shopKeeper.buyItem(cCharacter[0]);
            cout << endl;
            break;

        case 2:
            cout << "*****************************" << endl;
            cout << "*       Items To Sell       *" << endl;
            cout << "*****************************" << endl;
            shopKeeper.sellItem(cCharacter[0]);
            cout << endl;
            break;

        case 3:
            cout << "*****************************" << endl;
            cout << "*    Character Inventory    *" << endl;
            cout << "*****************************" << endl;
            cCharacter[0].listInv();
            cout << endl;
            break;

        case 4:
            cout << "*****************************" << endl;
            cout << "*   Current Gold Currency   *" << endl;
            cout << "*****************************" << endl;
            cout << "\t" << cCharacter[0].getCurrency() << endl;
            cout << endl;
            break;

        case 5:
            cout << "*****************************" << endl;
            cout << "*    Thanks for shopping    *" << endl;
            cout << "*****************************" << endl;
            return;

        default:
            cout << "Please enter valid data." << "\n";
            break;
        }
        cout << "*****************************" << endl;
        cout << "*     1: Purchase Items     *\n";
        cout << "*       2: Sell Items       *\n";
        cout << "*    3: List Your Items     *\n";
        cout << "*        4: Currency        *\n";
        cout << "*          5: Exit          *\n";
        cout << "*****************************" << endl;
    } while (responce != 5);

    return;
}

Body:
All I can see that sets  win is this part of the code,

    if (cCharacter[1].getHealth() < 0) {
        ran_pick = 0;
        win = 1;
    }

    else if (cCharacter[1].getHealth() > 0) {
        cout << "\n\t\t<" << cCharacter[1].getName() << "'s turn>" << endl;
        win = 0;
    }

However, if cCharacter[1].getHealth()==0, win will be left unset.


问:
Python Pandas Get a Cumulative Sum (cumsum) which excludes the current row
I am trying to get a cumulative count of a given column that excludes the current row in the dataframe.

My code is shown below. The problem with using cumsum() only is that it includes the current row in the count.

I want df['ExAnte Good Year Count'] to calculate cumsum on an ExAnte basis - ie. excluding the current row from the count.

```<code>d = {
      'Year':[2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008],
      'Good Year':[1, 0, 1, 0, 0, 1, 1, 1, 0]
      'Year Type':['X', 'Y', 'Z', 'Z', 'Z', 'X', 'Y', 'Z', 'Z']
    }

df = pd.DataFrame(d, columns=['Year','Good Year'])
df['ExAnte Good Year Count'] = df['Good Year'].cumsum()
</code>```

UPDATED QUERY:
I would also like to count the cumsum of 'Good Years', grouped by Year Type. I have tried...

```<code>'df['Good Year'].groupby(['Year Type']).shift().cumsum()'
</code>```

...but I get an error which says 'KeyError:'Year Type'

答:
what about this one?

```<code>df['ExAnte Good Year Count'] = df['Good Year'].shift().cumsum()
</code>```

The result should be the following:

```<code>   Year  Good Year  ExAnte Good Year Count
0  2000          1                     NaN
1  2001          0                     1.0
2  2002          1                     1.0
3  2003          0                     2.0
4  2004          0                     2.0
5  2005          1                     2.0
6  2006          1                     3.0
7  2007          1                     4.0
8  2008          0                     5.0
</code>```

Body:
I am trying to get a cumulative count of a given column that excludes the current row in the dataframe.

My code is shown below. The problem with using cumsum() only is that it includes the current row in the count.

I want df['ExAnte Good Year Count'] to calculate cumsum on an ExAnte basis - ie. excluding the current row from the count.

d = {
      'Year':[2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008],
      'Good Year':[1, 0, 1, 0, 0, 1, 1, 1, 0]
      'Year Type':['X', 'Y', 'Z', 'Z', 'Z', 'X', 'Y', 'Z', 'Z']
    }

df = pd.DataFrame(d, columns=['Year','Good Year'])
df['ExAnte Good Year Count'] = df['Good Year'].cumsum()

UPDATED QUERY:
I would also like to count the cumsum of 'Good Years', grouped by Year Type. I have tried...

'df['Good Year'].groupby(['Year Type']).shift().cumsum()'

...but I get an error which says 'KeyError:'Year Type'

Body:
what about this one?

df['ExAnte Good Year Count'] = df['Good Year'].shift().cumsum()

The result should be the following:

   Year  Good Year  ExAnte Good Year Count
0  2000          1                     NaN
1  2001          0                     1.0
2  2002          1                     1.0
3  2003          0                     2.0
4  2004          0                     2.0
5  2005          1                     2.0
6  2006          1                     3.0
7  2007          1                     4.0
8  2008          0                     5.0


问:
Total distinct General Ledger YTD totals in Oracle SQL
The below SQL script gives me line values of distinct general ledger accounts. I simply want them totaled to give me a combined value.</p>

```<code>Select
GLACCT_DESCRIP as "Service Income Account",
(TOTAL_BALANCE*-1) as "Dollars"

From
V_GLACCT_DESCRIP,
V_GLACCT_CURRENT_BALANCE

Where
V_GLACCT_DESCRIP.GLACCT_ID = V_GLACCT_CURRENT_BALANCE.GLACCT_ID
and V_GLACCT_DESCRIP.GLACCT IN ('495500-215','495510-215','495550-215','495560-215')
</code>```

答:
Perhaps this might help.</p>

```<code>SELECT glacct_descrip,
       Sum (total_balance) * -1
FROM   v_glacct_descrip
       INNER JOIN v_glacct_current_balance
               ON v_glacct_descrip.glacct_id =
                  v_glacct_current_balance.glacct_id
WHERE  v_glacct_descrip.glacct IN ( '495500-215', '495510-215', '495550-215',
                                    '495560-215' )
GROUP  BY glacct_descrip;
</code>```

Body:
The below SQL script gives me line values of distinct general ledger accounts. I simply want them totaled to give me a combined value.

Select
GLACCT_DESCRIP as "Service Income Account",
(TOTAL_BALANCE*-1) as "Dollars"

From
V_GLACCT_DESCRIP,
V_GLACCT_CURRENT_BALANCE

Where
V_GLACCT_DESCRIP.GLACCT_ID = V_GLACCT_CURRENT_BALANCE.GLACCT_ID
and V_GLACCT_DESCRIP.GLACCT IN ('495500-215','495510-215','495550-215','495560-215')

Body:
Perhaps this might help.

SELECT glacct_descrip,
       Sum (total_balance) * -1
FROM   v_glacct_descrip
       INNER JOIN v_glacct_current_balance
               ON v_glacct_descrip.glacct_id =
                  v_glacct_current_balance.glacct_id
WHERE  v_glacct_descrip.glacct IN ( '495500-215', '495510-215', '495550-215',
                                    '495560-215' )
GROUP  BY glacct_descrip;


问:
Two layers for loop in `JavaScript`

function convertObjectToList(obj) {
  var innerArr= [];
  var outerArr=[];
  for (var prop in obj) {
    innerArr.push(prop);
    innerArr.push(obj[prop]);
    console.log(innerArr);
    outerArr.push(innerArr);
    console.log(outerArr);
  } return outerArr;
}

convertObjectToList({
  name: 'Holly',
  age: 35,
})```

Can someone help me to figure out what happened inside the for loop?

Q: my question is on the second round: outerArr[0]= [ ‘name’, ‘Holly’ ], but the console shows me outerArr[0]= [ ‘name’, ‘Holly’, ‘age’, 35 ]

Actual output:

1. first round: innerArr=[ ‘name’, ‘Holly’ ]  & outerArr = [ [ ‘name’, ‘Holly’ ] ]

2. second round:
 innerArr=[ ‘name’, ‘Holly’, ‘age’, 35 ] & outerArr=[ [ ‘name’, ‘Holly’, ‘age’, 35 ],[ ‘name’, ‘Holly’, ‘age’, 35 ] ]

But I expeced: outerArr= [ [ ‘name’, ‘Holly’ ], [ ‘name’, ‘Holly’, ‘age’, 35 ] ]

答:
You could create a new copy of the inner array in the loop.

function convertObjectToList(obj) {
  var outerArr=[];
  var innerArr = [];
  var i = 0;
  for (var prop in obj) {
    innerArr = Array.slice(innerArr);
    innerArr.push(prop);
    innerArr.push(obj[prop]);
    outerArr.push(innerArr);
  } return outerArr;
}

console.log(convertObjectToList({
  name: 'Holly',
  age: 35,
}));```

Title: Two layers for loop in `JavaScript`

Body:
function convertObjectToList(obj) {
  var innerArr= [];
  var outerArr=[];
  for (var prop in obj) {
    innerArr.push(prop);
    innerArr.push(obj[prop]);
    console.log(innerArr);
    outerArr.push(innerArr);
    console.log(outerArr);
  } return outerArr;
}

convertObjectToList({
  name: 'Holly',
  age: 35,
})

Can someone help me to figure out what happened inside the for loop?

Q: my question is on the second round: outerArr[0]= [ ‘name’, ‘Holly’ ], but the console shows me outerArr[0]= [ ‘name’, ‘Holly’, ‘age’, 35 ]

Actual output:

1. first round: innerArr=[ ‘name’, ‘Holly’ ]  & outerArr = [ [ ‘name’, ‘Holly’ ] ]

2. second round:
 innerArr=[ ‘name’, ‘Holly’, ‘age’, 35 ] & outerArr=[ [ ‘name’, ‘Holly’, ‘age’, 35 ],[ ‘name’, ‘Holly’, ‘age’, 35 ] ]

But I expeced: outerArr= [ [ ‘name’, ‘Holly’ ], [ ‘name’, ‘Holly’, ‘age’, 35 ] ]


问:
How do I load an externally hosted (CDN) JS library *before* the VueJS instance is created?
I'm trying to integrate Material Design Lite in a VueJS application. I found the following blog-post:

https://posva.net/js/2015/08/26/using-material-design-lite-with-vuejs

Unfortunately, when I add this to my "main.js" file created from the vuejs cli tool I get the following error:

```<code>ERROR in ./src/main.js

  ✘  http://eslint.org/docs/rules/no-undef  'componentHandler' is not defined
  /data/src/main.js:474:5
      componentHandler.upgradeElement(this.el)
</code>```

I pushed a branch to github so the code is visible. It contains:

The commit introducting MDL and the error

The "index.html" file containing the links to the CDN

The VueJS "entry-point" which calls componentHandler

I'm fairly certain that MDL is loaded after the VueJS app is loaded, so the reference does not exist.

How can I make sure VueJS is only loaded after the dependencies are available?

Or, as I'm using webpack to build the code: Is there another way to integrate MDL? Maybe packing it up into the application?

答:
That is a linting error not an actual code error.
The linter couldn't find a method/variable called componentHandler. Doesn't necessarily mean that the code doesn't work, try using window.componentHandler to get the linter to stop complaining. You could also look into linter ignore rules to ignore that specific line and see if it builds then.

The linter runs in the build process in the webpack vue template, so the build will fail since it couldn't find a the reference you used in your vue codebase.
The linter doesn't know about the scripts you load externally in your html files.

As Bert said, I would also remove the defer

If you are unfamiliar with linters, all it does is look over your js code and check that you don't use undefined variables (like in this case), or use wrong indentation, etc. The vue template put the linter in the build process so you won't get a proper build until you have fixed everything the linter wants you to fix. You could disable linting entirely, but I recommend against it as it improves overall code quality if you keep it around imo.

Body:
I'm trying to integrate Material Design Lite in a VueJS application. I found the following blog-post:

https://posva.net/js/2015/08/26/using-material-design-lite-with-vuejs

Unfortunately, when I add this to my "main.js" file created from the vuejs cli tool I get the following error:

ERROR in ./src/main.js

  ✘  http://eslint.org/docs/rules/no-undef  'componentHandler' is not defined
  /data/src/main.js:474:5
      componentHandler.upgradeElement(this.el)

I pushed a branch to github so the code is visible. It contains:

The commit introducting MDL and the error

The "index.html" file containing the links to the CDN

The VueJS "entry-point" which calls componentHandler

I'm fairly certain that MDL is loaded after the VueJS app is loaded, so the reference does not exist.

How can I make sure VueJS is only loaded after the dependencies are available?

Or, as I'm using webpack to build the code: Is there another way to integrate MDL? Maybe packing it up into the application?


问:
How do I strip malicious HTML (XXS etc.) from content submissions?
I have a content submission form that contains multiple fields for input, all of which, when submitted, are entered directly into the database. When this content is requested, it is printed.

I have realized this is a security issue.

How can I strip malicious HTML (XSS) only, while still allowing formatting tags (b, i etc.)?

答:
@pst is correct...you need to explicitly allow certain tags.  But the problem is that the input can be all over the place therefore you'll need to use a library like HTML Tidy (link to Source Forge Project) to get it into a place where you can then DOMDocument::loadHTML the cleaned document.

You should use HTML Tidy to clean your input and get it into a complaint state so you can then explicitly allow certain tags.  Everything else should be removed from your cleaned content before its permanently stored.  (NOTE: for performance reasons do not store BLOBs in your database, store them in your file system and link to them with a file path in a secure location - a location that is not in your web root).

Good luck.


问:
How to split an array from a text file by a comma, only getting one array index displayed in Listbox?
First of all I would like to thank anyone willing to help ahead of time. My issue here is that when I attempt to populate my listbox with items in my array, I am getting only "General" added as a listbox item instead of the actual strings in the array. I'm rather new to programming so I apologize if this is an obvious error in my code, although I'm assuming it probably is.

This is my code:

```<code>Private Sub frmSalesSummary_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
    Dim info() As String = IO.File.ReadAllLines("info.txt")
    Dim splitChar As Char = ","
    Dim infoString As String
    For i = 0 To info.GetUpperBound(0)
        infoString = info(i).Split(splitChar)
        lstSummary.Items.Add(infoString(i))
    Next
End Sub
</code>```

The text file contains this for testing "alex,General,7,$105.00" on the first line.

There may be frequent edits to this question as I am actively trying to figure this out myself as well. Apologies.

答:
A small tip. You should never use controls to store the data you're using. Store it as a list of PersonDetails objects, or whatever you want to call them.

You can declare the PersonDetails object like this ..

```<code>Private Class PersonDetails
    Public Property Name As String
    Public Property Category As String
    Public Property Type As Integer
    Public Property Amount As Decimal
End Class
</code>```

And the list of them like this

```<code>Dim PersonSummaryList As New List(Of PersonDetails)
</code>```

Your form load event reads the text file and for each line, creates a new PersonDetails object and adds it to the list of PersonDetails and then adds the names to a ListBox

```<code>Private Sub frmSalesSummary_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim info() As String = IO.File.ReadAllLines("info.txt")
    Dim splitChar As Char = ","c
    Dim infoString() As String
    For i As Integer = 0 To info.GetUpperBound(0)
        infoString = info(i).Split(splitChar)
        'remove the commas and $ signs
        infoString(3) = infoString(3).Replace("$"c, "")
        Dim newPerson As New PersonDetails
        newPerson.Name = infoString(0)
        newPerson.Category = infoString(1)
        newPerson.Type = Integer.Parse(infoString(2))
        Decimal.TryParse(infoString(3), newPerson.Amount)
        PersonSummaryList.Add(newPerson)
    Next

End Sub
</code>```

In your ListBox, all you will see is a list of names, and when you click on an item, the code below will find the object that matches the name you selected and display whatever properties you want in a MessageBox, but of course you can do whatever you want with the tempPerson object.

```<code>Private Sub LstSummary_SelectedIndexChanged(sender As Object, e As EventArgs) Handles LstSummary.SelectedIndexChanged
    Dim tempPerson As PersonDetails = PersonSummaryList.Find(Function(x) x.Name = LstSummary.SelectedItem.ToString)
    MessageBox.Show("Name :" & tempPerson.Name & vbCrLf & "Amount :" & tempPerson.Amount)
End Sub
</code>```

Body:
First of all I would like to thank anyone willing to help ahead of time. My issue here is that when I attempt to populate my listbox with items in my array, I am getting only "General" added as a listbox item instead of the actual strings in the array. I'm rather new to programming so I apologize if this is an obvious error in my code, although I'm assuming it probably is.

This is my code:

Private Sub frmSalesSummary_Load(sender As Object, e As EventArgs) Handles
MyBase.Load
    Dim info() As String = IO.File.ReadAllLines("info.txt")
    Dim splitChar As Char = ","
    Dim infoString As String
    For i = 0 To info.GetUpperBound(0)
        infoString = info(i).Split(splitChar)
        lstSummary.Items.Add(infoString(i))
    Next
End Sub

The text file contains this for testing "alex,General,7,$105.00" on the first line.

There may be frequent edits to this question as I am actively trying to figure this out myself as well. Apologies.

Body:
A small tip. You should never use controls to store the data you're using. Store it as a list of PersonDetails objects, or whatever you want to call them.

You can declare the PersonDetails object like this ..

Private Class PersonDetails
    Public Property Name As String
    Public Property Category As String
    Public Property Type As Integer
    Public Property Amount As Decimal
End Class

And the list of them like this

Dim PersonSummaryList As New List(Of PersonDetails)

Your form load event reads the text file and for each line, creates a new PersonDetails object and adds it to the list of PersonDetails and then adds the names to a ListBox

Private Sub frmSalesSummary_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim info() As String = IO.File.ReadAllLines("info.txt")
    Dim splitChar As Char = ","c
    Dim infoString() As String
    For i As Integer = 0 To info.GetUpperBound(0)
        infoString = info(i).Split(splitChar)
        'remove the commas and $ signs
        infoString(3) = infoString(3).Replace("$"c, "")
        Dim newPerson As New PersonDetails
        newPerson.Name = infoString(0)
        newPerson.Category = infoString(1)
        newPerson.Type = Integer.Parse(infoString(2))
        Decimal.TryParse(infoString(3), newPerson.Amount)
        PersonSummaryList.Add(newPerson)
    Next

End Sub

In your ListBox, all you will see is a list of names, and when you click on an item, the code below will find the object that matches the name you selected and display whatever properties you want in a MessageBox, but of course you can do whatever you want with the tempPerson object.

Private Sub LstSummary_SelectedIndexChanged(sender As Object, e As EventArgs) Handles LstSummary.SelectedIndexChanged
    Dim tempPerson As PersonDetails = PersonSummaryList.Find(Function(x) x.Name = LstSummary.SelectedItem.ToString)
    MessageBox.Show("Name :" & tempPerson.Name & vbCrLf & "Amount :" & tempPerson.Amount)
End Sub


问:
Filebeat Kubernetes Processor and filtering
I am trying to ship my K8s pod logs to Elasticsearch using Filebeat.

I am following the guide online here: https://www.elastic.co/guide/en/beats/filebeat/6.0/running-on-kubernetes.html

Everything works as expected however I want to filter out events from system pods. My updated config looks like:

```<code>apiVersion: v1
kind: ConfigMap
metadata:
  name: filebeat-prospectors
  namespace: kube-system
  labels:
    k8s-app: filebeat
    kubernetes.io/cluster-service: "true"
data:
  kubernetes.yml: |-
    - type: log
      paths:
        - /var/lib/docker/containers/*/*.log
  multiline.pattern: '^\s'
  multiline.match: after
  json.message_key: log
  json.keys_under_root: true
  processors:
    - add_kubernetes_metadata:
        in_cluster: true
        namespace: ${POD_NAMESPACE}
    - drop_event.when.regexp:
        or:
          kubernetes.pod.name: "weave-net.*"
          kubernetes.pod.name: "external-dns.*"
          kubernetes.pod.name: "nginx-ingress-controller.*"
          kubernetes.pod.name: "filebeat.*"
</code>```

I am trying to ignore weave-net, external-dns, ingress-controller and filebeat events via:

```<code>- drop_event.when.regexp:
    or:
      kubernetes.pod.name: "weave-net.*"
      kubernetes.pod.name: "external-dns.*"
      kubernetes.pod.name: "nginx-ingress-controller.*"
      kubernetes.pod.name: "filebeat.*"
</code>```

However they continue to arrive in Elasticsearch.

答:
The conditions need to be a list:

```<code>- drop_event.when.regexp:
    or:
      - kubernetes.pod.name: "weave-net.*"
      - kubernetes.pod.name: "external-dns.*"
      - kubernetes.pod.name: "nginx-ingress-controller.*"
      - kubernetes.pod.name: "filebeat.*"
</code>```

I'm not sure if your order of parameters works. One of my working examples looks like this:

```<code>- drop_event:
    when:
      or:
        # Exclude traces from Zipkin
        - contains.path: "/api/v"
        # Exclude Jolokia calls
        - contains.path: "/jolokia/?"
        # Exclude pinging metrics
        - equals.path: "/metrics"
        # Exclude pinging health
        - equals.path: "/health"
</code>```

Body:
I am trying to ship my K8s pod logs to Elasticsearch using Filebeat.

I am following the guide online here: https://www.elastic.co/guide/en/beats/filebeat/6.0/running-on-kubernetes.html

Everything works as expected however I want to filter out events from system pods. My updated config looks like:

apiVersion: v1
kind: ConfigMap
metadata:
  name: filebeat-prospectors
  namespace: kube-system
  labels:
    k8s-app: filebeat
    kubernetes.io/cluster-service: "true"
data:
  kubernetes.yml: |-
    - type: log
      paths:
        - /var/lib/docker/containers/*/*.log
  multiline.pattern: '^\s'
  multiline.match: after
  json.message_key: log
  json.keys_under_root: true
  processors:
    - add_kubernetes_metadata:
        in_cluster: true
        namespace: ${POD_NAMESPACE}
    - drop_event.when.regexp:
        or:
          kubernetes.pod.name: "weave-net.*"
          kubernetes.pod.name: "external-dns.*"
          kubernetes.pod.name: "nginx-ingress-controller.*"
          kubernetes.pod.name: "filebeat.*"

I am trying to ignore weave-net, external-dns, ingress-controller and filebeat events via:

- drop_event.when.regexp:
    or:
      kubernetes.pod.name: "weave-net.*"
      kubernetes.pod.name: "external-dns.*"
      kubernetes.pod.name: "nginx-ingress-controller.*"
      kubernetes.pod.name: "filebeat.*"

However they continue to arrive in Elasticsearch.

Body:
The conditions need to be a list:

- drop_event.when.regexp:
    or:
      - kubernetes.pod.name: "weave-net.*"
      - kubernetes.pod.name: "external-dns.*"
      - kubernetes.pod.name: "nginx-ingress-controller.*"
      - kubernetes.pod.name: "filebeat.*"

I'm not sure if your order of parameters works. One of my working examples looks like this:

- drop_event:
    when:
      or:
        # Exclude traces from Zipkin
        - contains.path: "/api/v"
        # Exclude Jolokia calls
        - contains.path: "/jolokia/?"
        # Exclude pinging metrics
        - equals.path: "/metrics"
        # Exclude pinging health
        - equals.path: "/health"


问:
Why does ghci behave differently to runHaskell?
My goal is to pipe some steps for ghci to run from a bash script and then exit cleanly. The commentary online says to use runhaskell for this.

This is the command I'm trying to run:

```<code>ghci> import System.Random

ghci> random (mkStdGen 100) :: (Int, StdGen)
</code>```

With expected result similar to:

```<code>(-3633736515773289454,693699796 2103410263)
</code>```

When I drop this into a file randomtest.hs and execute it with runhaskell I get the following error:.

```<code>randomtest.hs:3:1: error:
    Invalid type signature: random (mkStdGen 100) :: ...
    Should be of form <variable> :: <type>
</code>```

I need a hint to go in the right direction.

My question is: Why does ghci behave differently to runHaskell?

答:
ghci is a REPL (Read, Eval, Print Loop). However, runhaskell is nearly the same as compiling a program into an executable, and then running it. GHCI lets us run individual functions and arbitrary expressions, wheras runhaskell just calls the main function and interprets the file, instead of compiling it, and running that.

As @AJFarmar points out, GHCI is best used to debug and test a program you're building, whilst runhaskell is a nice way to run a whole program without having to compile.

So, to fix your issue, we just need to give the program a main function. ghci calls print on the result of every expression which is typed into the interpreter and not bound to a variable.

So, our main function can just be:

main = print (random (mkStdGen 100) :: (Int, StdGen))

We still need to import System.Random, so the whole file becomes:

```<code>import System.Random

main = print (random (mkStdGen 100) :: (Int, StdGen))
</code>```

Then, we can run as expected:

```<code>[~]λ runhaskell randomtest.hs
(-3633736515773289454,693699796 2103410263)
</code>```

If we want to multiple commands from runhaskell we can just add more to a do block in main:

```<code>import System.Random

main = do
    print (random (mkStdGen 100) :: (Int, StdGen))
    let x = 5 * 5
    print x
    putStrLn "Hello world!"
</code>```

Body:
My goal is to pipe some steps for ghci to run from a bash script and then exit cleanly. The commentary online says to use runhaskell for this.

This is the command I'm trying to run:

ghci> import System.Random

ghci> random (mkStdGen 100) :: (Int, StdGen)

With expected result similar to:

(-3633736515773289454,693699796 2103410263)

When I drop this into a file randomtest.hs and execute it with runhaskell I get the following error:.

randomtest.hs:3:1: error:
    Invalid type signature: random (mkStdGen 100) :: ...
    Should be of form <variable> :: <type>

I need a hint to go in the right direction.

My question is: Why does ghci behave differently to runHaskell?

Body:
ghci is a REPL (Read, Eval, Print Loop). However, runhaskell is nearly the same as compiling a program into an executable, and then running it. GHCI lets us run individual functions and arbitrary expressions, wheras runhaskell just calls the main function and interprets the file, instead of compiling it, and running that.

As @AJFarmar points out, GHCI is best used to debug and test a program you're building, whilst runhaskell is a nice way to run a whole program without having to compile.

So, to fix your issue, we just need to give the program a main function. ghci calls print on the result of every expression which is typed into the interpreter and not bound to a variable.

So, our main function can just be:

main = print (random (mkStdGen 100) :: (Int, StdGen))

We still need to import System.Random, so the whole file becomes:

import System.Random

main = print (random (mkStdGen 100) :: (Int, StdGen))

Then, we can run as expected:

[~]λ runhaskell randomtest.hs
(-3633736515773289454,693699796 2103410263)

If we want to multiple commands from runhaskell we can just add more to a do block in main:

import System.Random

main = do
    print (random (mkStdGen 100) :: (Int, StdGen))
    let x = 5 * 5
    print x
    putStrLn "Hello world!"


问:
Add comma to output
I have created a calculator that shows the output of savings with a specific calculation. I just need the result to be formatted with commas and to be currency so it does not show every number after the decimal. For example if the outcome was:

$2500.566695969
I would only want it to show:
$2,500.56

I hope that makes sense, I tried a couple of things to get the comma in the right place but nothing worked. I am a bit newer to jQuery and this is my first attempt at a calculator like this. Any help is really appreciated. Below is my code.

```<code>function calculate() {
    var savingsVal = (jQuery('#savingsVal').val());
    var totalSavings = 0;
    var regType = (jQuery('#reg-type').val());

    if (filterValues(savingsVal)) {
        totalSavings = savingsVal * 0.15 * 3 - regType * 3;
    }

    jQuery('#totalSavings').val('$' + totalSavings);
}

function filterValues(eVal) {
    return true;
}

jQuery('.results-area').hide();

jQuery('#calculator').submit(function(e) {
    e.preventDefault();
    calculate();
    jQuery('.results-area').show("slow");
    jQuery(this).text( jQuery(this).submit().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") );
});
</code>```

答:
This looks a little obnoxious but below is a working function.

It accepts a string containing a number. It doesn't matter if the string contains a '$' or not.

It returns a string formatted with commas without the preceding '$', but this is easily added of course.

function toCurrency(str) {
    let ret = parseFloat(str[0] === '$' ? str.substr(1) : str).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    if (!isNaN(ret))
 return str;
    return ret;
}

let elem = document.getElementById('money');
elem.innerHTML = '$' + toCurrency(elem.innerHTML);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="money">$2500.566695969</p></code>```

Title: Add comma to output

Body:
I have created a calculator that shows the output of savings with a specific calculation. I just need the result to be formatted with commas and to be currency so it does not show every number after the decimal. For example if the outcome was:

$2500.566695969
I would only want it to show:
$2,500.56

I hope that makes sense, I tried a couple of things to get the comma in the right place but nothing worked. I am a bit newer to jQuery and this is my first attempt at a calculator like this. Any help is really appreciated. Below is my code.

function calculate() {
    var savingsVal = (jQuery('#savingsVal').val());
    var totalSavings = 0;
    var regType = (jQuery('#reg-type').val());

    if (filterValues(savingsVal)) {
        totalSavings = savingsVal * 0.15 * 3 - regType * 3;
    }

    jQuery('#totalSavings').val('$' + totalSavings);
}

function filterValues(eVal) {
    return true;
}

jQuery('.results-area').hide();

jQuery('#calculator').submit(function(e) {
    e.preventDefault();
    calculate();
    jQuery('.results-area').show("slow");
    jQuery(this).text( jQuery(this).submit().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") );
});

Body:
This looks a little obnoxious but below is a working function.

It accepts a string containing a number. It doesn't matter if the string contains a '$' or not.

It returns a string formatted with commas without the preceding '$', but this is easily added of course.

function toCurrency(str) {
    let ret = parseFloat(str[0] === '$' ? str.substr(1) : str).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    if (!isNaN(ret))
 return str;
    return ret;
}

let elem = document.getElementById('money');
elem.innerHTML = '$' + toCurrency(elem.innerHTML);

<p id="money">$2500.566695969</p>