问:
Is it able to create a sub object from a parent object in Python
I want to create an object with another class object as parent. For example:

```<code>class Parent:
    value = 0
    def __init__(self):
        self.value = int(input())
        self.call_subclass()

    def call_subclass(self):
        self.sub = Child()

class Child(Parent):
    def __init__(self):
        print(self.value)

obj = Parent()
</code>```

Let's say the input is 3, my expected output of print is also 3. But the actual output of above code is 0. The point is that, I want the sub class to inherit the self object of Parent. Not only inheriting the method and class variable from the Parent class, but also those instance variables of an actual called and existed Parent class object.

I know that there is a way to do this, is like below:

```<code>class Parent:
    value = 0
    def __init__(self):
        self.value = int(input())
        self.call_subclass()

    def call_subclass(self):
        self.sub = Child(self.value)

class Child(Parent):
    def __init__(self, value):
        self.value = value
        print(self.value)

obj = Parent()
</code>```

But this will be so clumsy if there is many instance variable. Also, the value is passing to Child by value, but not reference. So Child cannot get the most update instance variable value from Parent, but is what I want it to be able to implement.

Also, I know there is another way as below:

```<code>class Parent:
    value = 0
    def __init__(self):
        self.value = int(input())
        self.call_subclass()

    def call_subclass(self):
        self.sub = Child(self)

class Child(Parent):
    def __init__(self, parent):
        self.parent = parent
        print(self.parent.value)

obj = Parent()
</code>```

But this way seems not so concise. Also, some redundant resource will be produced, for example the Parent class' variable value = 0 will be inherited but with no use(the Child class should only interest in the instance variable and method of Parent class object obj). I would like to know if there is better method to achieve my purpose.

I understand there should be somebody already ask similar question, but I don't know what's the name of this technic. Therefore, I cannot find related information and decide to ask.

答:
if I am understanding correctly, I think you should just instance a Child class and not a Parent class.

Change the last line (from the original code) to this:

obj = Child()
```

Body:
I want to create an object with another class object as parent. For example:

class Parent:
    value = 0
    def __init__(self):
        self.value = int(input())
        self.call_subclass()

    def call_subclass(self):
        self.sub = Child()

class Child(Parent):
    def __init__(self):
        print(self.value)

obj = Parent()

Let's say the input is 3, my expected output of print is also 3. But the actual output of above code is 0. The point is that, I want the sub class to inherit the self object of Parent. Not only inheriting the method and class variable from the Parent class, but also those instance variables of an actual called and existed Parent class object.

I know that there is a way to do this, is like below:

class Parent:
    value = 0
    def __init__(self):
        self.value = int(input())
        self.call_subclass()

    def call_subclass(self):
        self.sub = Child(self.value)

class Child(Parent):
    def __init__(self, value):
        self.value = value
        print(self.value)

obj = Parent()

But this will be so clumsy if there is many instance variable. Also, the value is passing to Child by value, but not reference. So Child cannot get the most update instance variable value from Parent, but is what I want it to be able to implement.

Also, I know there is another way as below:

class Parent:
    value = 0
    def __init__(self):
        self.value = int(input())
        self.call_subclass()

    def call_subclass(self):
        self.sub = Child(self)

class Child(Parent):
    def __init__(self, parent):
        self.parent = parent
        print(self.parent.value)

obj = Parent()

But this way seems not so concise. Also, some redundant resource will be produced, for example the Parent class' variable value = 0 will be inherited but with no use(the Child class should only interest in the instance variable and method of Parent class object obj). I would like to know if there is better method to achieve my purpose.

I understand there should be somebody already ask similar question, but I don't know what's the name of this technic. Therefore, I cannot find related information and decide to ask.


来源: stackexchange

问:
S3 PutObject returns AccessDenied for PutObject command
Hoping someone can help.

Having an issue trying to write to an S3 bucket in a different account.

Myself and others have gone over the role (sts assumed) and the
permissions appear to be correct.

The bucket is encrypted with KMS

ListObjects returns a successful response.

CloudTrail shows the KMS
key being generated so we are getting to the bucket and kms is
allowing encryption.

CloudTrail shows the role being assumed.

I am not sure if the request is correct

```<code>PutObjectCommandInput
{
    "middlewareStack": {},
    "input": {
      "Bucket": "com-a-bucket-dev-feeds",
      "Body": "{ "value": "success"}",
      "Key": "datalake/raw/sites/20220127153225490.9CBC8C6F00DF025CE053AC17050DAF8F.json"
    }
  }
</code>```

The error response is:

AccessDenied: Access Denied

at deserializeAws_restXmlPutObjectCommandError (/var/task/app.js:31983:43)

at processTicksAndRejections (internal/process/task_queues.js:95:5)

at async /var/task/app.js:7648:24

at async /var/task/app.js:14753:22

at async StandardRetryStrategy.retry (/var/task/app.js:13621:42)

at async /var/task/app.js:13258:24 {

Code: 'AccessDenied',

Any help would be greatly appreciated

答:
After some digging with AWS Support, we discovered the issue.
The role policy in the second account was checking that the source of the action was from the VPC in which the Lambda was attached. This information is lost when the Lambda assumed a role in the second account, the AWS VPC for Lambdas is what was seen during the role policy check. ListObjects worked because a separate statement allowed it without a check for a specific VPC.

Changing the statement fixed the issue.

A few things to note about the request for cross-account access:

Bucket is the bucket name, not the ARN

The Key should not begin with a "/"

Leaving out the KMS/ACL information in the request will default to using what is defined on the bucket.

Thanks for the suggestions and hopes this helps someone.

ContentLicense: CC BY-SA 4.0

Body:
Hoping someone can help.

Having an issue trying to write to an S3 bucket in a different account.

Myself and others have gone over the role (sts assumed) and the
permissions appear to be correct.

The bucket is encrypted with KMS

ListObjects returns a successful response.

CloudTrail shows the KMS
key being generated so we are getting to the bucket and kms is
allowing encryption.

CloudTrail shows the role being assumed.

I am not sure if the request is correct

PutObjectCommandInput
{
    "middlewareStack": {},
    "input": {
      "Bucket": "com-a-bucket-dev-feeds",
      "Body": "{ "value": "success"}",
      "Key": "datalake/raw/sites/20220127153225490.9CBC8C6F00DF025CE053AC17050DAF8F.json"
    }
  }

The error response is:

AccessDenied: Access Denied

at deserializeAws_restXmlPutObjectCommandError (/var/task/app.js:31983:43)

at processTicksAndRejections (internal/process/task_queues.js:95:5)

at async /var/task/app.js:7648:24

at async /var/task/app.js:14753:22

at async StandardRetryStrategy.retry (/var/task/app.js:13621:42)

at async /var/task/app.js:13258:24 {

Code: 'AccessDenied',

Any help would be greatly appreciated


问:
Angular 2. Http calls to an "api" subdomain
The following example makes a regular call to http://example.com/api/products

makeApiCall(): Observable<ICall> {
    return this.http.post<ICall>('/api/products', {}, {})
}
```

For architectural reason, I need to make calls on 'api' subdomain (http://api. example.com/products)

How would I construct a call in such cases?

Please note, I would not hardcode 'example.com' anywhere.

答:
I would suggest you to add the base url i.E. https://api.example.com to the enviroment varables. If that's not an option you might can do it like this:

const baseUrl = document.location.protocol + '//api.' + document.location.hostname;
return this.http.post<ICall>(baseUrl+'/api/products', {}, {})
```

Body:
The following example makes a regular call to http://example.com/api/products

makeApiCall(): Observable<ICall> {
    return this.http.post<ICall>('/api/products', {}, {})
}

For architectural reason, I need to make calls on 'api' subdomain (http://api. example.com/products)

How would I construct a call in such cases?

Please note, I would not hardcode 'example.com' anywhere.


问:
Razor component instances created in loop - parameters problem
I would like generate instances of component like these:

```<code>            for (int i = 0; i < 10; i++)
            {
                <MyComponent Index="@i">
                    @i
                </MyComponent>
            }
</code>```

Problem is that every component instance has in final view the same value of param Index, and this value is 9. It si probably because this is right variables value when render time. Is it possible to pass right value of "i" variable to components? Thanks very much.

答:
Answer is very simple :-D</p>
```<code>        for (int i = 0; i < 10; i++)
        {
            int @iHlp = @i;
            <MyComponent Index="@iHlp">
                @iHlp
            </MyComponent>
        }
</code>```

Body:
I would like generate instances of component like these:

            for (int i = 0; i < 10; i++)
            {
                <MyComponent Index="@i">
                    @i
                </MyComponent>
            }

Problem is that every component instance has in final view the same value of param Index, and this value is 9. It si probably because this is right variables value when render time. Is it possible to pass right value of "i" variable to components? Thanks very much.

Body:
Answer is very simple :-D

        for (int i = 0; i < 10; i++)
        {
            int @iHlp = @i;
            <MyComponent Index="@iHlp">
                @iHlp
            </MyComponent>
        }


问:
how do i access each item of an array stored in local storage individually?
The code below fetches images and their names from a food api. I am able to store to those images in the local storage once a user hits the like button .i however want to get back the stored image and name data and display them in a favorite tab. But I can't seem to be able to achieve that..Any help?</p>
```<code>        let myFavMeals=[]
   function getRandomMeal(){
 fetch('https://api.spoonacular.com/recipes/random?
  number=10&apiKey=b354ffb530c5444da1eec4b02a3146be').then((data)=>{
  console.log(data)
  return data.json()
   }).then((completedata)=>{
 console.log(completedata.recipes)
  let data1=""
  completedata.recipes.forEach((recipe) => {
    const {
      id,
      title,
      readyInMinutes,
      extendedIngredients,
      servings,
      image,
      dishTypes,
      instructions,
    } = recipe;
      data1+=`
      <div class="meal-header">
          <img src=${recipe.image} alt=${recipe.title} >
      </div>
      <div class="meal-body">
          <h6>${recipe.title}</h6>
          <p class="show">see recipes</p>
          <button class="fav-btn">
              <i class="fa fa-heart"></i>
          </button>
      </div>
      <div class="holder">
      <div class="meal-desc">
      <p>ready in : ${recipe.readyInMinutes} minutes</p>
      <center><h6>instructions</h6></center>
      <p>${recipe.instructions}  </p>
      </div>
      </div>`
    })
    const meal=document.querySelector(".meal")
    meal.innerHTML=data1
   const holder=document.querySelector(".holder")
const show=document.querySelectorAll(".show")
show.forEach(shows=>{
    showcounter=0
    shows.addEventListener("click",()=>{
      holder.style.display="block"
      showcounter++
      if(showcounter== 2) {
      holder.style.display="none"
      }
    })
  })
const favBtns=meal.querySelectorAll(".fav-btn i")
const images = document.querySelectorAll('.meal-header > img')
favBtns.forEach((favBtn,i)=>{
  favBtn.addEventListener("click", ()=>{
    favBtn.classList.add("active")
    console.log(images[i].src, images[i].alt)
    myFavMeals.push(images[i].src, images[i].alt)
    localStorage.setItem("myFavMeals", JSON.stringify(myFavMeals))
    showMeal()
})
})

 }).catch((err)=>{
  console.log(err)
    })
}
getRandomMeal()
    function showMeal(){
      let favmeal= JSON.parse(localStorage.getItem("myFavMeals"))
      favmeal.forEach(favmeals=>{
        let meallist=""
        meallist+=`<ul>
             <li><img src=${favmeal} alt=${favmeal[i].alt}><span>${favmeal[i].alt}</span></li>
         </ul>`

         document.querySelector(".fav-meals").innerHTML+=meallist
      })

      }
</code>```

答:
You can save the favorites in the array as objects using object literal:

```<code>myFavMeals.push({src: images[i].src, alt: images[i].alt})
</code>```

And then access them in the loop using the keys src and alt:

```<code>function showMeal() {
  let favmeal = JSON.parse(localStorage.getItem("myFavMeals"));
  favmeal.forEach(favmeal => {
    let meallist = "";
    meallist += `<ul>
             <li><img src=${favmeal.src} alt=${favmeal.alt}><span>${favmeal.alt}</span></li>
         </ul>`;

    document.querySelector(".fav-meals").innerHTML += meallist;
  });
}
</code>```

Body:
The code below fetches images and their names from a food api. I am able to store to those images in the local storage once a user hits the like button .i however want to get back the stored image and name data and display them in a favorite tab. But I can't seem to be able to achieve that..Any help?

        let myFavMeals=[]
   function getRandomMeal(){
 fetch('https://api.spoonacular.com/recipes/random?
  number=10&apiKey=b354ffb530c5444da1eec4b02a3146be').then((data)=>{
  console.log(data)
  return data.json()
   }).then((completedata)=>{
 console.log(completedata.recipes)
  let data1=""
  completedata.recipes.forEach((recipe) => {
    const {
      id,
      title,
      readyInMinutes,
      extendedIngredients,
      servings,
      image,
      dishTypes,
      instructions,
    } = recipe;
      data1+=`

${recipe.title}

see recipes

          <button class="fav-btn">

          </button>

ready in : ${recipe.readyInMinutes} minutes

instructions

${recipe.instructions}

`
    })
    const meal=document.querySelector(".meal")
    meal.innerHTML=data1
   const holder=document.querySelector(".holder")
const show=document.querySelectorAll(".show")
show.forEach(shows=>{
    showcounter=0
    shows.addEventListener("click",()=>{
      holder.style.display="block"
      showcounter++
      if(showcounter== 2) {
      holder.style.display="none"
      }
    })
  })
const favBtns=meal.querySelectorAll(".fav-btn i")
const images = document.querySelectorAll('.meal-header > img')
favBtns.forEach((favBtn,i)=>{
  favBtn.addEventListener("click", ()=>{
    favBtn.classList.add("active")
    console.log(images[i].src, images[i].alt)
    myFavMeals.push(images[i].src, images[i].alt)
    localStorage.setItem("myFavMeals", JSON.stringify(myFavMeals))
    showMeal()
})
})

 }).catch((err)=>{
  console.log(err)
    })
}
getRandomMeal()
    function showMeal(){
      let favmeal= JSON.parse(localStorage.getItem("myFavMeals"))
      favmeal.forEach(favmeals=>{
        let meallist=""
        meallist+=`

${favmeal[i].alt}

`

         document.querySelector(".fav-meals").innerHTML+=meallist
      })

      }

Body:
You can save the favorites in the array as objects using object literal:

myFavMeals.push({src: images[i].src, alt: images[i].alt})

And then access them in the loop using the keys src and alt:

function showMeal() {
  let favmeal = JSON.parse(localStorage.getItem("myFavMeals"));
  favmeal.forEach(favmeal => {
    let meallist = "";
    meallist += `<ul>
             <li><img src=${favmeal.src} alt=${favmeal.alt}><span>${favmeal.alt}</span></li>
         </ul>`;

    document.querySelector(".fav-meals").innerHTML += meallist;
  });
}


问:
What would be the radio equivalent of this ngModel text input form, using spring boot mvc and angular?
I was taking a tutorial on making an employee CRUD model that uses spring boot and mysql server for the backend and angular for the front end. On the Create part it had this form-group (the gender part I was adding new fields).

```<code>    <div class="form-group">
            <label>
                Gender </label>
            <input type="text" class="form-control" id="gender" required [(ngModel)]="employee.gender" name="gender">
        </div>
</code>```

And that would work when submitting it (ie. creating the employee). But I can't figure out how to turn it into a radio button and submit it (it just gets stuck on the create page). This is what I tried to make when following a radio button example.

```<code><div class="form-group">

            <label for [(ngModel)]="employee.gender">Gender:</label>
            <div>
                <input id="male" type="radio" value="male" name="gender" formControlName="gender">
                <label for="male">Male</label>
            </div>

            <div>
                <input id="female" type="radio" value="female" name="gender" formControlName="gender">
                <label for="female">Female</label>
            </div>
        </div>
</code>```

My understanding could use more work, but I'm trying to learn. Any help is appreciated. Thanks

答:
You want to set obj employee prop gender with radio buttons.

You could group radio buttons and use (change) event to set the genders. I created this example a while back, it should fit your needs if you refactor this example and make onChange(event: any) to set the event.value to equal your employee.gender.

<mat-radio-group aria-label="Select an option" (change)="onChange($event)">
  <mat-radio-button value="1">Option 1 Male</mat-radio-button>
  <mat-radio-button value="2">Option 2 Female</mat-radio-button>

  Selected value: {{selectedValue | json}}, send to backend sex as: {{selectedSexObj | json}}
</mat-radio-group>
```
<pre class="lang-js prettyprint-override"><code>@Component({
  selector: 'radio-overview-example',
  templateUrl: 'radio-overview-example.html',
  styleUrls: ['radio-overview-example.css'],
})
export class RadioOverviewExample {
  selectedSexObj = { male: false, female: false };
  selectedValue: any;
  onChange(event: any) {
    this.selectedValue = event.value;
    if (event.value == 1) {
      this.selectedSexObj = { male: true, female: false };
    } else {
      this.selectedSexObj = { male: false, female: true };
    }
  }
}
</code>```

Here is a working example: https://stackblitz.com/edit/angular-qggcqg-qydurn?file=src%2Fapp%2Fradio-overview-example.ts

Body:
I was taking a tutorial on making an employee CRUD model that uses spring boot and mysql server for the backend and angular for the front end. On the Create part it had this form-group (the gender part I was adding new fields).

                Gender
            <input type="text" class="form-control" id="gender" required [(ngModel)]="employee.gender" name="gender">

And that would work when submitting it (ie. creating the employee). But I can't figure out how to turn it into a radio button and submit it (it just gets stuck on the create page). This is what I tried to make when following a radio button example.

            Gender:

                <input id="male" type="radio" value="male" name="gender" formControlName="gender">
                Male

                <input id="female" type="radio" value="female" name="gender" formControlName="gender">
                Female

My understanding could use more work, but I'm trying to learn. Any help is appreciated. Thanks

Body:
You want to set obj employee prop gender with radio buttons.

You could group radio buttons and use (change) event to set the genders. I created this example a while back, it should fit your needs if you refactor this example and make onChange(event: any) to set the event.value to equal your employee.gender.

<mat-radio-group aria-label="Select an option" (change)="onChange($event)">
  <mat-radio-button value="1">Option 1 Male</mat-radio-button>
  <mat-radio-button value="2">Option 2 Female</mat-radio-button>
  <br>
  <br>
  Selected value: {{selectedValue | json}}, send to backend sex as: {{selectedSexObj | json}}
</mat-radio-group>

@Component({
  selector: 'radio-overview-example',
  templateUrl: 'radio-overview-example.html',
  styleUrls: ['radio-overview-example.css'],
})
export class RadioOverviewExample {
  selectedSexObj = { male: false, female: false };
  selectedValue: any;
  onChange(event: any) {
    this.selectedValue = event.value;
    if (event.value == 1) {
      this.selectedSexObj = { male: true, female: false };
    } else {
      this.selectedSexObj = { male: false, female: true };
    }
  }
}

Here is a working example: https://stackblitz.com/edit/angular-qggcqg-qydurn?file=src%2Fapp%2Fradio-overview-example.ts


问:
Python Dataframe - Use column names as index, and sum of columns as values
I have a dataframe where the column names are dates, and values are number of cases. However, there are 300+ daily columns. How do I create a series where the index is the column names (dates), and values are the sum of number of days for each column?

Input:

```<code>      Country     1/1/2020   1/2/2020  ...  12/31/2020
  0   Afganistan  50         100       ...  500
  1   Albania     20         50        ...  50
  ...
  99  Zimbabwe   6          10         ...  5
</code>```

Desired output (pd.Series):

```<code>1/1/2020    76
1/2/2020    160
...
12/31/2020  555
</code>```

答:
Use DataFrame.sum with numeric_only=True parameter:

```<code>s = df.sum(numeric_only=True)
print (s)
1/1/2020       76
1/2/2020      160
12/31/2020    555
dtype: int64
</code>```

Body:
I have a dataframe where the column names are dates, and values are number of cases. However, there are 300+ daily columns. How do I create a series where the index is the column names (dates), and values are the sum of number of days for each column?

Input:

      Country     1/1/2020   1/2/2020  ...  12/31/2020
  0   Afganistan  50         100       ...  500
  1   Albania     20         50        ...  50
  ...
  99  Zimbabwe   6          10         ...  5

Desired output (pd.Series):

1/1/2020    76
1/2/2020    160
...
12/31/2020  555

Body:
Use DataFrame.sum with numeric_only=True parameter:

s = df.sum(numeric_only=True)
print (s)
1/1/2020       76
1/2/2020      160
12/31/2020    555
dtype: int64


问:
I am trying to train a model but got an error says (ValueError: Shapes (16, 16) and (16, 2) are incompatible)
I am working on voice emotion recognition project and when trying to fit the model I am getting the following error : got an error says:

```<code>(ValueError: Shapes (16, 16) and (16, 2) are incompatible)
</code>```

first I will show previous code before start fitting the model : ******

```<code>from keras.callbacks import ReduceLROnPlateau
    lr_reduce = ReduceLROnPlateau(monitor='val_loss', factor=0.9, patience=20, min_lr=0.000001)

mcp_save = ModelCheckpoint('model/aug_noiseNshift_2class2_np.h5', save_best_only=True, monitor='val_loss', mode='min')
mymodel = model.fit(x_traincnn, y_train, batch_size=16, epochs=700, validation_data = (x_testcnn, y_test), callbacks=[mcp_save, lr_reduce])
</code>```

and I am gotting the following error :

```<code>ValueError: in user code:

    /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:830 train_function  *
        return step_function(self, iterator)
    /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:813 run_step  *
        outputs = model.train_step(data)
    /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:771 train_step  *
        loss = self.compiled_loss(
    /usr/local/lib/python3.7/dist-packages/keras/engine/compile_utils.py:201 __call__  *
        loss_value = loss_obj(y_t, y_p, sample_weight=sw)
    /usr/local/lib/python3.7/dist-packages/keras/losses.py:142 __call__  *
        losses = call_fn(y_true, y_pred)
    /usr/local/lib/python3.7/dist-packages/keras/losses.py:246 call  *
        return ag_fn(y_true, y_pred, **self._fn_kwargs)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/util/dispatch.py:206 wrapper  **
        return target(*args, **kwargs)
    /usr/local/lib/python3.7/dist-packages/keras/losses.py:1631 categorical_crossentropy
        y_true, y_pred, from_logits=from_logits)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/util/dispatch.py:206 wrapper
        return target(*args, **kwargs)
    /usr/local/lib/python3.7/dist-packages/keras/backend.py:4827 categorical_crossentropy
        target.shape.assert_is_compatible_with(output.shape)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/tensor_shape.py:1161 assert_is_compatible_with
        raise ValueError("Shapes %s and %s are incompatible" % (self, other))

    ValueError: Shapes (16, 16) and (16, 2) are incompatible
</code>```

can you help please ?

答:
The issue was, I made a model (16,2) shape while it has to be (16,16). My output has 16 different classes, not 2, I changed model's last layer or the output layer to be 16 output.
Simple mistake I made because I am a beginner.</p>

Body:
I am working on voice emotion recognition project and when trying to fit the model I am getting the following error : got an error says:

(ValueError: Shapes (16, 16) and (16, 2) are incompatible)

first I will show previous code before start fitting the model : ******

from keras.callbacks import ReduceLROnPlateau
    lr_reduce = ReduceLROnPlateau(monitor='val_loss', factor=0.9, patience=20, min_lr=0.000001)

mcp_save = ModelCheckpoint('model/aug_noiseNshift_2class2_np.h5', save_best_only=True, monitor='val_loss', mode='min')
mymodel = model.fit(x_traincnn, y_train, batch_size=16, epochs=700, validation_data = (x_testcnn, y_test), callbacks=[mcp_save, lr_reduce])

and I am gotting the following error :

ValueError: in user code:

    /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:830 train_function  *
        return step_function(self, iterator)
    /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:813 run_step  *
        outputs = model.train_step(data)
    /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:771 train_step  *
        loss = self.compiled_loss(
    /usr/local/lib/python3.7/dist-packages/keras/engine/compile_utils.py:201 __call__  *
        loss_value = loss_obj(y_t, y_p, sample_weight=sw)
    /usr/local/lib/python3.7/dist-packages/keras/losses.py:142 __call__  *
        losses = call_fn(y_true, y_pred)
    /usr/local/lib/python3.7/dist-packages/keras/losses.py:246 call  *
        return ag_fn(y_true, y_pred, **self._fn_kwargs)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/util/dispatch.py:206 wrapper  **
        return target(*args, **kwargs)
    /usr/local/lib/python3.7/dist-packages/keras/losses.py:1631 categorical_crossentropy
        y_true, y_pred, from_logits=from_logits)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/util/dispatch.py:206 wrapper
        return target(*args, **kwargs)
    /usr/local/lib/python3.7/dist-packages/keras/backend.py:4827 categorical_crossentropy
        target.shape.assert_is_compatible_with(output.shape)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/tensor_shape.py:1161 assert_is_compatible_with
        raise ValueError("Shapes %s and %s are incompatible" % (self, other))

    ValueError: Shapes (16, 16) and (16, 2) are incompatible

can you help please ?


问:
Flutter gridview fill remaining height on screen
For the life of me I am not able to get the gridview.count to use the available height.
I have tried with the MediaQuery.of(context).size.height and width and tried with SafeArea but no luck.

Everything is contained in a Column.
The black bar is a container with a set height of 150 pixels. The grayblue bar is also a container with a set height of 50 pixels.

code:

```<code>  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Column(
          children: [
            DefaultTextStyle(
              style: const TextStyle(color: Colors.white, fontSize: 40.0),
              child: Container(
                width: double.infinity,
                height: 120.0,
                child: FittedBox(
                  fit: BoxFit.contain,
                  child: Center(
                    child: Text(results),
                  ),
                ),
                color: Colors.black,
              ),
            ),
            DefaultTextStyle(
              style: const TextStyle(
                color: Colors.white54,
                fontSize: 5.0,
              ),
              child: Container(
                width: double.infinity,
                height: 50.0,
                child: FittedBox(
                  fit: BoxFit.contain,
                  child: Center(
                    child: Text(history),
                  ),
                ),
                color: Colors.blueGrey,
              ),
            ),
            Expanded(
              child: GridView.count(
                padding: const EdgeInsets.all(2.0),
                crossAxisCount: 4,
                mainAxisSpacing: 2.0,
                crossAxisSpacing: 2.0,
                children: List.generate(
                  chars.length,
                  (index) {
                    return Material(
                      color: Colors.blueAccent,
                      child: InkWell(
                        // splashColor: Colors.amber,
                        onTap: () {
                          setState(() {

                          });
                        },
                        child: Center(
                          child: Text(chars[index]),
                        ),
                      ),
                    );
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
</code>```

答: Try using the Expanded widget provided by flutter. So, wrap your gridview with Expanded. Expanded will take all the available space of the screen.</p>

Body:
For the life of me I am not able to get the gridview.count to use the available height.
I have tried with the MediaQuery.of(context).size.height and width and tried with SafeArea but no luck.

Everything is contained in a Column.
The black bar is a container with a set height of 150 pixels. The grayblue bar is also a container with a set height of 50 pixels.

code:

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: Column(
          children: [
            DefaultTextStyle(
              style: const TextStyle(color: Colors.white, fontSize: 40.0),
              child: Container(
                width: double.infinity,
                height: 120.0,
                child: FittedBox(
                  fit: BoxFit.contain,
                  child: Center(
                    child: Text(results),
                  ),
                ),
                color: Colors.black,
              ),
            ),
            DefaultTextStyle(
              style: const TextStyle(
                color: Colors.white54,
                fontSize: 5.0,
              ),
              child: Container(
                width: double.infinity,
                height: 50.0,
                child: FittedBox(
                  fit: BoxFit.contain,
                  child: Center(
                    child: Text(history),
                  ),
                ),
                color: Colors.blueGrey,
              ),
            ),
            Expanded(
              child: GridView.count(
                padding: const EdgeInsets.all(2.0),
                crossAxisCount: 4,
                mainAxisSpacing: 2.0,
                crossAxisSpacing: 2.0,
                children: List.generate(
                  chars.length,
                  (index) {
                    return Material(
                      color: Colors.blueAccent,
                      child: InkWell(
                        // splashColor: Colors.amber,
                        onTap: () {
                          setState(() {

                          });
                        },
                        child: Center(
                          child: Text(chars[index]),
                        ),
                      ),
                    );
                  },
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }


问:
Dynamic Integration Runtime in Azure Data Factory (ADF)
I have multiple IR for each client. I want to use one pipeline to copy data from client SAP system to Blob.

I have created all the configuration variables like in below code but i am not able to create parameter for Integration Runtime variable.

Is there any JSON syntax where we can make it dynamic.

```<code>{
    "name": "LS_SAP_TBL",
    "type": "Microsoft.DataFactory/factories/linkedservices",
    "properties": {
        "type": "SapTable",
        "annotations": [],
        "typeProperties": {
            "clientId": "@{linkedService().ClientId}",
            "language": "",
            "sncMode": false,
            "userName": "@{linkedService().userName}",
            "password": {
                "type": "AzureKeyVaultSecret",
                "store": {
                    "referenceName": "KAJDSKJDHLSJDFHALKFD",
                    "type": "LinkedServiceReference"
                },
                "secretName": "@{linkedService().SecretName}"
            },
            "server": "@{linkedService().server}",
            "systemNumber": "@{linkedService().systemNumber}"
        },
        "connectVia": {
            "referenceName": "@IntegrationRuntime_Param - Need to pass this dynamically",
            "type": "IntegrationRuntimeReference"
        },
        "parameters": {
            "SecretName": {
                "type": "String"
            },
            "ClientId": {
                "type": "String"
            },
            "userName": {
                "type": "String"
            },
            "server": {
                "type": "String"
            },
            "systemNumber": {
                "type": "String"
            },
            "IntegrationRuntime_Param": {
                "type": "String"
            }
        }
    }
}```
```

答:
Unfortunately, as of now there in no option to parameterize the Integration Runtime.

You can parameterize the different parameters in a single IR to use it for multiple resources. But different IRs can't be parameterize.

Please refer this similar request on Microsoft Q&A for better understanding.

Need help on parameterization of Integration Runtime and Azure Key vault Secrets on link service in Azure Data Factory pipeline

Body:
I have multiple IR for each client. I want to use one pipeline to copy data from client SAP system to Blob.

I have created all the configuration variables like in below code but i am not able to create parameter for Integration Runtime variable.

Is there any JSON syntax where we can make it dynamic.

{
    "name": "LS_SAP_TBL",
    "type": "Microsoft.DataFactory/factories/linkedservices",
    "properties": {
        "type": "SapTable",
        "annotations": [],
        "typeProperties": {
            "clientId": "@{linkedService().ClientId}",
            "language": "",
            "sncMode": false,
            "userName": "@{linkedService().userName}",
            "password": {
                "type": "AzureKeyVaultSecret",
                "store": {
                    "referenceName": "KAJDSKJDHLSJDFHALKFD",
                    "type": "LinkedServiceReference"
                },
                "secretName": "@{linkedService().SecretName}"
            },
            "server": "@{linkedService().server}",
            "systemNumber": "@{linkedService().systemNumber}"
        },
        "connectVia": {
            "referenceName": "@IntegrationRuntime_Param - Need to pass this dynamically",
            "type": "IntegrationRuntimeReference"
        },
        "parameters": {
            "SecretName": {
                "type": "String"
            },
            "ClientId": {
                "type": "String"
            },
            "userName": {
                "type": "String"
            },
            "server": {
                "type": "String"
            },
            "systemNumber": {
                "type": "String"
            },
            "IntegrationRuntime_Param": {
                "type": "String"
            }
        }
    }
}```


问:
ld: duplicate symbol _x in /users/.... ERROR
I have 2 different classes but same primitive type declaration as you see below

```<code>int x = 0;
- (void)viewDidLoad{
[super viewDidLoad];
}
</code>```

if I change one of them name "x" to "y" there is no error? WHY? seperate classes same variable whats the problem???

答:
That's because the variable x is shared among classes. I think (but never tried) if you declare extern int x in another file, you could share the x variable.

Try static int x = 0. In general, always declare an internal class variable as static unless you want to share it with another file.

ContentLicense: CC BY-SA 3.0

Body:
I have 2 different classes but same primitive type declaration as you see below

int x = 0;
- (void)viewDidLoad{
[super viewDidLoad];
}

if I change one of them name "x" to "y" there is no error? WHY? seperate classes same variable whats the problem???


问:
why Typo3 website v10 show empty sitemap xml in frontend
I'm using a Typo3 website version 10 and the sitemap is not working properly,
i can see the configuration in the typoscript object browser but in the front-end www.mydomain.ch/?type=1533906435 the xml file is blanc.
Frontend screenshot:

Typoscript object browser screenshot:

seo extension is installed.
the website is multilangage.

what can be missing so that i see the sitemap ?

答:
If this is all you have, then you are missing some key configuration. You need to specify what should be shown. So, on your TypoScript, based on the documentation, you should define what pages/extension etc must be shown. For example:

```<code>plugin.tx_seo {
  config {
    xmlSitemap {
      sitemaps {
        pages {
          config {
            excludedDoktypes = 137, 138
            additionalWhere = AND (no_index = 0 OR no_follow = 0)
            #rootPage = <optionally specify a different root page. (default: rootPageId from site configuration)>
          }
        }
      }
    }
  }
}
</code>```

Here is an example for the extension news as well, in case you are using it.

```<code>plugin.tx_seo.config {
    xmlSitemap {
        sitemaps {
            news {
                provider = TYPO3\CMS\Seo\XmlSitemap\RecordsXmlSitemapDataProvider
                config {
                    table = tx_news_domain_model_news
                    additionalWhere =
                    sortField = sorting
                    lastModifiedField = tstamp
                    changeFreqField = sitemap_changefreq
                    priorityField = sitemap_priority
                    pid = 26
                    recursive = 2
                    url {
                        pageId = 25
                        fieldToParameterMap {
                            uid = tx_news_pi1[news]
                        }

                        additionalGetParameters {
                            tx_news_pi1.controller = News
                            tx_news_pi1.action = detail
                        }
                    }
                }
            }
        }
    }
}
</code>```

Here the documentation as well: Documentation

Body:
If this is all you have, then you are missing some key configuration. You need to specify what should be shown. So, on your TypoScript, based on the documentation, you should define what pages/extension etc must be shown. For example:

plugin.tx_seo {
  config {
    xmlSitemap {
      sitemaps {
        pages {
          config {
            excludedDoktypes = 137, 138
            additionalWhere = AND (no_index = 0 OR no_follow = 0)
            #rootPage = <optionally specify a different root page. (default: rootPageId from site configuration)>
          }
        }
      }
    }
  }
}

Here is an example for the extension news as well, in case you are using it.

plugin.tx_seo.config {
    xmlSitemap {
        sitemaps {
            news {
                provider = TYPO3\CMS\Seo\XmlSitemap\RecordsXmlSitemapDataProvider
                config {
                    table = tx_news_domain_model_news
                    additionalWhere =
                    sortField = sorting
                    lastModifiedField = tstamp
                    changeFreqField = sitemap_changefreq
                    priorityField = sitemap_priority
                    pid = 26
                    recursive = 2
                    url {
                        pageId = 25
                        fieldToParameterMap {
                            uid = tx_news_pi1[news]
                        }

                        additionalGetParameters {
                            tx_news_pi1.controller = News
                            tx_news_pi1.action = detail
                        }
                    }
                }
            }
        }
    }
}

Here the documentation as well: Documentation


问:
Subprojects var type in dsl
I am transitioning my code to Kotlin DSL and as i have multimodule app i have some hack to transition gralde tasks like clean, build etc to other modules. So i have following method in gradle:

```<code>private static def getSubProjectTasks(subprojects, taskName) {
    def tasks = []
    subprojects.each { Project project ->
        if (project.subprojects.size() == 0) {
            def relativeModulePath = project.path.replace(":feature:", "")
            tasks.add("$relativeModulePath:$taskName")
        }
    }
    return tasks
}
</code>```

Now trying to transition into kotlin dsl i started with this way

```<code>fun getSubProjectTasks(subproject: Unit, taskName: String) {
    for(project in subproject) {
        if(project.subprojects.size() == 0) {

        }
    }
}
</code>```

I am not really sure in Kotlin DSL what type subproject is? Is this just a collection or Unit or how to transition this method.

答:
Have you tried Iterable<Project>, List<Project> or Array<Project>?

I am judging based on your groovy lambda each.

You can also change your for for a map and have a single line doing everything:

fun getSubprojectTasks(subprojects: List<Subproject>, taskName: String) = subproject.mapNotNull { project ->
  if(project.subprojects.size == 0) {
    null
  } else {
    "${project.path.replace(":feature:", "")}$taskName"
  }

}
```

Title: Subprojects var type in dsl

Body:
I am transitioning my code to Kotlin DSL and as i have multimodule app i have some hack to transition gralde tasks like clean, build etc to other modules. So i have following method in gradle:

private static def getSubProjectTasks(subprojects, taskName) {
    def tasks = []
    subprojects.each { Project project ->
        if (project.subprojects.size() == 0) {
            def relativeModulePath = project.path.replace(":feature:", "")
            tasks.add("$relativeModulePath:$taskName")
        }
    }
    return tasks
}

Now trying to transition into kotlin dsl i started with this way

fun getSubProjectTasks(subproject: Unit, taskName: String) {
    for(project in subproject) {
        if(project.subprojects.size() == 0) {

        }
    }
}

I am not really sure in Kotlin DSL what type subproject is? Is this just a collection or Unit or how to transition this method.


问:
Is MUI DataGridPro key a secret?
import { LicenseInfo } from '@mui/x-data-grid-pro';

LicenseInfo.setLicenseKey(
'x0jTPl0USVkVZV0SsMjM1kDNyADM5cjM2ETPZJVSQhVRsIDN0YTM6IVREJ1T0b9586ef25c9853decfa7709eee27a1e',
);

Should the key be a secret?

答:
No, the license key does not need to be a secret. The only thing asked is not to proactively share your key to others.

http://mui.com/components/data-grid/getting-started/#security

Title: Is MUI DataGridPro key a secret?


问:
Using multiple forms in php but only one of them is working
Does a single php page contain more than 2 forms? If yes, how can we use it?</p>

答: Php does not support multiple form action in one form. Instead we can use mltiple submit buttons with unique names so that in php section we can redirect to any page using that button name.</p>


问:
How to get terminal print out when some print out are from exe file
I want to ask a question how to read all print out data in terminal in real time, which means that when the data is printed out in terminal, it's saved in text file synchronously. The python code is like:

```<code>def exe_run():
    os.system(r'"test.exe"')
    return

def main_run():
    #some code read from arduino serial port
    #...
    while True:
        data = ser.readline()
        print(data)
        count += 1
        if count % 3 == 0:
             exe_run() #run def exe_run every 3 times of arduino signal
             continue

result = main_run()
</code>```

In the exe file, it will gives a set of data when calling this file. So the result in terminal is something like:
arduino_siganl_1
arduino_siganl_2
arduino_siganl_3
exe_data_1
arduino_siganl_1
... (repeat)
Above is what I've got so far. And my question is I want to save all signals to text file in the same order like terminal. However, due to some data are come from exe file, I can't use f.write function. I tried sys.stdout, but I don't know how to make the 'saving to text' task become in real time. If I do things like:

```<code>sys.stdout = open('/the/path/to/your/file', 'w')
result = main_run()
sys.stdout.close()
</code>```

Seems data are not saved immediately when they are printed out, and some output are saved, some are not. Anyone has ideas how to achieve that? Thank you in advance.

答:
its generally not recommended to use os.system and instead they encourage you to use subprocess.Popen or other methods ...

```<code>def exe_run():
    return subprocess.check_output(['./test.exe'])
</code>```

now anything that is written to sys.stdout (ie print("asd")) will be returned to the caller

```<code>exe_output = exe_run()
# now do whatever you want with it...
print(f"------EXE OUTPUT-----\n{exe_output}\n-------END OUTPUT ----")
</code>```

if you want to just write to a file and make sure it is available you can use flush

```<code>with open("log.txt","wb") as fh:
    for i in range(2000):
       fh.write(f"{i},")
       fh.flush() # flush the output
       time.sleep(0.001)
</code>```

Body:
I want to ask a question how to read all print out data in terminal in real time, which means that when the data is printed out in terminal, it's saved in text file synchronously. The python code is like:

def exe_run():
    os.system(r'"test.exe"')
    return

def main_run():
    #some code read from arduino serial port
    #...
    while True:
        data = ser.readline()
        print(data)
        count += 1
        if count % 3 == 0:
             exe_run() #run def exe_run every 3 times of arduino signal
             continue

result = main_run()

In the exe file, it will gives a set of data when calling this file. So the result in terminal is something like:
arduino_siganl_1
arduino_siganl_2
arduino_siganl_3
exe_data_1
arduino_siganl_1
... (repeat)
Above is what I've got so far. And my question is I want to save all signals to text file in the same order like terminal. However, due to some data are come from exe file, I can't use f.write function. I tried sys.stdout, but I don't know how to make the 'saving to text' task become in real time. If I do things like:

sys.stdout = open('/the/path/to/your/file', 'w')
result = main_run()
sys.stdout.close()

Seems data are not saved immediately when they are printed out, and some output are saved, some are not. Anyone has ideas how to achieve that? Thank you in advance.

Body:
its generally not recommended to use os.system and instead they encourage you to use subprocess.Popen or other methods ...

def exe_run():
    return subprocess.check_output(['./test.exe'])

now anything that is written to sys.stdout (ie print("asd")) will be returned to the caller

exe_output = exe_run()
# now do whatever you want with it...
print(f"------EXE OUTPUT-----\n{exe_output}\n-------END OUTPUT ----")

if you want to just write to a file and make sure it is available you can use flush

with open("log.txt","wb") as fh:
    for i in range(2000):
       fh.write(f"{i},")
       fh.flush() # flush the output
       time.sleep(0.001)


问:
Incoming call notification in Android like whatsapp
I am an android developer. I didn't get any idea how to show notification when call is generate from server using opentok api. Also if anyone have any idea how Whatsapp does it. Kindly share how it will work.
Thanks a lot.

答:
Add this in your MANIFEST

```<code><uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
</code>```

Create a high priority notification service

```<code>import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import java.util.Objects;

public class HeadsUpNotificationService extends Service {
    private String CHANNEL_ID = "VoipChannel";
    private String CHANNEL_NAME = "Voip Channel";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Bundle data = null;
        if (intent != null && intent.getExtras() != null) {
            data = intent.getBundleExtra(ConstantApp.FCM_DATA_KEY);
        }
        try {
            Intent receiveCallAction = new Intent(getContext(), HeadsUpNotificationActionReceiver.class);
            receiveCallAction.putExtra(ConstantApp.CALL_RESPONSE_ACTION_KEY, ConstantApp.CALL_RECEIVE_ACTION);
            receiveCallAction.putExtra(ConstantApp.FCM_DATA_KEY, data);
            receiveCallAction.setAction("RECEIVE_CALL");

            Intent cancelCallAction = new Intent(getContext(), HeadsUpNotificationActionReceiver.class);
            cancelCallAction.putExtra(ConstantApp.CALL_RESPONSE_ACTION_KEY, ConstantApp.CALL_CANCEL_ACTION);
            cancelCallAction.putExtra(ConstantApp.FCM_DATA_KEY, data);
            cancelCallAction.setAction("CANCEL_CALL");

            PendingIntent receiveCallPendingIntent = PendingIntent.getBroadcast(getContext(), 1200, receiveCallAction, PendingIntent.FLAG_UPDATE_CURRENT);
            PendingIntent cancelCallPendingIntent = PendingIntent.getBroadcast(getContext(), 1201, cancelCallAction, PendingIntent.FLAG_UPDATE_CURRENT);

            createChannel();
            NotificationCompat.Builder notificationBuilder = null;
            if (data != null) {
                notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
                        .setContentText(data.getString("remoteUserName"))
                        .setContentTitle("Incoming Voice Call")
                        .setSmallIcon(R.drawable.ic_call_green)
                        .setPriority(NotificationCompat.PRIORITY_HIGH)
                        .setCategory(NotificationCompat.CATEGORY_CALL)
                        .addAction(R.drawable.ic_call_green, "Receive Call", receiveCallPendingIntent)
                        .addAction(R.drawable.ic_cancel_sexy, "Cancel call", cancelCallPendingIntent)
                        .setAutoCancel(true)
                        .setSound(Uri.parse("android.resource://" + getContext().getPackageName() + "/" + R.raw.voip_ringtone))
                        .setFullScreenIntent(receiveCallPendingIntent, true);
            }

            Notification incomingCallNotification = null;
            if (notificationBuilder != null) {
                incomingCallNotification = notificationBuilder.build();
            }
            startForeground(120, incomingCallNotification);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return START_STICKY;
    }

/*
Create noticiation channel if OS version is greater than or eqaul to Oreo
*/
    public void createChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            channel.setDescription("Call Notifications");
            channel.setSound(Uri.parse("android.resource://" + getContext().getPackageName() + "/" + R.raw.voip_ringtone),
                    new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                            .setLegacyStreamType(AudioManager.STREAM_RING)
                            .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION).build());
            Objects.requireNonNull(getContext().getSystemService(NotificationManager.class)).createNotificationChannel(channel);
        }
    }
}
</code>```

To handle Notification button clicks

```<code>import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

public class HeadsUpNotificationActionReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null && intent.getExtras() != null) {
            String action = intent.getStringExtra(ConstantApp.CALL_RESPONSE_ACTION_KEY);
            Bundle data = intent.getBundleExtra(ConstantApp.FCM_DATA_KEY);

            if (action != null) {
                performClickAction(context, action, data);
            }

           // Close the notification after the click action is performed.

            Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
            context.sendBroadcast(it);
            context.stopService(new Intent(context, HeadsUpNotificationService.class));
        }
    }

    private void performClickAction(Context context, String action, Bundle data) {
        if (action.equals(ConstantApp.CALL_RECEIVE_ACTION) && data != null && data.get("type").equals("voip")) {
            Intent openIntent = null;
            try {
                openIntent = new Intent(context, VoiceCallActivity.class));
                openIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(openIntent);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } else if (action.equals(ConstantApp.CALL_RECEIVE_ACTION) && data != null && data.get("type").equals("video")) {
            Intent openIntent = null;
            try {
                openIntent = new Intent(context, VideoCallActivity.class));
                openIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(openIntent);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } else if (action.equals(ConstantApp.CALL_CANCEL_ACTION)) {
            context.stopService(new Intent(context, HeadsUpNotificationService.class));
            Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
            context.sendBroadcast(it);
        }
    }
}
</code>```

Refer to this post for more details

Body:
Add this in your MANIFEST

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />

Create a high priority notification service

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import java.util.Objects;

public class HeadsUpNotificationService extends Service {
    private String CHANNEL_ID = "VoipChannel";
    private String CHANNEL_NAME = "Voip Channel";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Bundle data = null;
        if (intent != null && intent.getExtras() != null) {
            data = intent.getBundleExtra(ConstantApp.FCM_DATA_KEY);
        }
        try {
            Intent receiveCallAction = new Intent(getContext(), HeadsUpNotificationActionReceiver.class);
            receiveCallAction.putExtra(ConstantApp.CALL_RESPONSE_ACTION_KEY, ConstantApp.CALL_RECEIVE_ACTION);
            receiveCallAction.putExtra(ConstantApp.FCM_DATA_KEY, data);
            receiveCallAction.setAction("RECEIVE_CALL");

            Intent cancelCallAction = new Intent(getContext(), HeadsUpNotificationActionReceiver.class);
            cancelCallAction.putExtra(ConstantApp.CALL_RESPONSE_ACTION_KEY, ConstantApp.CALL_CANCEL_ACTION);
            cancelCallAction.putExtra(ConstantApp.FCM_DATA_KEY, data);
            cancelCallAction.setAction("CANCEL_CALL");

            PendingIntent receiveCallPendingIntent = PendingIntent.getBroadcast(getContext(), 1200, receiveCallAction, PendingIntent.FLAG_UPDATE_CURRENT);
            PendingIntent cancelCallPendingIntent = PendingIntent.getBroadcast(getContext(), 1201, cancelCallAction, PendingIntent.FLAG_UPDATE_CURRENT);

            createChannel();
            NotificationCompat.Builder notificationBuilder = null;
            if (data != null) {
                notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
                        .setContentText(data.getString("remoteUserName"))
                        .setContentTitle("Incoming Voice Call")
                        .setSmallIcon(R.drawable.ic_call_green)
                        .setPriority(NotificationCompat.PRIORITY_HIGH)
                        .setCategory(NotificationCompat.CATEGORY_CALL)
                        .addAction(R.drawable.ic_call_green, "Receive Call", receiveCallPendingIntent)
                        .addAction(R.drawable.ic_cancel_sexy, "Cancel call", cancelCallPendingIntent)
                        .setAutoCancel(true)
                        .setSound(Uri.parse("android.resource://" + getContext().getPackageName() + "/" + R.raw.voip_ringtone))
                        .setFullScreenIntent(receiveCallPendingIntent, true);
            }

            Notification incomingCallNotification = null;
            if (notificationBuilder != null) {
                incomingCallNotification = notificationBuilder.build();
            }
            startForeground(120, incomingCallNotification);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return START_STICKY;
    }

/*
Create noticiation channel if OS version is greater than or eqaul to Oreo
*/
    public void createChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            channel.setDescription("Call Notifications");
            channel.setSound(Uri.parse("android.resource://" + getContext().getPackageName() + "/" + R.raw.voip_ringtone),
                    new AudioAttributes.Builder().setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                            .setLegacyStreamType(AudioManager.STREAM_RING)
                            .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION).build());
            Objects.requireNonNull(getContext().getSystemService(NotificationManager.class)).createNotificationChannel(channel);
        }
    }
}

To handle Notification button clicks

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

public class HeadsUpNotificationActionReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null && intent.getExtras() != null) {
            String action = intent.getStringExtra(ConstantApp.CALL_RESPONSE_ACTION_KEY);
            Bundle data = intent.getBundleExtra(ConstantApp.FCM_DATA_KEY);

            if (action != null) {
                performClickAction(context, action, data);
            }

           // Close the notification after the click action is performed.

            Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
            context.sendBroadcast(it);
            context.stopService(new Intent(context, HeadsUpNotificationService.class));
        }
    }

    private void performClickAction(Context context, String action, Bundle data) {
        if (action.equals(ConstantApp.CALL_RECEIVE_ACTION) && data != null && data.get("type").equals("voip")) {
            Intent openIntent = null;
            try {
                openIntent = new Intent(context, VoiceCallActivity.class));
                openIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(openIntent);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } else if (action.equals(ConstantApp.CALL_RECEIVE_ACTION) && data != null && data.get("type").equals("video")) {
            Intent openIntent = null;
            try {
                openIntent = new Intent(context, VideoCallActivity.class));
                openIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(openIntent);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        } else if (action.equals(ConstantApp.CALL_CANCEL_ACTION)) {
            context.stopService(new Intent(context, HeadsUpNotificationService.class));
            Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
            context.sendBroadcast(it);
        }
    }
}

Refer to this post for more details


问:
Azure Cost Management - Budget Alert Script
I have a request to setup budget alert on our resource groups located in different subscriptions.  I am  trying to decide if it make sense to do it thru PowerShell or Terraform to automate this process.  My thinking is that management would update a .csv file quarterly with the budget amount and alert threshold for each of the RGs they want to set alerts form.  The .csv will have the following fields/columns:

SubscriptionName, SubscriptionId, ResourcegGropu, StartDate,
EndDate,TimeGrain,ContactEmails,Contact,BudgetAmount,budgetName,
alertLevels

Any suggests?  Thanks

答:
Using Terraform to perform the same operation on different Subscriptions will be difficult as for_each is not supported in provider blocks as shown in below image , so you will have to manually set up the provider blocks for all the subscriptions.

```<code>locals{
    budget=csvdecode(file("C:/Users/xxxxx/terraform/budgetalert/Budget.csv"))
}
provider "azurerm"{
    for_each ={ for i , user in local.budget : i => budget }
    features{}
    subscription_id = each.value.SubscriptionId
    alias = each.value.SubscriptionName
}
</code>```

As a solution to do this from terraform you can create different .csv files for different subscriptions and call them in different resource provider blocks like below :

```<code>provider "azurerm"{
    features {}
    subscription_id = "b83-----xxxxxxxxxxx-xxxx-xxxxx----23f"
}
provider "azurerm" {
    features {}
  subscription_id = "948--------x--xxxxxxxxxxxxx-xxxxxxx-59b"
  alias = "Subscription2"
}

locals{
    budgetsub1=csvdecode(file("C:/Users/xxxx/terraform/budgetalert/Budget.csv"))
    budgetsub2=csvdecode(file("C:/Users/xxxx/terraform/budgetalert/budgetsub2.csv"))
}
output "local" {
  value=local.budgetsub1
}
output "local1" {
  value = local.budgetsub2
}

data "azurerm_resource_group" "rg_subscription1"{
    for_each = { for i , budget in local.budgetsub1 : i => budget }
    name= each.value.ResourceGroup
}
data "azurerm_resource_group" "rg_subscription2"{
    provider = azurerm.Subscription2
    for_each = { for i , budget in local.budgetsub2 : i => budget }
    name= each.value.ResourceGroup
}

resource "azurerm_consumption_budget_resource_group" "rg_budget_subscription1" {
    for_each = { for i , budget in local.budgetsub1 : i => budget }
  name       = each.value.budgetName
  amount     = each.value.BudgetAmount
  time_grain = each.value.TimeGrain
  time_period {
    start_date = each.value.StartDate
    end_date  = each.value.EndDate
  }
  resource_group_id = data.azurerm_resource_group.rg_subscription1[each.key].id
  notification {
      enabled = true
    threshold      = 80
    operator       = "GreaterThanOrEqualTo"
    contact_emails = ["${each.value.ContactEmails}"]
  }
  lifecycle {
    ignore_changes = [
      time_period
    ]
  }
}
resource "azurerm_consumption_budget_resource_group" "rg_budget_subscription2" {
    provider = azurerm.Subscription2
    for_each = { for i , budget in local.budgetsub2 : i => budget }
  name       = each.value.budgetName
  amount     = each.value.BudgetAmount
  time_grain = each.value.TimeGrain
  time_period {
    start_date = each.value.StartDate
    end_date  = each.value.EndDate
  }
  resource_group_id = data.azurerm_resource_group.rg_subscription2[each.key].id
  notification {
      enabled = true
    threshold      = 80
    operator       = "GreaterThanOrEqualTo"
    contact_emails = ["${each.value.ContactEmails}"]
  }
  lifecycle {
    ignore_changes = [
      time_period
    ]
  }
}
</code>```

Output:

Body:
Using Terraform to perform the same operation on different Subscriptions will be difficult as for_each is not supported in provider blocks as shown in below image , so you will have to manually set up the provider blocks for all the subscriptions.

locals{
    budget=csvdecode(file("C:/Users/xxxxx/terraform/budgetalert/Budget.csv"))
}
provider "azurerm"{
    for_each ={ for i , user in local.budget : i => budget }
    features{}
    subscription_id = each.value.SubscriptionId
    alias = each.value.SubscriptionName
}

As a solution to do this from terraform you can create different .csv files for different subscriptions and call them in different resource provider blocks like below :

provider "azurerm"{
    features {}
    subscription_id = "b83-----xxxxxxxxxxx-xxxx-xxxxx----23f"
}
provider "azurerm" {
    features {}
  subscription_id = "948--------x--xxxxxxxxxxxxx-xxxxxxx-59b"
  alias = "Subscription2"
}

locals{
    budgetsub1=csvdecode(file("C:/Users/xxxx/terraform/budgetalert/Budget.csv"))
    budgetsub2=csvdecode(file("C:/Users/xxxx/terraform/budgetalert/budgetsub2.csv"))
}
output "local" {
  value=local.budgetsub1
}
output "local1" {
  value = local.budgetsub2
}

data "azurerm_resource_group" "rg_subscription1"{
    for_each = { for i , budget in local.budgetsub1 : i => budget }
    name= each.value.ResourceGroup
}
data "azurerm_resource_group" "rg_subscription2"{
    provider = azurerm.Subscription2
    for_each = { for i , budget in local.budgetsub2 : i => budget }
    name= each.value.ResourceGroup
}

resource "azurerm_consumption_budget_resource_group" "rg_budget_subscription1" {
    for_each = { for i , budget in local.budgetsub1 : i => budget }
  name       = each.value.budgetName
  amount     = each.value.BudgetAmount
  time_grain = each.value.TimeGrain
  time_period {
    start_date = each.value.StartDate
    end_date  = each.value.EndDate
  }
  resource_group_id = data.azurerm_resource_group.rg_subscription1[each.key].id
  notification {
      enabled = true
    threshold      = 80
    operator       = "GreaterThanOrEqualTo"
    contact_emails = ["${each.value.ContactEmails}"]
  }
  lifecycle {
    ignore_changes = [
      time_period
    ]
  }
}
resource "azurerm_consumption_budget_resource_group" "rg_budget_subscription2" {
    provider = azurerm.Subscription2
    for_each = { for i , budget in local.budgetsub2 : i => budget }
  name       = each.value.budgetName
  amount     = each.value.BudgetAmount
  time_grain = each.value.TimeGrain
  time_period {
    start_date = each.value.StartDate
    end_date  = each.value.EndDate
  }
  resource_group_id = data.azurerm_resource_group.rg_subscription2[each.key].id
  notification {
      enabled = true
    threshold      = 80
    operator       = "GreaterThanOrEqualTo"
    contact_emails = ["${each.value.ContactEmails}"]
  }
  lifecycle {
    ignore_changes = [
      time_period
    ]
  }
}

Output:


问:
How can I swap internal IP address between two GCP VMs?
I have a running VM1 (internal IP is: xxx.xxx.0.7). I will create another new VM2 and I want to change the IP of VM1 to any other IP and set the IP of VM2 to "xxx.xxx.0.7". OS of both VM is windows server.

I have found some way to change the IP of a running VM. But I am not sure if that works. Is there any straightforward way to do this?

Thanks in advance!

答: This should be possible, while you'd have to use a temporary third one IP address, in order not to produce a duplicate address conflict among one of the other two addresses, while changing them. They MUST be unique at any time, else you'll have a routing problem. The most straightforward might be to use both server's serial consoles, because these would not care about temporary IP address conflicts. The crux is, that one cannot change both at precisely the same time, and as soon as having produced the duplicate IP address, one may want to resort to the serial console anyway.</p>


问:
convert times like these 1h30m/13h30m/1d5m into seconds
```<code>time_convert = {"s":1, "m":60, "h":3600,"d":86400}
converted = int(time[0]) * time_convert[time[-1]]
</code>```

That code above only converts the first first number to the corresponding converted time so 12h would come back as 3600 instead of 43200, so that way no other times would work for what I'm trying to do.
I'm wanting to convert any time the user says into seconds so, 1h5m,15h40m,1d55m ect

答:
You can use also strptime to convert the string to a time object and timedelta to calculate the total number of seconds:

```<code>import time
from datetime import timedelta

time_str = "1h30m"

time_obj = time.strptime(time_str, "%Hh%Mm")
seconds = timedelta(hours=time_obj.tm_hour, minutes=time_obj.tm_min).total_seconds()

print(seconds)
</code>```

This will output:

```<code>5400.0
</code>```

You can find more on how to configure expected time format and others here:  strptime and timedelta

Body:
time_convert = {"s":1, "m":60, "h":3600,"d":86400}
converted = int(time[0]) * time_convert[time[-1]]

That code above only converts the first first number to the corresponding converted time so 12h would come back as 3600 instead of 43200, so that way no other times would work for what I'm trying to do.
I'm wanting to convert any time the user says into seconds so, 1h5m,15h40m,1d55m ect

Body:
You can use also strptime to convert the string to a time object and timedelta to calculate the total number of seconds:

import time
from datetime import timedelta

time_str = "1h30m"

time_obj = time.strptime(time_str, "%Hh%Mm")
seconds = timedelta(hours=time_obj.tm_hour, minutes=time_obj.tm_min).total_seconds()

print(seconds)

This will output:

5400.0

You can find more on how to configure expected time format and others here:  strptime and timedelta


问:
Minikube restarts forever
I have an issue. I typed the minikube start command and it stuck. What should I do? Is deleting minikube the only solution?

```<code>Restarting existing docker container for "minikube"
</code>```

答:
You can try sudo minikube delete to delete the container first,
then minikube start and see if the issue is fixed or not.

Title: Minikube restarts forever

Body:
I have an issue. I typed the minikube start command and it stuck. What should I do? Is deleting minikube the only solution?

Restarting existing docker container for "minikube"


问:
Is this the correct way to save form values in MVC3?
Here's my code:

```<code>[HttpGet]
public ActionResult Register()
{
    RegisterViewModel model = new RegisterViewModel();
    using (CityRepository city = new CityRepository())
    {
        model.SelectCityList = new SelectList(city.FindAllCities().ToList(), "CityID", "CityName");
    }

    using (CountryRepository country = new CountryRepository())
    {
        model.SelectCountryList = new SelectList(country.FindAllCountries().ToList(), "CountryID", "CountryName");
    }

    return View(model);
}

[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        //Actually register the user here.
        RedirectToAction("Index", "Home");
    }

    //Something went wrong, redisplay the form for correction.
    return View(model);
}
</code>```

Is this the best approach or is there another better tested way? Keep in mind that my database tables/field names are nothing like what I declared in my models. I have to scrape the values from the ViewModel and put them into an entity framework generated class to persist the information.

Anything here that screams out at you as wrong?

答:
I prefer this pattern:

Controller:

```<code> [HttpGet]
        public ActionResult Index()
        {
            var cities= (from m in db.cities select m);
            ViewBag.Cities= cities;

            var states = (from m in db.States select m);
            ViewBag.States = states;

            return View();
        }
        [HttpPost]
         public ActionResult Index(RegisterViewModel model)
             {
             if (ModelState.IsValid)
                {
                  // Saving the data
                  return View("ActionName", model);
                }
        return View();
    }
</code>```

View:

```<code>@Html.DropDownList("DDLCities",new SelectList(ViewBag.Cities, "CityId" , "CityName" ), new { @class = "className" })
@Html.DropDownList("DDLStates",new SelectList(ViewBag.States, "StateId" , "StateName" ), new { @class = "className" })
</code>```

Body:
Here's my code:

[HttpGet]
public ActionResult Register()
{
    RegisterViewModel model = new RegisterViewModel();
    using (CityRepository city = new CityRepository())
    {
        model.SelectCityList = new SelectList(city.FindAllCities().ToList(), "CityID", "CityName");
    }

    using (CountryRepository country = new CountryRepository())
    {
        model.SelectCountryList = new SelectList(country.FindAllCountries().ToList(), "CountryID", "CountryName");
    }

    return View(model);
}

[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        //Actually register the user here.
        RedirectToAction("Index", "Home");
    }

    //Something went wrong, redisplay the form for correction.
    return View(model);
}

Is this the best approach or is there another better tested way? Keep in mind that my database tables/field names are nothing like what I declared in my models. I have to scrape the values from the ViewModel and put them into an entity framework generated class to persist the information.

Anything here that screams out at you as wrong?

Body:
I prefer this pattern:

Controller:

 [HttpGet]
        public ActionResult Index()
        {
            var cities= (from m in db.cities select m);
            ViewBag.Cities= cities;

            var states = (from m in db.States select m);
            ViewBag.States = states;

            return View();
        }
        [HttpPost]
         public ActionResult Index(RegisterViewModel model)
             {
             if (ModelState.IsValid)
                {
                  // Saving the data
                  return View("ActionName", model);
                }
        return View();
    }

View:

@Html.DropDownList("DDLCities",new SelectList(ViewBag.Cities, "CityId" , "CityName" ), new { @class = "className" })
@Html.DropDownList("DDLStates",new SelectList(ViewBag.States, "StateId" , "StateName" ), new { @class = "className" })


问:
HTML/JS - Start timer on load
All works great. At the moment, I don't have to press the button to start the timer, it start automatically on page load. Problem is the start, stop and reset buttons still appeared. When I hide the button code the timer not working. When the page load the buttons should not be appeared and timer should work fine.

Here is my code:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>30 second countdown timer</title>
  </head>
  <body onload="startTimer();">
    <div id="countdown">
      <div id="countdown-number">30</div>
    </div>
    <div class="action-list">
      <button id="stop">
        <img src="https://img.icons8.com/ios-glyphs/30/000000/pause--v1.png" />
      </button>
      <button id="start">
        <img src="https://img.icons8.com/ios-glyphs/30/000000/play--v1.png" />
      </button>
      <button id="reset">
        <img src="https://img.icons8.com/ios-glyphs/30/000000/stop.png" />
      </button>
    </div>
    <audio id="timeout_audio"></audio>
  </body>
</html>

<script>
  // Select Countdown container
const countContainer = document.getElementById("countdown-number");

// Select action buttons
const startButton = document.getElementById("start");
const stopButton = document.getElementById("stop");
const resetButton = document.getElementById("reset");

// Select timeout Audio element
const timeoutAudio = document.getElementById("timeout_audio");

// variable to store count
var remainingTime = 30;

// variable to store time interval
var timer;

// Variable to track whether timer is running or not
var isStopped = true;

// Function to start Timer
const startTimer = () => {
  if (isStopped) {
    isStopped = false;
    countContainer.innerHTML = remainingTime;
    timer = setInterval(renderTime, 1000);
  }
};

// Function to stop Timer
const stopTimer = () => {
  isStopped = true;
  if (timer) {
    clearInterval(timer);
  }
};

// Function to reset Timer
const resetTimer = () => {
  isStopped = true;
  clearInterval(timer);
  remainingTime = 30;
  countContainer.innerHTML = remainingTime;
};

// Initialize timeout sound
timeoutAudio.src = "http://soundbible.com/grab.php?id=1252&type=mp3";
timeoutAudio.load();

// Attach onclick event to buttons
startButton.onclick = startTimer;
resetButton.onclick = resetTimer;
stopButton.onclick = stopTimer;

// function to display time
const renderTime = () => {
  // decement time
  remainingTime -= 1;
  // render count on the screen
  countContainer.innerHTML = remainingTime;
  // timeout on zero
  if (remainingTime === 0) {
    isStopped = true;
    clearInterval(timer);
    // Play audio on timeout
    timeoutAudio.play();
    remainingTime = 30;
  }
};
</script>
<style>
  body {
  font-family: sans-serif;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-image: url("https://img4.goodfon.com/wallpaper/nbig/1/2e/multfilm-shou-simpsons-personazh-20th-century-fox-art-ris-15.jpg");
}
#countdown {
  display: flex;
  justify-content: center;
  align-items: center;
  color: #0e2c4c;
  font-size: 70px;
  width: 200px;
  height: 200px;
  background-color: #e7d9fc;
  border-radius: 50%;
}
.action-list {
  display: flex;
  gap: 30px;
  margin-top: 30px;
}
button {
  border: none;
  background-color: #e7d9fc;
  border-radius: 50%;
  width: 60px;
  height: 60px;
  cursor: pointer;
}
</style>
</code>```

答:
So, basically you want that when the page loads, the buttons should not be dispalyed, and the timer should work fine. So, what you can do is, take the div for the buttons, and set its dispaly to none when the timer starts running, and when the timer reaches 0, again set the display to block.

write this in your script

```<code>var x = document.getElementsByClassName('action-list')[0];
</code>```

and in your startTimer function, set the display to none

```<code>const startTimer = () => {
  x.style.display = "none";
  // your code for startTimer
};
</code>```

In your renderTime() function, when the time reaches 0, you can set the display to block

```<code>const renderTime = () => {
  remainingTime -= 1;
  countContainer.innerHTML = remainingTime;
  // timeout on zero
  if (remainingTime === 0) {
    isStopped = true;
    clearInterval(timer);
    // set the display to block, so that the buttons appear again
    x.style.display = "block";
    // Play audio on timeout
    timeoutAudio.play();
    remainingTime = 30;
  }
};
</code>```

Title: HTML/JS - Start timer on load

Body:
All works great. At the moment, I don't have to press the button to start the timer, it start automatically on page load. Problem is the start, stop and reset buttons still appeared. When I hide the button code the timer not working. When the page load the buttons should not be appeared and timer should work fine.

Here is my code:

<!DOCTYPE html>

    <title>30 second countdown timer</title>

30

      <button id="stop">

      </button>
      <button id="start">

      </button>
      <button id="reset">

      </button>

    <audio id="timeout_audio"></audio>

Body:
So, basically you want that when the page loads, the buttons should not be dispalyed, and the timer should work fine. So, what you can do is, take the div for the buttons, and set its dispaly to none when the timer starts running, and when the timer reaches 0, again set the display to block.

write this in your script

var x = document.getElementsByClassName('action-list')[0];

and in your startTimer function, set the display to none

const startTimer = () => {
  x.style.display = "none";
  // your code for startTimer
};

In your renderTime() function, when the time reaches 0, you can set the display to block

const renderTime = () => {
  remainingTime -= 1;
  countContainer.innerHTML = remainingTime;
  // timeout on zero
  if (remainingTime === 0) {
    isStopped = true;
    clearInterval(timer);
    // set the display to block, so that the buttons appear again
    x.style.display = "block";
    // Play audio on timeout
    timeoutAudio.play();
    remainingTime = 30;
  }
};


问:
Nondeterministic growth in Julia loop
I have a computation loop with adaptive time stepping and I need to store the results at each iteration. In other words, I do not know the vector size before the computation, so I can not preallocate a vector size to store the data. Right now, I build a vector using the push! function

```<code>function comp_loop()
    clock = [0.0]
    data = [0.0]
    while run_time < model_time

        # Calculate new timestep
        timestep = rand(Float64)  # Be sure to add Random
        run_time += timestep

        # Build vector
        push!(clock,run_time)
        push!(data,timestep)

    end
end
</code>```

Is there a more efficient way to go about this? Again, I know the optimal choice is to preallocate the vector, but I do not have that luxury available. Buffers are theoretically not an option either, as I don't now how large to make them. I'm looking for something more "optimal" on how to implement this in Julia (i.e. maybe some advanced application available in the language).

答:
Theoretically, you can use a linked list such as the one from DataStructures.jl to get O(1) appending.  And then optionally write that out to a Vector afterwards (probably in reverse order, though).

In practise, push!ing to a Vector is often efficient enough -- Vectors use a doubling strategy to manage their dynamic size, which leads to amortized constant time and the advantage of contiguous memory access.

So you could try the linked list, but be sure to benchmark whether it's worth the effort.

Now, the above is about time complexity.  When you care about allocation, the argument is quite similar; with a vector, you are going to end up with memory proportional to the next power of two after your actual requirements.  Most often, that can be considered amortized, too.

Title: Nondeterministic growth in Julia loop

Body:
I have a computation loop with adaptive time stepping and I need to store the results at each iteration. In other words, I do not know the vector size before the computation, so I can not preallocate a vector size to store the data. Right now, I build a vector using the push! function

function comp_loop()
    clock = [0.0]
    data = [0.0]
    while run_time < model_time

        # Calculate new timestep
        timestep = rand(Float64)  # Be sure to add Random
        run_time += timestep

        # Build vector
        push!(clock,run_time)
        push!(data,timestep)

    end
end

Is there a more efficient way to go about this? Again, I know the optimal choice is to preallocate the vector, but I do not have that luxury available. Buffers are theoretically not an option either, as I don't now how large to make them. I'm looking for something more "optimal" on how to implement this in Julia (i.e. maybe some advanced application available in the language).


问:
I want to do ternary operation like below code but code is not working fine
When I change f7 value it will perform correctly till second condition but third and fourth condition does not trigger. What can I do please help me it stop on second condition?

```<code>var f7 = 5;
var g7 = (f7 <= 3 ? 100 : (2 <= f7 < 4 ? 75 : (4 <= f7 < 5 ? 60 : (5 <= f7 < 6 ? 40 : 15))));
console.log(g7);
</code>```

答:
The problem is the order in which you're executing the comparisons. I like to format ternary expressions over multiple lines to make them easier to work with, removing unnecesary brackets unless they help readability.

E.g.

```<code>var g7 = f7 <= 3
  ? 100
  : 2 <= f7 < 4
     ? 75
     : 4 <= f7 < 5
        ? 60
        : 5 <= f7 < 6
           ? 40
           : 15
</code>```

That makes it a little clearer that your first comparison overlaps the values tested for in your second comparison. Do you really mean to check f7 <= 3 before checking that 2<=f7<4?

I would have thought this would be used with a strictly ascending range of values with no overlaps.

Body:
When I change f7 value it will perform correctly till second condition but third and fourth condition does not trigger. What can I do please help me it stop on second condition?

var f7 = 5;
var g7 = (f7 <= 3 ? 100 : (2 <= f7 < 4 ? 75 : (4 <= f7 < 5 ? 60 : (5 <= f7 < 6 ? 40 : 15))));
console.log(g7);

Body:
The problem is the order in which you're executing the comparisons. I like to format ternary expressions over multiple lines to make them easier to work with, removing unnecesary brackets unless they help readability.

E.g.

var g7 = f7 <= 3
  ? 100
  : 2 <= f7 < 4
     ? 75
     : 4 <= f7 < 5
        ? 60
        : 5 <= f7 < 6
           ? 40
           : 15

That makes it a little clearer that your first comparison overlaps the values tested for in your second comparison. Do you really mean to check f7 <= 3 before checking that 2<=f7<4?

I would have thought this would be used with a strictly ascending range of values with no overlaps.


问:
Az query to list all subscriptions, resource groups and resources in it
I am trying to iterate over all azure subscriptions, resource groups and resources</p>

答:
An easier way of doing it would be to use the Azure Resource Graph Explorer. I find it to be very powerful, flexible and hassle-free for querying anything about Azure. I'd suggest to give it a try if you're often going to be working with Azure inventory - it's also very user-friendly and uses KQL as query language. You can easily filter out the results as you need.

Here's how you would query all resources across all of your subscriptions:

Make sure the scope is your entire tenant

Type the following query:

```<code>resources
</code>```

Run the query

Download as CSV

Here's how this would look like below:

Body:
An easier way of doing it would be to use the Azure Resource Graph Explorer. I find it to be very powerful, flexible and hassle-free for querying anything about Azure. I'd suggest to give it a try if you're often going to be working with Azure inventory - it's also very user-friendly and uses KQL as query language. You can easily filter out the results as you need.

Here's how you would query all resources across all of your subscriptions:

Make sure the scope is your entire tenant

Type the following query:

resources

Run the query

Download as CSV

Here's how this would look like below:


问:
Content Scroll to Bottom Not Working
I am Developing App in ionic. when load page scrollToBottom not working.

Html section

<ion-content #content>
</ion-content>
```

<p>TS Section</p>

<pre class="lang-ts prettyprint-override"><code>@ViewChild(Content) content: Content;

ionViewDidLoad() {
    console.log('ionViewDidLoad PersonalChatPage');
    this.content.scrollToBottom();
}
</code>```

答:
don't use the garbage scrolling methods from your framework I have the same problem with framework ionic, instead use standard .scrollIntoView() it works nicely...

I set up two dummy hidden divs, top and bottom around my "content" like so

```<code><div id="QV_Top">TOP</div>
... your actual content here
<div id="QV_Bottom">BOTTOM</div>
</code>```

then fixed my scroll helper methods like so:

finally the actual scroll to id follows:

Title: Content Scroll to Bottom Not Working

Body:
I am Developing App in ionic. when load page scrollToBottom not working.

Html section

<ion-content #content>
</ion-content>

TS Section

@ViewChild(Content) content: Content;

ionViewDidLoad() {
    console.log('ionViewDidLoad PersonalChatPage');
    this.content.scrollToBottom();
}

Body:
don't use the garbage scrolling methods from your framework I have the same problem with framework ionic, instead use standard .scrollIntoView() it works nicely...

I set up two dummy hidden divs, top and bottom around my "content" like so

<div id="QV_Top">TOP</div>
... your actual content here
<div id="QV_Bottom">BOTTOM</div>

then fixed my scroll helper methods like so:

finally the actual scroll to id follows:


问:
Set up a number of categories to display on a page
I am basically looking for a way to display only 3 categories on my template page.
I used a foreach loop to display all the categories on my pages

```<code>$categories = get_categories();
foreach($categories as $category) {
   echo '<div class="col-md-4"><a href="' .
    get_category_link($category->term_id) . '">' . $category->name
  . '</a></div>';
}?>
</code>```

this code displays all the categories on my page but I just want to display 3 per page and eventually add paginations

答:
```<code>$startCategory = 0;
for($i = $startCategory; $i <= count($categories); $i++) {
 echo '<div class="col-md-4"><a href="' .get_category_link($categories[$i]['term_id']) . '">' . $categories[$i]['name']. '</a></div>';
 $startCategory++;
 if($startCategory > (count($categories) -1)){
  break;
 }
//pass $startCategory to next page , next page
$startCategory  = $_POST["startCategory"]; // by using post method

$startCategory  = $_GET["startCategory"]; // by using get method
for($i = $startCategory; $i <= count($categories); $i++) {
echo '<div class="col-md-4"><a href="' .
    get_category_link($categories[$i]['term_id']) . '">' . $categories[$i]['name']
  . '</a></div>';
$startCategory++;
 if($startCategory > (count($categories) -1)){
  break;
 }
}
</code>```

Body:
I am basically looking for a way to display only 3 categories on my template page.
I used a foreach loop to display all the categories on my pages

$categories = get_categories();
foreach($categories as $category) {
   echo '
term_id) . '">' . $category->name
  . '
';
}?>

this code displays all the categories on my page but I just want to display 3 per page and eventually add paginations


问:
We made it reliable. What's next? Usability?
I'm working in a small development group. We are building and improving our product.

Half a year ago we couldn't think about higher characteristics, such as usability, because we had so many problems with our product. Many bugs, high technical debt, low performance and other problems kept us from being able to focus on usability.

With time we've improved our process substantially. What we've done:

Real Agile iterations

Continuous integration

Testing(unit-tests, functional Smoke tests, performance)

Code quality is 'good'

Painless deployment process

So we are now producing stable, reliable releases. The following quote (paraphrased) describes our current situation:

first - make it work; after that, make it reliable; after that, make it usable

We are geeks, so we can't 'make' a great UI by ourselves.
So what should we do? What direction can you recommend?
Maybe we should hire Usability experts part-time or full-time?
How can we explain the importance of Usability to our stakeholders?
How do we convince them that this is useful?

答:
I know so many geeks including myself who know usability, so one way would be learning it. Another way bringing someone in who can do UI design and usability.

To convince them that usability is important:
It's useless if you can't use it!

I don't know what sort of product you build but you always got clients, and clients always love usable applications. This will increase sales, happy client count and decrease tech support.

OwnerDisplayName: Fedyashev Nikita

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Gortok

OwnerDisplayName: Slough


问:
Psudo-Random Number Prediction
I am building a program using various methods of generating psudo random numbers. With reasonable results. I of course get better results (statistically speaking), if I use either the inbuilt random number generator in visual C#, or some other formal psudo random code where the method is not known to me. This is not my question.

My question is, given any of the methods used, and given the fact that any computer generated random number is done according to a specified formula and code logic, it is not by definition truly random. Hense the term psudo random.

Given that fact, is it possible to accurately predict what the number will be. Or at least predict it more accurately than a good guess. My research says that anything guessed correctly up to 73% of the time is really only good guessing. So in order to be considered accurate prediction, it must be able to show correct "guesses" more than 73% of the time in order to say it is not a guess.

Assume we dont know the seed, or if we do know the seed, then we dont know the formula used to get the result from the seed.

The below was edited after I accepted an answer and is for future people woundering what I meant.

up to 73% is a "good guesser" - the accepted answer says there is no such thing. So I will clarify.

In the context of the documentary that I watched they weighted things as follows (my words not direct quotes of the program):

Below 37% is just plain wrong (or a poor guesser).

37% to 63% is the expected range of a normal persons ability to guess, some poorly some well. On average it comes to around 50%.

Really "good guessers", were able to break the 63% barrier and sometimes by a large amount either because they knew what their counterparts (in the case of twins) might answer and therefore answered likewise, or had some other system (in the case of fortune tellers and the like).

Tests were done to determine these systems and it was found that comming close to the 73% barrier by anyone was almost impossible, and it was simply impossible to do it on a regular basis (i.e. more than once) showing that they got lucky the first time round. So anyone who got more than 63% but less than 73% on a regular basis was simply labeled a "good guesser".

One of the answers below suggest if you flip a coin 4 times and you guess right 3 out of 4 times you get 75%. But to do it 10 or 100 times is much more difficult. In the explanation above, the first case would show you were able to predict the future accurately enough to make a difference. Continuing with the same test under the same conditions, ie another 4 flips, and another 4. Would almost always bring the person well below the 73% mark showing them to be at best a "good guesser".

I only mention this to clarify. Its not actually part of the question. Thank you all for your answers and suggestions.

答:
where did you get 73% from?!  statistics doesn't really work like that.  you are ignoring two factors:

what is important is not the percentage, but the numbers of wrong and right.  if you guessed a coin toss three times out of four that would be 75% right, but could easily be luck.  in contrast, guessing 75 times out of a hundred, while still 75%, is very unlikely to be down to chance.

guessing something from many choices is more impressive than guessing between few options.  so guessing whether a coin is heads or tails is relatively easy - you will be right half the time.  but guessing a random number, which might have any value from 0 to a million, say, is much harder - even if someone only guess that correctly 1% of the time, it would be very unusual.

anyway, to answer the question, with enough pseudo-random numbers you may start to predict certain patterns (for example, successive numbers may make a pattern in a "space" of some dimension).  that might not give you the next number, but may give you enough to say whether it will will be larger or smaller than average, for example.

and if you know the underlying algorithm then, you in some cases you can work backwards from the random number (or a series of values) to find the "internal state".  once you have that you can predict all future numbers, because you are effectively running the same program in parallel.

random number generators designed to avoid these two problems (and some others) are called "secure random number generators".

Title: Psudo-Random Number Prediction