问:
Flow with redux - passing union type gives error
I have this type:

```<code>export type Action<P> = {
  type: string,
  payload: P
}
</code>```

I now need to pass a return type to Dispatch, which I want to be an Action<number> or an Action<boolean>

Why can I not do this?

```<code>const mapDispatchToProps = (dispatch: Dispatch<Action<number | boolean>>) => {
  return bindActionCreators(
    {
      updateAlertModalHeight: updateAlertModalHeight,
      updateAlertModalIsOpen: updateAlertModalIsOpen,
      updateHasYesNo: updateAlertModalHasYesNo
    },
    dispatch
  )
}
</code>```

It doesn't let me do Action<number> | Action<boolean> either.

The error is:

Cannot call bindActionCreators because number [1] is incompatible
  with boolean [2] in type argument P [3] of type argument A [4] of
  property updateAlertModalHeight of type argument C. (References:
  [1] [2] [3] [4])flow

Where am I going wrong?

Here is updateAlertModalHeight from the error message:

```<code>export const updateAlertModalHeight: ActionCreator<Action<number>, number> = (
  payload
) => ({
  type: UPDATE_ALERT_MODAL_HEIGHT,
  payload
})
</code>```

and:

```<code>export const updateAlertModalIsOpen: ActionCreator<Action<boolean>, boolean> = (
  payload
) => ({
  type: UPDATE_ALERT_MODAL_IS_OPEN,
  payload
})
</code>```

the two action creators have a different type and Flow is not allowing them to be used in the same bindActionCreators call. How do I get flow to allow it?

It all seems to work when I make everything this type:

```<code>export type ActionT = Action<boolean | string | number>

export const updateAlertModalIsOpen: ActionCreator<ActionT, boolean> = (
  payload
) => ({
  type: UPDATE_ALERT_MODAL_IS_OPEN,
  payload
})
</code>```

and:

```<code>const mapDispatchToProps = (dispatch: Dispatch<ActionT>) => {
</code>```

But that is less specific typing which sucks because it doesn't describe which type of action is being returned.

I would like to edit the redux type definitions to allow multiple Action types but it is difficult to understand what change to make.

答:
To move forward I have gotten flow to be quiet by getting rid of my custom type Action and am importing Redux's type Action E.G. import type { Action } from 'redux'. The one Redux uses is

```<code>  declare export type Action<T> = {
    type: T
  }
</code>```

I find it a bit weird because the type field is always a string in a redux action. E.G 'UPDATE_ALERT_MODAL_IS_OPEN'. So it is pointless to specify string. I always type them with Action<string>

My action creator becomes:

```<code>export const updateAlertModalIsOpen: ActionCreator<Action<string>, boolean> = (
  payload
) => ({
  type: UPDATE_ALERT_MODAL_IS_OPEN,
  payload
})
</code>```

mapDispatchToProps becomes:

```<code>const mapDispatchToProps = (dispatch: Dispatch<Action<string>>) => {
  return bindActionCreators(
    {
      updateAlertModalIsOpen,
      updateAlertModalHeight,
      updateHasYesNo: updateAlertModalHasYesNo
    },
    dispatch
  )
}
</code>```

Body:
I have this type:

export type Action
 = {
  type: string,
  payload: P
}

I now need to pass a return type to Dispatch, which I want to be an Action<number> or an Action<boolean>

Why can I not do this?

const mapDispatchToProps = (dispatch: Dispatch<Action<number | boolean>>) => {
  return bindActionCreators(
    {
      updateAlertModalHeight: updateAlertModalHeight,
      updateAlertModalIsOpen: updateAlertModalIsOpen,
      updateHasYesNo: updateAlertModalHasYesNo
    },
    dispatch
  )
}

It doesn't let me do Action<number> | Action<boolean> either.

The error is:

Cannot call bindActionCreators because number [1] is incompatible
  with boolean [2] in type argument P [3] of type argument A [4] of
  property updateAlertModalHeight of type argument C. (References:
  [1] [2] [3] [4])flow

Where am I going wrong?

Here is updateAlertModalHeight from the error message:

export const updateAlertModalHeight: ActionCreator<Action<number>, number> = (
  payload
) => ({
  type: UPDATE_ALERT_MODAL_HEIGHT,
  payload
})

and:

export const updateAlertModalIsOpen: ActionCreator<Action<boolean>, boolean> = (
  payload
) => ({
  type: UPDATE_ALERT_MODAL_IS_OPEN,
  payload
})

the two action creators have a different type and Flow is not allowing them to be used in the same bindActionCreators call. How do I get flow to allow it?

It all seems to work when I make everything this type:

export type ActionT = Action<boolean | string | number>

export const updateAlertModalIsOpen: ActionCreator<ActionT, boolean> = (
  payload
) => ({
  type: UPDATE_ALERT_MODAL_IS_OPEN,
  payload
})

and:

const mapDispatchToProps = (dispatch: Dispatch<ActionT>) => {

But that is less specific typing which sucks because it doesn't describe which type of action is being returned.

I would like to edit the redux type definitions to allow multiple Action types but it is difficult to understand what change to make.

Body:
To move forward I have gotten flow to be quiet by getting rid of my custom type Action and am importing Redux's type Action E.G. import type { Action } from 'redux'. The one Redux uses is

  declare export type Action<T> = {
    type: T
  }

I find it a bit weird because the type field is always a string in a redux action. E.G 'UPDATE_ALERT_MODAL_IS_OPEN'. So it is pointless to specify string. I always type them with Action<string>

My action creator becomes:

export const updateAlertModalIsOpen: ActionCreator<Action<string>, boolean> = (
  payload
) => ({
  type: UPDATE_ALERT_MODAL_IS_OPEN,
  payload
})

mapDispatchToProps becomes:

const mapDispatchToProps = (dispatch: Dispatch<Action<string>>) => {
  return bindActionCreators(
    {
      updateAlertModalIsOpen,
      updateAlertModalHeight,
      updateHasYesNo: updateAlertModalHasYesNo
    },
    dispatch
  )
}


来源: stackexchange

问:
List of all imports in python 3
How to find out list of all available imports in python 3 via program? I tried this at first, but couldn't understand what it returned

```<code>import sys
    sys.modules
</code>```

I think this isn't the way, although this struck my mind first. I searched the web and found this http://effbot.org/librarybook/core-modules-index.htm

Can someone tell me whether this is correct or not?

答:
Why would you want to do that?

In any case, I doubt your link is relevant for what you are asking. The list of available modules that ships with python is here:

http://docs.python.org/py3k/library/index.html

The list of modules that are built in is here:

```<code>sys.builtin_module_names
</code>```

To get a list of everything you can import, including installed modules, you would have to go through the sys.path and look for modules "manually", which is not an entirely trivial task, considering these can be both python files, compiled files like .so and .dll, directories and even zip files, and you would have to handle pth files too.

However, I don't see any need for ever doing that.

ContentLicense: CC BY-SA 3.0

Title: List of all imports in python 3

Body:
How to find out list of all available imports in python 3 via program? I tried this at first, but couldn't understand what it returned

import sys
    sys.modules

I think this isn't the way, although this struck my mind first. I searched the web and found this http://effbot.org/librarybook/core-modules-index.htm

Can someone tell me whether this is correct or not?

Body:
Why would you want to do that?

In any case, I doubt your link is relevant for what you are asking. The list of available modules that ships with python is here:

http://docs.python.org/py3k/library/index.html

The list of modules that are built in is here:

sys.builtin_module_names

To get a list of everything you can import, including installed modules, you would have to go through the sys.path and look for modules "manually", which is not an entirely trivial task, considering these can be both python files, compiled files like .so and .dll, directories and even zip files, and you would have to handle pth files too.

However, I don't see any need for ever doing that.


问:
React Hooks - Should I use 'useState' for state that is unchanging?
When I initially learned React Component's I was always told to put everything in this.state. Whether it be some pieces of data that update frequently or some that never update at all.

However, with the implementation of React hooks, I'm not sure how frequently I should use useState even when the state will not update.

Let me give you an example of some of my form logic:

```<code>const FormAuth = props => {
    //Frequently updates
    const [validInput, setValidInput] = useState({
        isCompletedForm: Boolean,
        firstName: Boolean,
        lastName: Boolean,
        email: Boolean,
        password: Boolean,
        confirmPassword: Boolean
    });

    // Never updates
    const [formSchema, setFormSchema] = useState({
        firstName: Joi.string().required(),
        lastName: Joi.string().required(),
        email: Joi.string().required().email().regex(emailRegex),
        password: Joi.string().required().regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$^+=!*()@%&?.]).{8,30}$/),
        confirmPassword: Joi.string().required()
    })

    // Never updates
    const [inputRef, setInputRef] = useState({
        firstNameRef: React.createRef(),
        lastNameRef: React.createRef(),
        emailRef: React.createRef(),
        passwordRef: React.createRef(),
        confirmPasswordRef: React.createRef()
    });

    // render some JSX
}
</code>```

Here I have 3 states. The first state are Booleans that say if the inputs look good. The second state is a formSchema which will never be updated. Lastly, the third state is the Refs for each of the inputs which will also never be updated.

My question is: Would is make more sense to only have one state for validInputs since it updates frequently, and then for formSchema and inputRef create a const object with vanilla javascript? Or should everything go into state like before?

It seems to me that it would make more sense to only use useState if that state is going to update, but I'm trying to see what is the proper convention for hooks moving forward.

答:
i am scared that your frequently updated state are in object. yeah you can do that but it not an good way to update your individual state by putting them in object.

 you don't need to keep data in state if it is not changing or updating. you can assign that type of data in some variables.

//you can track your state value and state change by this function
//you can use this same function in different component
export function useFormInput(initialValue = "") {
    const [input, setInput] = useState(initialValue);
    function handleInputChange(e) {
        setInput(e.target.value);
    }

    return {
        value: input,
        onChange: handleInputChange,
    }
}

const FormAuth = props => {
  //Frequently updates
  //useFormInput function will return input value and unchange function
  const firstName = useFormInput();
  const lastName = useFormInput();

  // Never updates
  //here your not updating data is assigned in formSchema variable
  const formSchema = {
    firstName: Joi.string().required(),
    lastName: Joi.string().required(),
    email: Joi.string().required().email().regex(emailRegex),
    password: Joi.string().required().regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$^+=!*()@%&?.]).{8,30}$/),
    confirmPassword: Joi.string().required()
  }

  // Never updates
  const inputRef = {
    firstNameRef: React.createRef(),
    lastNameRef: React.createRef(),
    emailRef: React.createRef(),
    passwordRef: React.createRef(),
    confirmPasswordRef: React.createRef()
  }

  return(

      //firstname value and onchange function will be
      //assigned useing spread operator
      <input {...firstName} placeholder="first name"/>
      <input {...lastName} placeholder="last name"/>

  )
}```

ContentLicense: CC BY-SA 4.0

Body:
When I initially learned React Component's I was always told to put everything in this.state. Whether it be some pieces of data that update frequently or some that never update at all.

However, with the implementation of React hooks, I'm not sure how frequently I should use useState even when the state will not update.

Let me give you an example of some of my form logic:

const FormAuth = props => {
    //Frequently updates
    const [validInput, setValidInput] = useState({
        isCompletedForm: Boolean,
        firstName: Boolean,
        lastName: Boolean,
        email: Boolean,
        password: Boolean,
        confirmPassword: Boolean
    });

    // Never updates
    const [formSchema, setFormSchema] = useState({
        firstName: Joi.string().required(),
        lastName: Joi.string().required(),
        email: Joi.string().required().email().regex(emailRegex),
        password: Joi.string().required().regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$^+=!*()@%&?.]).{8,30}$/),
        confirmPassword: Joi.string().required()
    })

    // Never updates
    const [inputRef, setInputRef] = useState({
        firstNameRef: React.createRef(),
        lastNameRef: React.createRef(),
        emailRef: React.createRef(),
        passwordRef: React.createRef(),
        confirmPasswordRef: React.createRef()
    });

    // render some JSX
}

Here I have 3 states. The first state are Booleans that say if the inputs look good. The second state is a formSchema which will never be updated. Lastly, the third state is the Refs for each of the inputs which will also never be updated.

My question is: Would is make more sense to only have one state for validInputs since it updates frequently, and then for formSchema and inputRef create a const object with vanilla javascript? Or should everything go into state like before?

It seems to me that it would make more sense to only use useState if that state is going to update, but I'm trying to see what is the proper convention for hooks moving forward.

Body:
i am scared that your frequently updated state are in object. yeah you can do that but it not an good way to update your individual state by putting them in object.

 you don't need to keep data in state if it is not changing or updating. you can assign that type of data in some variables.

//you can track your state value and state change by this function
//you can use this same function in different component
export function useFormInput(initialValue = "") {
    const [input, setInput] = useState(initialValue);
    function handleInputChange(e) {
        setInput(e.target.value);
    }

    return {
        value: input,
        onChange: handleInputChange,
    }
}

const FormAuth = props => {
  //Frequently updates
  //useFormInput function will return input value and unchange function
  const firstName = useFormInput();
  const lastName = useFormInput();

  // Never updates
  //here your not updating data is assigned in formSchema variable
  const formSchema = {
    firstName: Joi.string().required(),
    lastName: Joi.string().required(),
    email: Joi.string().required().email().regex(emailRegex),
    password: Joi.string().required().regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[#$^+=!*()@%&?.]).{8,30}$/),
    confirmPassword: Joi.string().required()
  }

  // Never updates
  const inputRef = {
    firstNameRef: React.createRef(),
    lastNameRef: React.createRef(),
    emailRef: React.createRef(),
    passwordRef: React.createRef(),
    confirmPasswordRef: React.createRef()
  }

  return(
    <div>
      //firstname value and onchange function will be
      //assigned useing spread operator
      <input {...firstName} placeholder="first name"/>
      <input {...lastName} placeholder="last name"/>
    </div>
  )
}


问:
Why Let Docker Choose a Port
What is the use-case for letting docker choose a port range automatically with the -P flag?

Is this just convenience so that you don't have to explicitly pass a specific port? But then any thing needing to access that service would need to know the port right?

答:
As far use-case this is very important to let the docker choose port automatically in some cases like blue-green deployment on a single host.

For Instance, You running your container on AWS ECS and there is one EC2 instance so you would not able to do a blue-green deployment, in this, you will get an error something like

service test was unable to place a task because no container instance met all of its requirements. The closest matching container-instance 97d97ce9-967d-49ad-83ad-f4f904aae1f6 is already using a port required by your task. For more information, see the Troubleshooting section.

You can also look into this article,

If you have a service with 2 containers (tasks), you need at least 2 ECS container instances because multiple containers can’t run on the same port on the same server, each container is hosted on a separate server. So in order to run multiple containers over the same container instance, we need Dynamic port mapping!

This is in the context of AWS, you can replicate in your case as well by deploying multiple services on your host using dynamic port mapping.

understanding-dynamic-port-mapping-in-amazon-ecs-with-application-load-balancer

This is one case, another case can be, you would able to run multiple services of the same docker container because all need the same port, which can be achieved using the dynamic port.

Another case can be the Wowza streaming engine which needs a dynamic port or range of port to publish and get the stream from the client.

Dynamic port mapping explains here in case of AWS.

https://aws.amazon.com/premiumsupport/knowledge-center/dynamic-port-mapping-ecs/

Title: Why Let Docker Choose a Port


问:
ngClass calls method Multiple times
I have created a method and attached it to ngClass for adding two styles depending upon the condition.I am also passing the number as parameter to be used in the switch case.

component.html

```<code><div class="circle" [ngClass]="setMyClassesCircle(1)">
<div class="circle" [ngClass]="setMyClassesCircle(2)">
<div class="circle" [ngClass]="setMyClassesCircle(3)">
<div class="circle" [ngClass]="setMyClassesCircle(4)">
</code>```

component.ts

```<code> setMyClassesCircle(val)
 {
   let circleClasses
   console.log('Inside method')

   switch(val)
   {

     case 1:
     {

    circleClasses = {
   'inprogress-circle': this.inProgress == val,
   'completed-circle': this.oneCompleted == true

   }
     break;
   }
   case 2:
   {
    circleClasses = {
   'inprogress-circle': this.inProgress == val,
   'completed-circle': this.twoCompleted == true
   }
     break;
   }
   case 3:
   {
    circleClasses = {
   'inprogress-circle': this.inProgress == val,
   'completed-circle': this.threeCompleted == true
   }
     break;
   }
   case 4:
   {
    circleClasses = {
   'inprogress-circle': this.inProgress == val,
   'completed-circle': this.fourCompleted == true
   }
     break;
   }
</code>```

Through this way I am binding circleClasses to my template.

But the issue I am facing is setMyClassesCircle() method is called more than 10 times, while I am calling the method only four times.'Inside method' is printed more than 10 times in my console.

I could not figure out why the method is being called these many number of times.

答: Angular runs changedetection life cycle several times to determine if the outcome of your function has changed. It'll run it every time you click things or similar events happen to determine if things have changed again. Binding values to functions is not advised for this reason, instead you should calculate the values in your .ts file and just bind against the precalculated values.</p>

Title: ngClass calls method Multiple times

Body:
I have created a method and attached it to ngClass for adding two styles depending upon the condition.I am also passing the number as parameter to be used in the switch case.

component.html

component.ts

 setMyClassesCircle(val)
 {
   let circleClasses
   console.log('Inside method')

   switch(val)
   {

     case 1:
     {

    circleClasses = {
   'inprogress-circle': this.inProgress == val,
   'completed-circle': this.oneCompleted == true

   }
     break;
   }
   case 2:
   {
    circleClasses = {
   'inprogress-circle': this.inProgress == val,
   'completed-circle': this.twoCompleted == true
   }
     break;
   }
   case 3:
   {
    circleClasses = {
   'inprogress-circle': this.inProgress == val,
   'completed-circle': this.threeCompleted == true
   }
     break;
   }
   case 4:
   {
    circleClasses = {
   'inprogress-circle': this.inProgress == val,
   'completed-circle': this.fourCompleted == true
   }
     break;
   }

Through this way I am binding circleClasses to my template.

But the issue I am facing is setMyClassesCircle() method is called more than 10 times, while I am calling the method only four times.'Inside method' is printed more than 10 times in my console.

I could not figure out why the method is being called these many number of times.


问:
A Query regarding the value of Exit Status of Child Process Created with fork()
Just have a query about Status of Child processes created with fork()

```<code>#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main (){
    int pid;
    int status;

    printf("Parent: %d\n", getpid());

    pid = fork();
    if (pid == 0){
        printf("Child %d\n", getpid());
        sleep(4);
        exit(1);
       }

  waitpid(pid, &status, 0);

  printf("The status of child is %u\n",status);

  printf("Parent: %d\n", getpid());

  return 0;
  }
</code>```

I expect the status to print 1 , but it prints 256(a byte of 0's is added )

Can someone explain why is this? I am a newbie to C , so please excuse as this question may appear silly to the experts.

答:
From man waitpid:

If wstatus is not NULL, wait() and waitpid() store status information
         in the int to which it points.  This integer can be inspected with
         the following macros (which take the integer itself as an argument,
         not a pointer to it, as is done in wait() and waitpid()!):

WEXITSTATUS(stat_val)

If the value of WIFEXITED(stat_val) is non-zero, this macro evaluates to the low-order 8 bits of the status argument that the child process passed to _exit() or exit(), or the value the child process returned from main().

So you should:

```<code>printf("The status of child is %u\n", WEXITSTATUS(status));
</code>```

Body:
Just have a query about Status of Child processes created with fork()

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>

int main (){
    int pid;
    int status;

    printf("Parent: %d\n", getpid());

    pid = fork();
    if (pid == 0){
        printf("Child %d\n", getpid());
        sleep(4);
        exit(1);
       }

  waitpid(pid, &status, 0);

  printf("The status of child is %u\n",status);

  printf("Parent: %d\n", getpid());

  return 0;
  }

I expect the status to print 1 , but it prints 256(a byte of 0's is added )

Can someone explain why is this? I am a newbie to C , so please excuse as this question may appear silly to the experts.

Body:
From man waitpid:

If wstatus is not NULL, wait() and waitpid() store status information
         in the int to which it points.  This integer can be inspected with
         the following macros (which take the integer itself as an argument,
         not a pointer to it, as is done in wait() and waitpid()!):

WEXITSTATUS(stat_val)

If the value of WIFEXITED(stat_val) is non-zero, this macro evaluates to the low-order 8 bits of the status argument that the child process passed to _exit() or exit(), or the value the child process returned from main().

So you should:

printf("The status of child is %u\n", WEXITSTATUS(status));


答:
I think it called many times because of angular change detection, the cleaner solution is to use ngclass in-line like this:</p>

```<code>    <div class="circle" [ngClass]="{
        'inprogress-circle': inProgress == 1,
       'completed-circle': oneCompleted == true }" >

 <div class="circle" [ngClass]="{
        'inprogress-circle': inProgress == 2,
       'completed-circle': oneCompleted == true }" >

 <div class="circle" [ngClass]="{
        'inprogress-circle': inProgress == 3,
       'completed-circle': oneCompleted == true }" >

 <div class="circle" [ngClass]="{
        'inprogress-circle': inProgress == 4,
       'completed-circle': oneCompleted == true }" >
</code>```

Title: ngClass calls method Multiple times

Body:
I think it called many times because of angular change detection, the cleaner solution is to use ngclass in-line like this:

    <div class="circle" [ngClass]="{
        'inprogress-circle': inProgress == 1,
       'completed-circle': oneCompleted == true }" >

 <div class="circle" [ngClass]="{
        'inprogress-circle': inProgress == 2,
       'completed-circle': oneCompleted == true }" >

 <div class="circle" [ngClass]="{
        'inprogress-circle': inProgress == 3,
       'completed-circle': oneCompleted == true }" >

 <div class="circle" [ngClass]="{
        'inprogress-circle': inProgress == 4,
       'completed-circle': oneCompleted == true }" >


问:
What is the most efficient way to deep clone an object in JavaScript?
What is the most efficient way to clone a JavaScript object? I've seen obj = eval(uneval(o)); being used, but that's non-standard and only supported by Firefox.

 I've done things like obj = JSON.parse(JSON.stringify(o)); but question the efficiency.

 I've also seen recursive copying functions with various flaws.

I'm surprised no canonical solution exists.

答:
Object.assign({},sourceObj) only clones the object if their property is not having reference type key.
ex

```<code>obj={a:"lol",b:["yes","no","maybe"]}
clonedObj = Object.assign({},obj);

clonedObj.b.push("skip")// changes will reflected to the actual obj as well because of its reference type.
obj.b //will also console => yes,no,maybe,skip
</code>```

So for the deep cloning is not possible to achieve in this way.

The best solution that works is

```<code>var obj = Json.stringify(yourSourceObj)
var cloned = Json.parse(obj);
</code>```

LastEditorDisplayName: JasonBunting

Body:
Object.assign({},sourceObj) only clones the object if their property is not having reference type key.
ex

obj={a:"lol",b:["yes","no","maybe"]}
clonedObj = Object.assign({},obj);

clonedObj.b.push("skip")// changes will reflected to the actual obj as well because of its reference type.
obj.b //will also console => yes,no,maybe,skip

So for the deep cloning is not possible to achieve in this way.

The best solution that works is

var obj = Json.stringify(yourSourceObj)
var cloned = Json.parse(obj);


问:
How to show progress dialog (in separate thread?) while processing some code in main thread

I need to do the following: when app is started it runs an activity (splashActivity) which tries to create an DBHelper (SQLiteDatabase) instance which at creation time checks if database is exists and creates one if it doesn't.

In this DB creation process i want to show the ProgressDialog and prevent the main thread to process while DB is not ready.

the splashActivity:

```<code>public class SplashActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);
        showSplash();
        DBHelper dbHelper = new DBHelper(this);
        dbHelper.close();
  }
}
</code>```

the DBHelper class:

```<code>public class DBHelper extends SQLiteOpenHelper {
...
    private ProgressDialog mProgressDialog;
...
  public DBHelper(Context context) {
    super(context, DB_NAME, null, 1);
    appContext=context;
    dbReadable = getReadableDatabase();
    if (createDB)
        initDB();
  }
  @Override
  public void onCreate(SQLiteDatabase db) {
      createDB=true;
  }
  public void initDB() {
      ...
      if (createDB)
          restoreDB();
      ...
  }

  private void restoreDB(){
   // place for db creation/restoring method call (restoreDBFromFile() etc)
   // and displaying the progress
  }
</code>```

I tried to make AsyncTask as DBHelper's inner class:

```<code>  private class RestoreDBTask extends AsyncTask <Void, Void, String>
    {
        private ProgressDialog dialog;

        @Override
        protected void onPreExecute()
        {
            this.dialog = ProgressDialog.show(DBHelper.this.appContext, DBHelper.this.appContext.getResources().getString(R.string.progress_wait),
                    DBHelper.this.appContext.getResources().getString(R.string.progress_db_installing), true);
        }

        @Override
        protected String doInBackground(Void... params)
        {
            restoreDBFromFile();
            return "";
        }

        @Override
        protected void onPostExecute(String result)
        {
            this.dialog.dismiss();
        }
    }
</code>```

so the restoreDB() was:

```<code>restoreDB() {
      RestoreDBTask task = new RestoreDBTask();
      task.execute();
}
</code>```

it starts task showing PD but meanwhile the main thread continues and so it crashes cause DB wasn't ready. That means main thread should be suspended while DB is not ready so i tried to sleep/wait/join with no success. Ok. it's not good anyway.

Next time i made call to restoreDBFromFile() from restoreDB() so that async task was used only for PD displaying:

```<code>restoreDB() {
  RestoreDBTask task = new RestoreDBTask();
  task.execute();
  restoreDBFromFile();
}
</code>```

It doesn't display any PD. So I tried to create PD right in the restoreDB():

```<code>restoreDB() {
   mProgressDialog = ProgressDialog.show(appContext,
          appContext.getResources().getString(R.string.progress_wait),
          appContext.getResources().getString(R.string.progress_db_installing),
          true);
  restoreDBFromFile();
}
</code>```

but no PD either! Next time i tried the following:

```<code>    restoreDB() {
      Thread thread =  new Thread(null, new Runnable(){
              @Override
              public void run() {
                  mProgressDialog = ProgressDialog.show(appContext,
                          appContext.getResources().getString(R.string.progress_wait),
                          appContext.getResources().getString(R.string.progress_db_installing),
                          true);
              }
          }, "ProgressDialog");
      thread.start();
      restoreDBFromFile();
}
</code>```

once again got no PD and got immediate crash:

04-12 08:40:38.894:
  ERROR/AndroidRuntime(2448): ERROR:
  thread attach failed 04-12
  08:40:38.913: DEBUG/dalvikvm(2448):
  LinearAlloc 0x0 used 639500 of 5242880
  (12%) 04-12 08:40:39.094:
  DEBUG/ddm-heap(2454): Got feature list
  request 04-12 08:40:39.492:
  WARN/dalvikvm(2454): threadid=15:
  thread exiting with uncaught exception
  (group=0x4001b188) 04-12 08:40:39.492:
  ERROR/AndroidRuntime(2454): Uncaught
  handler: thread ProgressDialog exiting
  due to uncaught exception 04-12
  08:40:39.504:
  ERROR/AndroidRuntime(2454):
  java.lang.RuntimeException: Can't
  create handler inside thread that has
  not called Looper.prepare() 04-12
  08:40:39.504:
  ERROR/AndroidRuntime(2454):     at
  android.os.Handler.(Handler.java:121)
  04-12 08:40:39.504:
  ERROR/AndroidRuntime(2454):     at
  android.app.Dialog.(Dialog.java:105)
  04-12 08:40:39.504:
  ERROR/AndroidRuntime(2454):     at
  android.app.AlertDialog.(AlertDialog.java:63)
  04-12 08:40:39.504:
  ERROR/AndroidRuntime(2454):     at
  android.app.ProgressDialog.(ProgressDialog.java:80)
  04-12 08:40:39.504:
  ERROR/AndroidRuntime(2454):     at
  android.app.ProgressDialog.(ProgressDialog.java:76)
  04-12 08:40:39.504:
  ERROR/AndroidRuntime(2454):     at
  android.app.ProgressDialog.show(ProgressDialog.java:101)
  04-12 08:40:39.504:
  ERROR/AndroidRuntime(2454):     at
  android.app.ProgressDialog.show(ProgressDialog.java:90)
  04-12 08:40:39.504:
  ERROR/AndroidRuntime(2454):     at
  com.taxiorder.DBHelper$1.run(DBHelper.java:157)
  04-12 08:40:39.504:
  ERROR/AndroidRuntime(2454):     at
  java.lang.Thread.run(Thread.java:1096)

.

Tried a few more things with no result... So I just can't figure out what's wrong.

Once again - I just need to show PD while restoreDB() executing. I can't run restoreDB() in separate thread because I need it finished before app can proceed. As I can see PD should be run in separate thread only but i can't manage it.

Now I have 2 additional questions:

1) If a PD should be created in separate thread could it be created and showed if it's thread doesn't do anything at all. I mean something like this:

```<code>    new Thread(){
          public void run(){
              mProgressDialog = ProgressDialog.show(appContext,
                      appContext.getResources().getString(R.string.progress_wait),
                      appContext.getResources().getString(R.string.progress_db_installing),
                      true);

      }.start();
</code>```

As I understand the thread dies immediately after executing run() cause there is nothing to do and so PD doesn't show.

2) PD by itself doesn't suspend any thread while displaying, does it?

答:
Try to declare AsyncTask as an inner class for the activity, instantiate and execute it there. I think the problem is in context given to ProgressDialog when you are creating it, your logic for doing this is too complicated. Declaring AsyncTask in activity is more common practice.

Then, AsyncTask must do all you need with DB in doInBackground method

```<code>public class SplashActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        new RestoreDBTask().execute();
    }

}

private class RestoreDBTask extends AsyncTask <Void, Void, String>
{
    private ProgressDialog dialog;

    @Override
    protected void onPreExecute()
    {
        dialog = ProgressDialog.show(
            SplashActivity.this,
            getString(R.string.progress_wait),
            getString(R.string.progress_db_installing),
            true);
    }

    @Override
    protected String doInBackground(Void... params)
    {
        // do all the things with DB
        DBHelper dbHelper = new DBHelper(SplashActivity.this);
        dbHelper.close();
        return "";
    }

    @Override
    protected void onPostExecute(String result)
    {
        dialog.dismiss();
    }
}
</code>```

Body:
I need to do the following: when app is started it runs an activity (splashActivity) which tries to create an DBHelper (SQLiteDatabase) instance which at creation time checks if database is exists and creates one if it doesn't.

In this DB creation process i want to show the ProgressDialog and prevent the main thread to process while DB is not ready.

the splashActivity:

public class SplashActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);
        showSplash();
        DBHelper dbHelper = new DBHelper(this);
        dbHelper.close();
  }
}

the DBHelper class:

public class DBHelper extends SQLiteOpenHelper {
...
    private ProgressDialog mProgressDialog;
...
  public DBHelper(Context context) {
    super(context, DB_NAME, null, 1);
    appContext=context;
    dbReadable = getReadableDatabase();
    if (createDB)
        initDB();
  }
  @Override
  public void onCreate(SQLiteDatabase db) {
      createDB=true;
  }
  public void initDB() {
      ...
      if (createDB)
          restoreDB();
      ...
  }

  private void restoreDB(){
   // place for db creation/restoring method call (restoreDBFromFile() etc)
   // and displaying the progress
  }

I tried to make AsyncTask as DBHelper's inner class:

  private class RestoreDBTask extends AsyncTask <Void, Void, String>
    {
        private ProgressDialog dialog;

        @Override
        protected void onPreExecute()
        {
            this.dialog = ProgressDialog.show(DBHelper.this.appContext, DBHelper.this.appContext.getResources().getString(R.string.progress_wait),
                    DBHelper.this.appContext.getResources().getString(R.string.progress_db_installing), true);
        }

        @Override
        protected String doInBackground(Void... params)
        {
            restoreDBFromFile();
            return "";
        }

        @Override
        protected void onPostExecute(String result)
        {
            this.dialog.dismiss();
        }
    }

so the restoreDB() was:

restoreDB() {
      RestoreDBTask task = new RestoreDBTask();
      task.execute();
}

it starts task showing PD but meanwhile the main thread continues and so it crashes cause DB wasn't ready. That means main thread should be suspended while DB is not ready so i tried to sleep/wait/join with no success. Ok. it's not good anyway.

Next time i made call to restoreDBFromFile() from restoreDB() so that async task was used only for PD displaying:

restoreDB() {
  RestoreDBTask task = new RestoreDBTask();
  task.execute();
  restoreDBFromFile();
}

It doesn't display any PD. So I tried to create PD right in the restoreDB():

restoreDB() {
   mProgressDialog = ProgressDialog.show(appContext,
          appContext.getResources().getString(R.string.progress_wait),
          appContext.getResources().getString(R.string.progress_db_installing),
          true);
  restoreDBFromFile();
}

but no PD either! Next time i tried the following:

    restoreDB() {
      Thread thread =  new Thread(null, new Runnable(){
              @Override
              public void run() {
                  mProgressDialog = ProgressDialog.show(appContext,
                          appContext.getResources().getString(R.string.progress_wait),
                          appContext.getResources().getString(R.string.progress_db_installing),
                          true);
              }
          }, "ProgressDialog");
      thread.start();
      restoreDBFromFile();
}

once again got no PD and got immediate crash:

04-12 08:40:38.894:
  ERROR/AndroidRuntime(2448): ERROR:
  thread attach failed 04-12
  08:40:38.913: DEBUG/dalvikvm(2448):
  LinearAlloc 0x0 used 639500 of 5242880
  (12%) 04-12 08:40:39.094:
  DEBUG/ddm-heap(2454): Got feature list
  request 04-12 08:40:39.492:
  WARN/dalvikvm(2454): threadid=15:
  thread exiting with uncaught exception
  (group=0x4001b188) 04-12 08:40:39.492:
  ERROR/AndroidRuntime(2454): Uncaught
  handler: thread ProgressDialog exiting
  due to uncaught exception 04-12
  08:40:39.504:
  ERROR/AndroidRuntime(2454):
  java.lang.RuntimeException: Can't
  create handler inside thread that has
  not called Looper.prepare() 04-12
  08:40:39.504:
  ERROR/AndroidRuntime(2454):     at
  android.os.Handler.(Handler.java:121)
  04-12 08:40:39.504:
  ERROR/AndroidRuntime(2454):     at
  android.app.Dialog.(Dialog.java:105)
  04-12 08:40:39.504:
  ERROR/AndroidRuntime(2454):     at
  android.app.AlertDialog.(AlertDialog.java:63)
  04-12 08:40:39.504:
  ERROR/AndroidRuntime(2454):     at
  android.app.ProgressDialog.(ProgressDialog.java:80)
  04-12 08:40:39.504:
  ERROR/AndroidRuntime(2454):     at
  android.app.ProgressDialog.(ProgressDialog.java:76)
  04-12 08:40:39.504:
  ERROR/AndroidRuntime(2454):     at
  android.app.ProgressDialog.show(ProgressDialog.java:101)
  04-12 08:40:39.504:
  ERROR/AndroidRuntime(2454):     at
  android.app.ProgressDialog.show(ProgressDialog.java:90)
  04-12 08:40:39.504:
  ERROR/AndroidRuntime(2454):     at
  com.taxiorder.DBHelper$1.run(DBHelper.java:157)
  04-12 08:40:39.504:
  ERROR/AndroidRuntime(2454):     at
  java.lang.Thread.run(Thread.java:1096)

.

Tried a few more things with no result... So I just can't figure out what's wrong.

Once again - I just need to show PD while restoreDB() executing. I can't run restoreDB() in separate thread because I need it finished before app can proceed. As I can see PD should be run in separate thread only but i can't manage it.

Now I have 2 additional questions:

1) If a PD should be created in separate thread could it be created and showed if it's thread doesn't do anything at all. I mean something like this:

    new Thread(){
          public void run(){
              mProgressDialog = ProgressDialog.show(appContext,
                      appContext.getResources().getString(R.string.progress_wait),
                      appContext.getResources().getString(R.string.progress_db_installing),
                      true);

      }.start();

As I understand the thread dies immediately after executing run() cause there is nothing to do and so PD doesn't show.

2) PD by itself doesn't suspend any thread while displaying, does it?

Body:
Try to declare AsyncTask as an inner class for the activity, instantiate and execute it there. I think the problem is in context given to ProgressDialog when you are creating it, your logic for doing this is too complicated. Declaring AsyncTask in activity is more common practice.

Then, AsyncTask must do all you need with DB in doInBackground method

public class SplashActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        new RestoreDBTask().execute();
    }

}

private class RestoreDBTask extends AsyncTask <Void, Void, String>
{
    private ProgressDialog dialog;

    @Override
    protected void onPreExecute()
    {
        dialog = ProgressDialog.show(
            SplashActivity.this,
            getString(R.string.progress_wait),
            getString(R.string.progress_db_installing),
            true);
    }

    @Override
    protected String doInBackground(Void... params)
    {
        // do all the things with DB
        DBHelper dbHelper = new DBHelper(SplashActivity.this);
        dbHelper.close();
        return "";
    }

    @Override
    protected void onPostExecute(String result)
    {
        dialog.dismiss();
    }
}


问:
Docker won't start on Windows: Not Enough memory to start docker
I am trying to get started with Docker on Windows. My machine has 4GB of RAM and a 1.9GHz - 2.5GHz Intel i5 processor, running Windows 10 Pro x64. I know these aren't powerful specs, but I would have thought I should be able to run Docker?

However, having downloaded Docker, I get the error message:

Not Enough memory to start docker

I have seen various forum posts and github issues about this and followed all the advice I can see, such as modifying the settings in Docker, I tried these:

They also mentioned changing the settings of the Hyper-V VM however, this seems to be deleted and recreated with the Docker specified settings on every attempted launch. I tried 2048MB, 1792MB, 1536MB, 1280MB and 1024MB of RAM, all of which failed.

What else can I do? Surely I can run docker in some form on my machine? NB: I have closed all non-essential background apps. There doesn't seem to be many other suggestions for what seems to be a fairly common issue, where the given solutions don't work?

答:
I solved this issue by right clicking on the docker tray icon chose    settings and then tapped on the "Advanced" section.

Then I lowered the memory from the default 2048 to 1536 and works    like charm.
Another option is try to switch to Windows Containers then Restart    the Machine and switch back to Linux Containers.

Below is my docker settings with Advanced tab open. Note the Memory is 1536 and My laptop has 4GB Ram.

Also the virtual machine "MobyLinuxVM" is running as shown below;

I hope this helps someone one day even if was a late answer :)


问:
Function conversion of argument did not succeed when calling WCF service
I have a WCF service with this function :

```<code>namespace PortfolioSerivce
{
    [ServiceContract]
    public interface IService1
    {
         [OperationContract]
         bool CreateOrders(List<OrderDTO> ListOrder);
    }
}
</code>```

and here its code

```<code>    public bool CreateOrders(List<OrderDTO> ListOrder)
    {
        return true;
    }
</code>```

The class OrderDTO is defined as below :

```<code>[DataContract]
public class OrderDTO
{
    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public char OrderType { get; set; }

    [DataMember]
    public float OrderedQty { get; set; }

    [DataMember]
    public float PreUNitCost { get; set; }

    [DataMember]
    public float PostUnitCost { get; set; }

    [DataMember]
    public float MarketPrice { get; set; }

    [DataMember]
    public float ClientId { get; set; }

    [DataMember]
    public float SecurityId { get; set; }
}
</code>```

In WPF, I have a function in which I want to pass a list to the WCF function:

```<code>    internal bool RemoteCreateOrders(List<Position> securityMarketDTO)
    {
        List<OrderDTO> ListOrders = new List<OrderDTO>();
        Tools.MyRemoteService.CreateOrders((List<OrderDTO>)ListOrders);
        return true;
    }
</code>```

When I compile I got those errors :

The best overloaded method match for 'PortfolioView.PortfolioService.Service1Client.CreateOrders(PortfolioView.PortfolioService.OrderDTO[])' has some invalid arguments

Cannot convert from 'System.Collections.Generic.List' to 'PortfolioView.PortfolioService.OrderDTO[]'

What is the problem here, as I send a list of OrderDTO from my app and in WCF I declared as parameter a list of OrderDTO. What conversion should I use?

Thanks in advance.

答:
From  you exception , you Service1Client's method CreateOrders needs a variable of type OrderDTO[], while you pass List.

Please pass the variable of right type , use ListOrders.ToArray to convert list to array.

Or if you want to pass List, please let vs generate List for collection when you add service reference.

When adding service reference using vs, you could click advanced at the bottom, and then your could configure Collection type.

Body:
I have a WCF service with this function :

namespace PortfolioSerivce
{
    [ServiceContract]
    public interface IService1
    {
         [OperationContract]
         bool CreateOrders(List<OrderDTO> ListOrder);
    }
}

and here its code

    public bool CreateOrders(List<OrderDTO> ListOrder)
    {
        return true;
    }

The class OrderDTO is defined as below :

[DataContract]
public class OrderDTO
{
    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public char OrderType { get; set; }

    [DataMember]
    public float OrderedQty { get; set; }

    [DataMember]
    public float PreUNitCost { get; set; }

    [DataMember]
    public float PostUnitCost { get; set; }

    [DataMember]
    public float MarketPrice { get; set; }

    [DataMember]
    public float ClientId { get; set; }

    [DataMember]
    public float SecurityId { get; set; }
}

In WPF, I have a function in which I want to pass a list to the WCF function:

    internal bool RemoteCreateOrders(List<Position> securityMarketDTO)
    {
        List<OrderDTO> ListOrders = new List<OrderDTO>();
        Tools.MyRemoteService.CreateOrders((List<OrderDTO>)ListOrders);
        return true;
    }

When I compile I got those errors :

The best overloaded method match for 'PortfolioView.PortfolioService.Service1Client.CreateOrders(PortfolioView.PortfolioService.OrderDTO[])' has some invalid arguments

Cannot convert from 'System.Collections.Generic.List' to 'PortfolioView.PortfolioService.OrderDTO[]'

What is the problem here, as I send a list of OrderDTO from my app and in WCF I declared as parameter a list of OrderDTO. What conversion should I use?

Thanks in advance.


问:
Does getting a synchronized collection from collections class synchronize a class?
I am trying to understand what does synchronizedCollection, synchronizedList, synchronizedMap, synchronizedSet and other such methods do. From what I understand synchronization can be done on blocks and methods and not on classes so let's say if I have a hashmap.

```<code>HashMap<Integer,String> hashMap = new HashMap<Integer,String>();
HashMap<Integer,String> syncHashMap = Collections.synchronizedMap(hashMap);
</code>```

Questions

So did the above code just synchronized whole syncHashMap class or
every method inside it?

If we can simply use a threadsafe collection such as
ConcurrentHashMap or SynchronizedMap in multithreading scenario then what's the need of
Collections.synchronizedMap(hashMap) and other similar methods in
Collections class

Will deeply appreciate some direction on this, thanks in advance.

答:
There are several terms touching the subject you are asking about.

Synchronization

There are number of interfaces and classes that help synchronize your code between threads. A Semaphore, a CyclicBarrier or synchronous collections like BlockingQueue. See java.util.concurrent package for a list of those classes.

The synchronized block is also a way of synchronizing, though using it properly requires more experience.

Mutex

Different languages (and libraries) implement the standard mutex differently. The idea remains the same - in order to proceed with execution of particular code, a MUTually EXclusive token, a mutex has to be acquired. In java this acquisition happens before entering a synchronized block.

Thread-safety

To put it simply, a class is thread safe when all its methods can be accessed in any order from any number of threads concurrently. There are several ways of acheiving thread-safety. For example, Strings are thread safe. They are not synchronized, but they are immutable and that also causes thread safety. All Collections.synchronized*() methods return thread safe wrappers for collections, privided that all future* (*see happens-before relationship) access to them is executed through those wrappers (that's why it's a good rule for beginners to call the Collections.synchronized*() on new objects only.

The answer

Having the knowledge from previous paragraphs, to answer your question: no, it does not synchronize a class. It does not change the original Collection implementation at all.
It does create a read and write thread-safe synchronized mutable kind-of-proxy to that class, however.

Body:
I am trying to understand what does synchronizedCollection, synchronizedList, synchronizedMap, synchronizedSet and other such methods do. From what I understand synchronization can be done on blocks and methods and not on classes so let's say if I have a hashmap.

HashMap<Integer,String> hashMap = new HashMap<Integer,String>();
HashMap<Integer,String> syncHashMap = Collections.synchronizedMap(hashMap);

Questions

So did the above code just synchronized whole syncHashMap class or
every method inside it?

If we can simply use a threadsafe collection such as
ConcurrentHashMap or SynchronizedMap in multithreading scenario then what's the need of
Collections.synchronizedMap(hashMap) and other similar methods in
Collections class

Will deeply appreciate some direction on this, thanks in advance.


问:
Using file upload control how to upload empty folder in asp.net c#?
Using file upload controls in asp.net c# how to upload empty folder.</p>

答: You cannot upload folders anywhere. Your site needs to give the user the opportunity to create folders, eg with a TextField for the name of the folder and a button to submit the request. But you are not able to upload an empty folder. Not even a folder containing files. In this case only the files will be uploaded. Maybe you wanna use a ZIP file to upload an "archived folder".</p>


问:
how to calculate the exact age of a person from date of birth in android
```<code>  First example: birthdate :10-01-1991(ddmmyyyy)
                 CurrentDate :10-01-2017
</code>```

if above is the condition then I want to print 26 as  current age.
      Second example: birthdate :25-07-1991(ddmmyyyy)

                      CurrentDate :10-01-2017
 if above is the condition then I want to print 25 as current age.

please help me ....!!!!!!

Below is the code that i have tried.

```<code>private int calculateage(Integer day1, Integer month1, Integer year1)
{
Calendar birthCal = new GregorianCalendar(1991, 01, 10);

Calendar nowCal = new GregorianCalendar();

age = nowCal.get(Calendar.YEAR) - birthCal.get(Calendar.YEAR);
boolean isMonthGreater = birthCal.get(Calendar.MONTH) >= nowCal
        .get(Calendar.MONTH);

boolean isMonthSameButDayGreater = birthCal.get(Calendar.MONTH) >= nowCal.get(Calendar.MONTH)
        && birthCal.get(Calendar.DAY_OF_MONTH) >= nowCal
                .get(Calendar.DAY_OF_MONTH);

if (age < 18) {
    Age = age;
}
else if (isMonthGreater || isMonthSameButDayGreater) {
    Age = age - 1;
}
return Age;
</code>```

}

答:
This will be the suitable method for each condition of calculating Age from given Date --

```<code>public static String getAge(int year, int month, int day)
{

 Calendar dob = Calendar.getInstance();

 Calendar today = Calendar.getInstance();

dob.set(year, month, day);

int today_m = today.get(Calendar.MONTH);

int dob_m = dob.get(Calendar.MONTH);

int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);

if (dob_m > today_m)
{

age--;
}
else if (dob_m == today_m)
{

int day_today = today.get(Calendar.DAY_OF_MONTH);

int day_dob = dob.get(Calendar.DAY_OF_MONTH);
if (day_dob > day_today) {
age--;}

}
return age+"";
}
</code>```

In MainActivity

```<code>public SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");

Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf2.parse("2000-03-21"));

String age=Util.getAge(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE));
</code>```

I am setting the given date in a calendar and sending the year,date and month to getAge() method.
    you can change the date format as per you requirement.

Body:
  First example: birthdate :10-01-1991(ddmmyyyy)
                 CurrentDate :10-01-2017

if above is the condition then I want to print 26 as  current age.
      Second example: birthdate :25-07-1991(ddmmyyyy)

                      CurrentDate :10-01-2017
 if above is the condition then I want to print 25 as current age.

please help me ....!!!!!!

Below is the code that i have tried.

private int calculateage(Integer day1, Integer month1, Integer year1)
{
Calendar birthCal = new GregorianCalendar(1991, 01, 10);

Calendar nowCal = new GregorianCalendar();

age = nowCal.get(Calendar.YEAR) - birthCal.get(Calendar.YEAR);
boolean isMonthGreater = birthCal.get(Calendar.MONTH) >= nowCal
        .get(Calendar.MONTH);

boolean isMonthSameButDayGreater = birthCal.get(Calendar.MONTH) >= nowCal.get(Calendar.MONTH)
        && birthCal.get(Calendar.DAY_OF_MONTH) >= nowCal
                .get(Calendar.DAY_OF_MONTH);

if (age < 18) {
    Age = age;
}
else if (isMonthGreater || isMonthSameButDayGreater) {
    Age = age - 1;
}
return Age;

}

Body:
This will be the suitable method for each condition of calculating Age from given Date --

public static String getAge(int year, int month, int day)
{

 Calendar dob = Calendar.getInstance();

 Calendar today = Calendar.getInstance();

dob.set(year, month, day);

int today_m = today.get(Calendar.MONTH);

int dob_m = dob.get(Calendar.MONTH);

int age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);

if (dob_m > today_m)
{

age--;
}
else if (dob_m == today_m)
{

int day_today = today.get(Calendar.DAY_OF_MONTH);

int day_dob = dob.get(Calendar.DAY_OF_MONTH);
if (day_dob > day_today) {
age--;}

}
return age+"";
}

In MainActivity

public SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");

Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf2.parse("2000-03-21"));

String age=Util.getAge(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE));

I am setting the given date in a calendar and sending the year,date and month to getAge() method.
    you can change the date format as per you requirement.


问:
go modules installing go tools
I'm using go modules as dependency management, and I'm having problem to install something like this:

```<code>go get -u github.com/go-critic/go-critic/...
</code>```

the result from above was:

```<code>go: cannot find main module; see 'go help modules'
</code>```

答:
Just had the same issue on go1.11.2. Tried to set GO111MODULE=on, but this couldn't fix it.

My solution:

Upgrade to use go 1.12.5: https://golang.org/doc/install?download=go1.12.5.linux-amd64.tar.gz

This can resolve go: cannot find main module; see 'go help modules' issue.

Then I got another issue go: cannot use path@version syntax in GOPATH mode,

which can be resolved setting env GO111MODULE=on

Title: go modules installing go tools

Body:
I'm using go modules as dependency management, and I'm having problem to install something like this:

go get -u github.com/go-critic/go-critic/...

the result from above was:

go: cannot find main module; see 'go help modules'


问:
How to specify multiple files in $sourcePath
I'm trying to copy multiple files locally to network share.

Method I am using

```<code>$sourcePath = "C:\folder\file.csv"
</code>```

Works fine, but when I add addition file to the same sourcepath it fails, e.g

```<code>$sourcePath = "C:\folder\file.csv, C:\folder\file2.csv"
</code>```

I would like to be able to copy two separate files specified in sourcepath.

答:
Define $sourcePath = C:\folder\file.csv, C:\folder\file2.csv as array in the following way:

```<code>$sourcePath = "C:\folder\file.csv", "C:\folder\file2.csv"
</code>```

After that you can copy via:

```<code>$sourcePath | Foreach-Object { Copy-item $_ "C:\temp" -Verbose }
</code>```

Hope that helps.

Body:
I'm trying to copy multiple files locally to network share.

Method I am using

$sourcePath = "C:\folder\file.csv"

Works fine, but when I add addition file to the same sourcepath it fails, e.g

$sourcePath = "C:\folder\file.csv, C:\folder\file2.csv"

I would like to be able to copy two separate files specified in sourcepath.

Body:
Define $sourcePath = C:\folder\file.csv, C:\folder\file2.csv as array in the following way:

$sourcePath = "C:\folder\file.csv", "C:\folder\file2.csv"

After that you can copy via:

$sourcePath | Foreach-Object { Copy-item $_ "C:\temp" -Verbose }

Hope that helps.


问:
Wep API fails to return data from HttpClient call
I have not been able to figure out why the following issue is happening:

I have created a simple web api controller (.Net Framework 4.6.1)

```<code>public class TestController : ApiController
{
    // GET api/<controller>
    public async Task<string> Get()
    {
        var url = "http://api.plos.org/search?q=title:DNA";
        using (var httpClient = new HttpClient())
        {
            using (var response = await httpClient.GetAsync(url))
            {
                using (var content = response.Content)
                {
                    var result = await content.ReadAsStringAsync();
                    return result;

                }
            }
        }
    }
}
</code>```

When I run the code above I get the following error after about 20 seconds.

```<code>{
    "Message": "An error has occurred.",
    "ExceptionMessage": "An error occurred while sending the request.",
    "ExceptionType": "System.Net.Http.HttpRequestException",
    "StackTrace": "   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at restapitest2.Controllers.TestController.<Get>d__0.MoveNext() in C:\\restapitest2\\restapitest2\\Controllers\\TestController.cs:line 19\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__1`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()",
    "InnerException": {
        "Message": "An error has occurred.",
        "ExceptionMessage": "Unable to connect to the remote server",
        "ExceptionType": "System.Net.WebException",
        "StackTrace": "   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)\r\n   at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)",
        "InnerException": {
            "Message": "An error has occurred.",
            "ExceptionMessage": "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 216.74.38.80:80",
            "ExceptionType": "System.Net.Sockets.SocketException",
            "StackTrace": "   at System.Net.Sockets.Socket.InternalEndConnect(IAsyncResult asyncResult)\r\n   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)\r\n   at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)"
        }
    }
}
</code>```

When I create a dotnet core web api controller the same code works fine.

This is what the dot net core code looks like.

```<code>[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public async Task<ActionResult<string>> Get()
    {
        var url = "http://api.plos.org/search?q=title:DNA";
        using (var httpClient = new HttpClient())
        {
            using (var response = await httpClient.GetAsync(url))
            {
                using (var content = response.Content)
                {
                    var result = await content.ReadAsStringAsync();
                    return result;

                }
            }
        }
    }
}
</code>```

What is strange is that if I use an internal URL both api solutions return data.

Any help would be appreciated

答:
Are you sure you aren't behind a proxy?

Are you sure that your DNS server can look up api.plos.org?

Check your exception more deeply, checking its inner exceptions will help you understand is that a DNS problem or a proxy problem.

If you are behind a proxy don't forget to set proxy for HttpClient.

Update 1:

A connection attempt failed because the connected party did not
  properly respond after a period of time, or established connection
  failed because connected host has failed to respond 216.74.38.80:80

I faced this error every time that I got a proxy on my machine. Since you said "if you run fiddler everything works fine" I assume you need to remove proxy settings from windows Lan Settings.

In the run type inetcpl.cpl and press enter.

Go to the Connections tab.

At the bottom of the dialog, there is Lan Settings button. Click on it.

In the LAN settings dialog make sure you have unchecked all the checkboxes especially use proxy for your lan.

Off-topic recommendation:

HttpClient is intended to be instantiated once and re-used throughout
  the life of an application. Instantiating an HttpClient class for
  every request will exhaust the number of sockets available under heavy
  loads. This will result in SocketException errors. Below is an example
  using HttpClient correctly.

```<code>public class GoodController : ApiController
{
    // OK
    private static readonly HttpClient HttpClient;

    static GoodController()
    {
        HttpClient = new HttpClient();
    }
}
</code>```

Body:
I have not been able to figure out why the following issue is happening:

I have created a simple web api controller (.Net Framework 4.6.1)

public class TestController : ApiController
{
    // GET api/<controller>
    public async Task<string> Get()
    {
        var url = "http://api.plos.org/search?q=title:DNA";
        using (var httpClient = new HttpClient())
        {
            using (var response = await httpClient.GetAsync(url))
            {
                using (var content = response.Content)
                {
                    var result = await content.ReadAsStringAsync();
                    return result;

                }
            }
        }
    }
}

When I run the code above I get the following error after about 20 seconds.

{
    "Message": "An error has occurred.",
    "ExceptionMessage": "An error occurred while sending the request.",
    "ExceptionType": "System.Net.Http.HttpRequestException",
    "StackTrace": "   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at restapitest2.Controllers.TestController.<Get>d__0.MoveNext() in C:\\restapitest2\\restapitest2\\Controllers\\TestController.cs:line 19\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__1`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()",
    "InnerException": {
        "Message": "An error has occurred.",
        "ExceptionMessage": "Unable to connect to the remote server",
        "ExceptionType": "System.Net.WebException",
        "StackTrace": "   at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)\r\n   at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)",
        "InnerException": {
            "Message": "An error has occurred.",
            "ExceptionMessage": "A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 216.74.38.80:80",
            "ExceptionType": "System.Net.Sockets.SocketException",
            "StackTrace": "   at System.Net.Sockets.Socket.InternalEndConnect(IAsyncResult asyncResult)\r\n   at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)\r\n   at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)"
        }
    }
}

When I create a dotnet core web api controller the same code works fine.

This is what the dot net core code looks like.

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public async Task<ActionResult<string>> Get()
    {
        var url = "http://api.plos.org/search?q=title:DNA";
        using (var httpClient = new HttpClient())
        {
            using (var response = await httpClient.GetAsync(url))
            {
                using (var content = response.Content)
                {
                    var result = await content.ReadAsStringAsync();
                    return result;

                }
            }
        }
    }
}

What is strange is that if I use an internal URL both api solutions return data.

Any help would be appreciated

Body:
Are you sure you aren't behind a proxy?

Are you sure that your DNS server can look up api.plos.org?

Check your exception more deeply, checking its inner exceptions will help you understand is that a DNS problem or a proxy problem.

If you are behind a proxy don't forget to set proxy for HttpClient.

Update 1:

A connection attempt failed because the connected party did not
  properly respond after a period of time, or established connection
  failed because connected host has failed to respond 216.74.38.80:80

I faced this error every time that I got a proxy on my machine. Since you said "if you run fiddler everything works fine" I assume you need to remove proxy settings from windows Lan Settings.

In the run type inetcpl.cpl and press enter.

Go to the Connections tab.

At the bottom of the dialog, there is Lan Settings button. Click on it.

In the LAN settings dialog make sure you have unchecked all the checkboxes especially use proxy for your lan.

Off-topic recommendation:

HttpClient is intended to be instantiated once and re-used throughout
  the life of an application. Instantiating an HttpClient class for
  every request will exhaust the number of sockets available under heavy
  loads. This will result in SocketException errors. Below is an example
  using HttpClient correctly.

public class GoodController : ApiController
{
    // OK
    private static readonly HttpClient HttpClient;

    static GoodController()
    {
        HttpClient = new HttpClient();
    }
}


问:
nginx: Remove "Server" response header - not honour what said in doco
Nginx version: 1.15.8

According to nginx doc: http://nginx.org/en/docs/http/ngx_http_core_module.html#server_tokens:

"starting from version 1.9.13 the signature on error pages and the “Server” response header field value can be set explicitly using the string with variables. An empty string disables the emission of the “Server” field."

But when I put in this

```<code>server_tokens '';
</code>```

it complains:

```<code>nginx: [emerg] invalid value ""
</code>```

Also tried:

```<code>server_tokens "";
</code>```

```<code>server_tokens;
</code>```

None of them work. Note that I want to remove the "Server" header completely not just the version which can be done straightforwardly with "server_tokens off;"

Does anyone have it working this way ? Comments & suggestions are welcome.

Thanks,

答:
Additionally, as part of our commercial subscription, starting from version 1.9.13 the signature on error pages and the “Server” response header field value can be set explicitly using the string with variables. An empty string disables the emission of the “Server” field.

Source: http://nginx.org/en/docs/http/ngx_http_core_module.html#server_tokens

It requires a commercial subscription.

Otherwise, install ngx_headers_more module.

And add the following to your nginx conf, and restart nginx. This will remove the "server" header. -

```<code>more_clear_headers  "Server";
more_clear_headers  "server";
</code>```

Installation: https://github.com/openresty/headers-more-nginx-module#installation

Body:
Nginx version: 1.15.8

According to nginx doc: http://nginx.org/en/docs/http/ngx_http_core_module.html#server_tokens:

"starting from version 1.9.13 the signature on error pages and the “Server” response header field value can be set explicitly using the string with variables. An empty string disables the emission of the “Server” field."

But when I put in this

server_tokens '';

it complains:

nginx: [emerg] invalid value ""

Also tried:

server_tokens "";

server_tokens;

None of them work. Note that I want to remove the "Server" header completely not just the version which can be done straightforwardly with "server_tokens off;"

Does anyone have it working this way ? Comments & suggestions are welcome.

Thanks,

Body:
Additionally, as part of our commercial subscription, starting from version 1.9.13 the signature on error pages and the “Server” response header field value can be set explicitly using the string with variables. An empty string disables the emission of the “Server” field.

Source: http://nginx.org/en/docs/http/ngx_http_core_module.html#server_tokens

It requires a commercial subscription.

Otherwise, install ngx_headers_more module.

And add the following to your nginx conf, and restart nginx. This will remove the "server" header. -

more_clear_headers  "Server";
more_clear_headers  "server";

Installation: https://github.com/openresty/headers-more-nginx-module#installation


问:
Can you create conditional plugs in elixir?
I want to call a plug from the else part of an if-else statement.

I've tried calling plug SpiderWeb.AdminAuth but I get the ArgumentError: cannot set attribute @plugs inside function/macro..

I've also tried SpiderWeb.AdminAuth.call(conn) but I get error UndefinedFunctionError at GET /user/1: function SpiderWeb.AdminAuth.call/1 is undefined or private.

I could alternatively rewrite the entire plug in the else part but this goes against DRY principle.

This is the user controller file:

```<code>defmodule SpiderWeb.UserController do
  use SpiderWeb, :controller

  alias Spider.Accounts
  plug :user_authenticate when action in [:index, :show]
  plug SpiderWeb.AdminAuth when action in [:index]

  ## Action parameters changed to ensure only current user has access or admin ##
  def action(conn, _) do
    args = [conn, conn.params, conn.assigns.current_user]
    apply(__MODULE__, action_name(conn), args)
  end

  def index(conn, _params) do
    users = Accounts.list_users
    render(conn, "index.html", users: users)
  end

  def show(conn, %{"id" => id}, current_user) do
    if current_user.id == String.to_integer(id) do
      user = Accounts.get_user!(id)
      render(conn, "show.html", user: user)
    else
      SpiderWeb.AdminAuth.call(conn)
    end
  end
end

</code>```

This is the Admin authentication plug:

```<code>defmodule SpiderWeb.AdminAuth do
    import Plug.Conn
    import Phoenix.Controller

    alias Spider.Accounts
    alias SpiderWeb.Router.Helpers, as: Routes

    def init(opts), do: opts

    def call(conn, _opts) do
        case Accounts.check_admin(conn.assigns.current_user) do
            {:ok, _} -> conn
            {:error, _} -> conn
                |> put_flash(:error, "You don't have access to that page")
                |> redirect(to: Routes.page_path(conn, :index))
                |> halt()
        end
    end
end
</code>```

My goal is to ensure that only the current authenticated user can access the show page (with their own id) OR an admin.

EDIT: Other attempts
I've also tried making a separate dummy function and trying to plug the plug into that:

```<code>...
  plug SpiderWeb.AdminAuth when action in [:index, :do_nothing]
...
def show(conn, %{"id" => id}, current_user) do
    ...
    else
      do_nothing(conn)
    end
  end

  defp do_nothing(conn) do
  end
end
</code>```

But instead I get a RuntimeError at GET /user/1 : expected action/2 to return a Plug.Conn, all plugs must receive a connection (conn) and return a connection, got: nil

答:
You got it almost right, you only forgot to pass the second argument to call!

A module plug is a module with two functions: init/1 and call/2. In order to invoke any module plug dynamically, you need to invoke init/1 with the default options and pass call/2 with the connection as first argument and the result of calling init/1 as second. This is the whole plug specification. :)

In other words, you can do this:

```<code>def show(conn, %{"id" => id}, current_user) do
  if ... do
    ...
  else
    SpiderWeb.AdminAuth.call(conn, SpiderWeb.AdminAuth.init([]))
  end
end
</code>```

But perhaps, the best option is for you to create a new Plug that "ensure that only the current authenticated user can access the show page (with their own id) OR an admin". This way you can reuse it and keep the authorization logic outside of the action.

Body:
I want to call a plug from the else part of an if-else statement.

I've tried calling plug SpiderWeb.AdminAuth but I get the ArgumentError: cannot set attribute @plugs inside function/macro..

I've also tried SpiderWeb.AdminAuth.call(conn) but I get error UndefinedFunctionError at GET /user/1: function SpiderWeb.AdminAuth.call/1 is undefined or private.

I could alternatively rewrite the entire plug in the else part but this goes against DRY principle.

This is the user controller file:

defmodule SpiderWeb.UserController do
  use SpiderWeb, :controller

  alias Spider.Accounts
  plug :user_authenticate when action in [:index, :show]
  plug SpiderWeb.AdminAuth when action in [:index]

  ## Action parameters changed to ensure only current user has access or admin ##
  def action(conn, _) do
    args = [conn, conn.params, conn.assigns.current_user]
    apply(__MODULE__, action_name(conn), args)
  end

  def index(conn, _params) do
    users = Accounts.list_users
    render(conn, "index.html", users: users)
  end

  def show(conn, %{"id" => id}, current_user) do
    if current_user.id == String.to_integer(id) do
      user = Accounts.get_user!(id)
      render(conn, "show.html", user: user)
    else
      SpiderWeb.AdminAuth.call(conn)
    end
  end
end

This is the Admin authentication plug:

defmodule SpiderWeb.AdminAuth do
    import Plug.Conn
    import Phoenix.Controller

    alias Spider.Accounts
    alias SpiderWeb.Router.Helpers, as: Routes

    def init(opts), do: opts

    def call(conn, _opts) do
        case Accounts.check_admin(conn.assigns.current_user) do
            {:ok, _} -> conn
            {:error, _} -> conn
                |> put_flash(:error, "You don't have access to that page")
                |> redirect(to: Routes.page_path(conn, :index))
                |> halt()
        end
    end
end

My goal is to ensure that only the current authenticated user can access the show page (with their own id) OR an admin.

EDIT: Other attempts
I've also tried making a separate dummy function and trying to plug the plug into that:

...
  plug SpiderWeb.AdminAuth when action in [:index, :do_nothing]
...
def show(conn, %{"id" => id}, current_user) do
    ...
    else
      do_nothing(conn)
    end
  end

  defp do_nothing(conn) do
  end
end

But instead I get a RuntimeError at GET /user/1 : expected action/2 to return a Plug.Conn, all plugs must receive a connection (conn) and return a connection, got: nil

Body:
You got it almost right, you only forgot to pass the second argument to call!

A module plug is a module with two functions: init/1 and call/2. In order to invoke any module plug dynamically, you need to invoke init/1 with the default options and pass call/2 with the connection as first argument and the result of calling init/1 as second. This is the whole plug specification. :)

In other words, you can do this:

def show(conn, %{"id" => id}, current_user) do
  if ... do
    ...
  else
    SpiderWeb.AdminAuth.call(conn, SpiderWeb.AdminAuth.init([]))
  end
end

But perhaps, the best option is for you to create a new Plug that "ensure that only the current authenticated user can access the show page (with their own id) OR an admin". This way you can reuse it and keep the authorization logic outside of the action.


问:
Calling function that stores integers in an array in C
I have a homework assignment that I need assistance with.

I have written a function that should take user input using scanf and store it into an array. It will also count the number of times an integer is entered (except 0, which terminates the program)
I am specifically having an issue calling this function within main()
Any suggestions on how to fix it?

I've tried using defining the function at the bottom, and using different variables within the function: getVals

```<code>#include <stdio.h>

#define ARRAYSIZE 20 //defines the size of the array to 20

int nVals = 0;
int getVals(int myVals[], int maxVals);
int input[ARRAYSIZE+1] = {'0'};

int getVals(int myVals[], int maxVals)
{
  for (maxVals = 0; maxVals < ARRAYSIZE; maxVals++) { //When the row is    less than ten, it will run the loop and increment the row
    printf("Please Enter up to 20 integers "); //which will allow the name to be stored in the next row
    scanf("%d", &myVals[maxVals]);

    if ((myVals[maxVals] <= 0) || (maxVals == ARRAYSIZE -1))
       return nVals;
    if (myVals[maxVals] > 0)
       nVals++;

  }
}

int main() {
  printf("This program will receive up to 20 inputs from you, and sort them from least to greatest\n\n");
  printf("Enter 0 or a negative number to exit the program.\n");

  getVals(int ARRAYSIZE, int input[ARRAYSIZE]);

  printf("You have entered %d numbers\n", nVals);
  printf("%d", input[]);
  printf("\n");
  printf("Now sorting....\n");

  return 0;
}
</code>```

答:
Problem in main()

As Rishi noted in their answer, one line at fault is this line in main():

```<code>getVals(int ARRAYSIZE, int input[ARRAYSIZE]);
</code>```

This should prevent your code compiling, because after the preprocessor is finished, the line reads:

```<code>getVals(int 20, int input[20]);
</code>```

That is not valid C, at all — the first 20 is a meaningless syntactic error.

Assuming you have something that more or less compiles, such as either of these:

```<code>getVals(int SIZE, int input[ARRAYSIZE]);
getVals(int SIZE, int input[SIZE]);
</code>```

then you have a function declaration without a return type.  Under C90 rules, that couldn't appear in the middle of a function.  Under C99 or later rules, it can appear where it does, but it should have a return type –

```<code>int getVals(int SIZE, int input[ARRAYSIZE]);
int getVals(int SIZE, int input[SIZE]);
</code>```

The first of the declarations is valid in both C90 and C99, though the ARRAYSIZE is immaterial.  The second of the declarations is only valid in C99 or later, because it uses a VLA (variable length array).  Those did not exist in C90.

However, because this is a declaration and not a function call, the actual getVals() function is never called — which is your reported problem.

You actually want:

```<code>int num = getVals(ARRAYSIZE, input);
</code>```

Except:

You've defined getVals() using:

```<code>int getVals(int myVals[], int maxVals)
</code>```

so you really need to call:

```<code>getVals(input, ARRAYSIZE);
</code>```

Problems in getVals()

This function is a mess too.  You should probably use something like:

```<code>int getVals(int myVals[], int maxVals)
{
    int i;
    for (i = 0; i < maxVals; i++)
    {
        printf("Please Enter up to 20 integers ");
        if (scanf("%d", &myVals[i]) != 1)
            return i;
        if (myVals[i] <= 0)
            return i;
        nVals++;
    }
    return i;
}
</code>```

I've retained nVals as a global variable, but it really isn't necessary.  You should avoid global variables (variables defined outside of any function) whenever possible.

Body:
I have a homework assignment that I need assistance with.

I have written a function that should take user input using scanf and store it into an array. It will also count the number of times an integer is entered (except 0, which terminates the program)
I am specifically having an issue calling this function within main()
Any suggestions on how to fix it?

I've tried using defining the function at the bottom, and using different variables within the function: getVals

#include <stdio.h>

#define ARRAYSIZE 20 //defines the size of the array to 20

int nVals = 0;
int getVals(int myVals[], int maxVals);
int input[ARRAYSIZE+1] = {'0'};

int getVals(int myVals[], int maxVals)
{
  for (maxVals = 0; maxVals < ARRAYSIZE; maxVals++) { //When the row is    less than ten, it will run the loop and increment the row
    printf("Please Enter up to 20 integers "); //which will allow the name to be stored in the next row
    scanf("%d", &myVals[maxVals]);

    if ((myVals[maxVals] <= 0) || (maxVals == ARRAYSIZE -1))
       return nVals;
    if (myVals[maxVals] > 0)
       nVals++;

  }
}

int main() {
  printf("This program will receive up to 20 inputs from you, and sort them from least to greatest\n\n");
  printf("Enter 0 or a negative number to exit the program.\n");

  getVals(int ARRAYSIZE, int input[ARRAYSIZE]);

  printf("You have entered %d numbers\n", nVals);
  printf("%d", input[]);
  printf("\n");
  printf("Now sorting....\n");

  return 0;
}

Body:
Problem in main()

As Rishi noted in their answer, one line at fault is this line in main():

getVals(int ARRAYSIZE, int input[ARRAYSIZE]);

This should prevent your code compiling, because after the preprocessor is finished, the line reads:

getVals(int 20, int input[20]);

That is not valid C, at all — the first 20 is a meaningless syntactic error.

Assuming you have something that more or less compiles, such as either of these:

getVals(int SIZE, int input[ARRAYSIZE]);
getVals(int SIZE, int input[SIZE]);

then you have a function declaration without a return type.  Under C90 rules, that couldn't appear in the middle of a function.  Under C99 or later rules, it can appear where it does, but it should have a return type –

int getVals(int SIZE, int input[ARRAYSIZE]);
int getVals(int SIZE, int input[SIZE]);

The first of the declarations is valid in both C90 and C99, though the ARRAYSIZE is immaterial.  The second of the declarations is only valid in C99 or later, because it uses a VLA (variable length array).  Those did not exist in C90.

However, because this is a declaration and not a function call, the actual getVals() function is never called — which is your reported problem.

You actually want:

int num = getVals(ARRAYSIZE, input);

Except:

You've defined getVals() using:

int getVals(int myVals[], int maxVals)

so you really need to call:

getVals(input, ARRAYSIZE);

Problems in getVals()

This function is a mess too.  You should probably use something like:

int getVals(int myVals[], int maxVals)
{
    int i;
    for (i = 0; i < maxVals; i++)
    {
        printf("Please Enter up to 20 integers ");
        if (scanf("%d", &myVals[i]) != 1)
            return i;
        if (myVals[i] <= 0)
            return i;
        nVals++;
    }
    return i;
}

I've retained nVals as a global variable, but it really isn't necessary.  You should avoid global variables (variables defined outside of any function) whenever possible.


问:
"Maximum update depth exceeded" in React functional component
I have a problem with a react functional component. When the react-apollo query is "on completed" executes a code to handle a token, and when finish send to another page (using history.push).

When run the code I get a infinite loop with this message: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops

I've tried comment history.push and the infinite loop does not happen again.

I comment all the logic in list-session component to avoid a recursive call, but it does not work (I checked thoroughly the code to confirm is not a recursive call).

I thing the problem is related with the lifecycle or with the history.push behavior

Ptt: I'm learning react on this moment

```<code>  const { setUserInfo, setUserId } = useContext(userContext);
  const { token } = match.params;

  const onCompleted = data => {
    if (data.validateUser.status) {
      setUserId(token);
      setUserInfo(data.validateUser.infoUser);
      localStorage.setItem("token", token);
      // history.push("/list-session");
    } else {
      history.push("/rare-page");
    }
  };

  return (
    <div className="Auth" data-testid="AuthPage">
      <Query
        query={VALIDATE_USER}
        variables={{ userId: token }}
        onCompleted={onCompleted}
      >
        {({ error }) => {
          if (error) return <Error />;
          return (
            <>
              <h2 data-testid="AuthState">Authenticating...</h2>
              <div className="spinner-border text-info" role="status">
                <span className="sr-only">Loading...</span>
              </div>
            </>
          );
        }}
      </Query>
    </div>
  );
}
</code>```

EDIT 1:
Added relevant code in the problem. I checked the component and no one of this make a recursive call, and no make a infinite setState call. The setState problem is the consecuence to another problem.

```<code>        <AnimatedSwitch
          atEnter={bounceTransition.atEnter}
          atLeave={bounceTransition.atLeave}
          atActive={bounceTransition.atActive}
          mapStyles={mapStyles}
          className="route-wrapper"
        >
          <Route exact path="/" component={NoCredentials} />
          <Route exact path="/token/:token" component={Auth} />
          <Route path="/list-session" component={Home} />
        </AnimatedSwitch>
</code>```

and this is the code in Home component:

```<code>const Home = () => {
  const [activeTab, setActiveTab] = useState("activeSessions");

  return (
    <ValidateToken>
      <Container className="bg-light">
        <div className="Home">
          <CreateSessionComponent />
          <Nav tabs>
            <NavItem>
              <NavLink
                className={classnames({
                  active: activeTab === "activeSessions"
                })}
                onClick={() => setActiveTab("activeSessions")}
              >
                Active Sessions
              </NavLink>
            </NavItem>
          </Nav>
          <TabContent activeTab={activeTab}>
            <TabPane tabId="activeSessions">
              {activeTab === "activeSessions" && (
                <div>
                  <SessionsListComponent status="ACTIVE" />
                </div>
              )}
            </TabPane>
          </TabPane>
          </TabContent>
        </div>
      </Container>
    </ValidateToken>
  );
};

export default Home;
</code>```

答:
The "maximum update depth exceeded" error occurs when you are trying to update a variable multiple times until the stack size exceeds. This usually happens when u are trying to set a state inside render() or calling a method inside render which in turn sets the state. So check if there is a setState() call inside render method of your code.

Also this might happen because of setting the localStorage variable inside render. Try to move it out of render. But if you anyways need it you can use the componentDidMount() hook. That way all your variables will be available to you when your component is rendered.

Body:
I have a problem with a react functional component. When the react-apollo query is "on completed" executes a code to handle a token, and when finish send to another page (using history.push).

When run the code I get a infinite loop with this message: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops

I've tried comment history.push and the infinite loop does not happen again.

I comment all the logic in list-session component to avoid a recursive call, but it does not work (I checked thoroughly the code to confirm is not a recursive call).

I thing the problem is related with the lifecycle or with the history.push behavior

Ptt: I'm learning react on this moment

  const { setUserInfo, setUserId } = useContext(userContext);
  const { token } = match.params;

  const onCompleted = data => {
    if (data.validateUser.status) {
      setUserId(token);
      setUserInfo(data.validateUser.infoUser);
      localStorage.setItem("token", token);
      // history.push("/list-session");
    } else {
      history.push("/rare-page");
    }
  };

  return (

      <Query
        query={VALIDATE_USER}
        variables={{ userId: token }}
        onCompleted={onCompleted}
      >
        {({ error }) => {
          if (error) return <Error />;
          return (
            <>

Authenticating...

                Loading...

            </>
          );
        }}
      </Query>

  );
}

EDIT 1:
Added relevant code in the problem. I checked the component and no one of this make a recursive call, and no make a infinite setState call. The setState problem is the consecuence to another problem.

        <AnimatedSwitch
          atEnter={bounceTransition.atEnter}
          atLeave={bounceTransition.atLeave}
          atActive={bounceTransition.atActive}
          mapStyles={mapStyles}
          className="route-wrapper"
        >
          <Route exact path="/" component={NoCredentials} />
          <Route exact path="/token/:token" component={Auth} />
          <Route path="/list-session" component={Home} />
        </AnimatedSwitch>

and this is the code in Home component:

const Home = () => {
  const [activeTab, setActiveTab] = useState("activeSessions");

  return (
    <ValidateToken>
      <Container className="bg-light">

          <CreateSessionComponent />

            <NavItem>
              <NavLink
                className={classnames({
                  active: activeTab === "activeSessions"
                })}
                onClick={() => setActiveTab("activeSessions")}
              >
                Active Sessions
              </NavLink>
            </NavItem>

          <TabContent activeTab={activeTab}>
            <TabPane tabId="activeSessions">
              {activeTab === "activeSessions" && (

                  <SessionsListComponent status="ACTIVE" />

              )}
            </TabPane>
          </TabPane>
          </TabContent>

      </Container>
    </ValidateToken>
  );
};

export default Home;


问:
Bootstrap input-group-prepend/addon width adjustment
I'm having issues making prepend add-ons the same width. I'm using Font Awesome icons and the prepend is sized to each specific icon. I found another thread from about a year ago describing my exact problem, but there wasn't an answer.

Bootstrap4 make all input-group-addons same width

Here's a screenshot of my issue:

I tried using various CSS tweaks with no luck, including the one provided in that aforementioned thread.

Relevant HTML:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

      <input type="text" class="form-control" placeholder="Name">

      <input type="text" class="form-control" placeholder="Email">

      <input type="text" class="form-control" placeholder="Subject">

      <textarea class="form-control" id="exampleFormControlTextarea1" rows="3" placeholder="Message"></textarea>

```

答:
I tried your same code snippet, with just some css tweaks it works for me.
I just added the following css,
Please use this css, this will solve your prepend/addon width issue.

.input-group-text {
    width: 40px;
}
.input-group-text span {
    margin: 0 auto;
}```

Here is also the url to the snippet as well,
bootstrap-input-group-prepend-addon-width-issue

Body:
I tried your same code snippet, with just some css tweaks it works for me.
I just added the following css,
Please use this css, this will solve your prepend/addon width issue.

.input-group-text {
    width: 40px;
}
.input-group-text span {
    margin: 0 auto;
}

Here is also the url to the snippet as well,
bootstrap-input-group-prepend-addon-width-issue