问:
Deleting certain values fitting a requirement from dictionary in Python
I am an aspiring programmer and I wanted to take out the brightest colors from the matplotlib CSS4
dictionary which can be reached with "print(matplotlib.colors.CSS4_COLORS". Can you please fix it?

```<code>def hex_to_rgb(hex):
    hex = hex.lstrip('#')
    lv = len(hex)
    return tuple(int(hex[i:i+lv//3], 16) for i in range(0, lv, lv//3))

for key, value in CSS4_COLORS.items():
    rgb = hex_to_rgb(value)
    rgb_average = (rgb[0] + rgb[1] + rgb[2]) / 3
    if rgb_average > 210:
        del CSS4_COLORS[key]

print(CSS4_COLORS)
</code>```

It gives out the error:

```<code>RuntimeError: dictionary changed size during iteration
</code>```

Sorry if this was answered before, I must have not understood then.

答:
The error messages states what the problem is: it is not permitted to delete elements of a dictionary you are currently iterating over. You can find more on the reasoning behind this at this post, but the essence is that deleting an entry changes the 'iteration order', so you cannot simply continue iteration where you left off.

A simple way to solve this would be to duplicate the dictionary, iterating over the first and deleting entries from the second. Better yet is to use a dictionary comprehension to construct a new dictionary with only the elements of the old dictionary that have a low enough average.

def hex_to_rgb(hex):
    hex = hex.lstrip('#')
    lv = len(hex)
    return tuple(int(hex[i:i+lv//3], 16) for i in range(0, lv, lv//3))

def average(value):
    rgb = hex_to_rgb(value)
    return (rgb[0] + rgb[1] + rgb[2]) / 3

without_brightest = {key:value for key, value in CSS$_COLORS.items() if average(value) <= 210}
# The condition becomes the opposite, <= 210 instead of > 210, because we are deciding what to include instead of what to delete.

print(without_brightest)
```

<p>This will yield the new dictionary excluding the bright values, and it will leave the original matplotlib dictionary intact.</p>

<p>If, for some reason, you need to modify the original dictionary instead of creating a new one, you can use the method mentioned previously of making a second dictionary to iterate over. You can make a shallow copy with <code>dict.copy</code>, which would change your second for loop to</p>

<pre class="lang-py prettyprint-override"><code>for key, value in CSS4_COLORS.copy().items():
    rgb = hex_to_rgb(value)
    rgb_average = (rgb[0] + rgb[1] + rgb[2]) / 3
    if rgb_average > 210:
        del CSS4_COLORS[key]
</code>```

This would create a new dictionary to iterate over, and modify the original. You should probably only use this method if you need the original modified and cannot simply assign another dictionary to it. You have to make a new dictionary object either way, so the first variant is preferable.

Body:
I am an aspiring programmer and I wanted to take out the brightest colors from the matplotlib CSS4
dictionary which can be reached with "print(matplotlib.colors.CSS4_COLORS". Can you please fix it?

def hex_to_rgb(hex):
    hex = hex.lstrip('#')
    lv = len(hex)
    return tuple(int(hex[i:i+lv//3], 16) for i in range(0, lv, lv//3))

for key, value in CSS4_COLORS.items():
    rgb = hex_to_rgb(value)
    rgb_average = (rgb[0] + rgb[1] + rgb[2]) / 3
    if rgb_average > 210:
        del CSS4_COLORS[key]

print(CSS4_COLORS)

It gives out the error:

RuntimeError: dictionary changed size during iteration

Sorry if this was answered before, I must have not understood then.

Body:
The error messages states what the problem is: it is not permitted to delete elements of a dictionary you are currently iterating over. You can find more on the reasoning behind this at this post, but the essence is that deleting an entry changes the 'iteration order', so you cannot simply continue iteration where you left off.

A simple way to solve this would be to duplicate the dictionary, iterating over the first and deleting entries from the second. Better yet is to use a dictionary comprehension to construct a new dictionary with only the elements of the old dictionary that have a low enough average.

def hex_to_rgb(hex):
    hex = hex.lstrip('#')
    lv = len(hex)
    return tuple(int(hex[i:i+lv//3], 16) for i in range(0, lv, lv//3))

def average(value):
    rgb = hex_to_rgb(value)
    return (rgb[0] + rgb[1] + rgb[2]) / 3

without_brightest = {key:value for key, value in CSS$_COLORS.items() if average(value) <= 210}
# The condition becomes the opposite, <= 210 instead of > 210, because we are deciding what to include instead of what to delete.

print(without_brightest)

This will yield the new dictionary excluding the bright values, and it will leave the original matplotlib dictionary intact.

If, for some reason, you need to modify the original dictionary instead of creating a new one, you can use the method mentioned previously of making a second dictionary to iterate over. You can make a shallow copy with dict.copy, which would change your second for loop to

for key, value in CSS4_COLORS.copy().items():
    rgb = hex_to_rgb(value)
    rgb_average = (rgb[0] + rgb[1] + rgb[2]) / 3
    if rgb_average > 210:
        del CSS4_COLORS[key]

This would create a new dictionary to iterate over, and modify the original. You should probably only use this method if you need the original modified and cannot simply assign another dictionary to it. You have to make a new dictionary object either way, so the first variant is preferable.


来源: stackexchange

问:
Why does GitAhead give this error on fetch/pull?
I am using GitAhead on an existing repo, and trying to pull or fetch to get updates.

GitAhead is giving me this error:

Unable to fetch from 'origin' - config value 'autoupdate.enable' was not found

Git itself doesn't seem to have this config parameter .. so not sure what GitAhead is expecting.

Appreciate any pointers/solutions.

答:
I have been using GitAhead for a while, but mainly for viewing the merge graphs. I just tried using GitAhead to do a pull, and I ran into this problem as well.

I couldn't find any solutions online, but I found that GitAhead (version 2.62.2 on CentOS 7.8) does not understand:

```<code>ssh://hostname/path_to_repo
</code>```

I get the error in the original question.

However, the solution for me was to use the following URL when cloning from a remote repository:

git clone user_id@hostname:/path_to_repo
```

After creating another clone with this URL, I'm able to pull in GitAhead.

ContentLicense: CC BY-SA 4.0

Body:
I have been using GitAhead for a while, but mainly for viewing the merge graphs. I just tried using GitAhead to do a pull, and I ran into this problem as well.

I couldn't find any solutions online, but I found that GitAhead (version 2.62.2 on CentOS 7.8) does not understand:

ssh://hostname/path_to_repo

I get the error in the original question.

However, the solution for me was to use the following URL when cloning from a remote repository:

git clone user_id@hostname:/path_to_repo

After creating another clone with this URL, I'm able to pull in GitAhead.


问:
CORS error with the Access-Controll-Allow-Origin * - NodeJS and Angular
I'm doing a web app with Angular and when I connect the backend with the front it gives me a CORS error:
 Access to XMLHttpRequest at 'http://localhost:3700/api/save-project' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I know what the CORS is but I don't know why this error because in my app.js in the backend I have the code for blocking CORS

How can I fix this issue?

Code:

app.js
    'use strict'

```<code>var express = require('express');
var bodyParser = require('body-parser');

var app = express();

// cargar archivo Rutas
var routes = require('./routes/product');

// Middlewares
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json()); // Content-Type: image/jpg

// Configurar cabeceras y cors
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
    res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
    next();
});

// Rutas
app.use('/api', routes);

// exportar
module.exports = app;
</code>```

component in Angular:

```<code>import { Component, OnInit } from '@angular/core';
import { ProductService } from 'src/app/services/products.service';
import { Product } from 'src/app/models/product';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'crear',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css'],
  providers: [HttpClient, ProductService]
})
export class CreateComponent implements OnInit {
  public producto: Product;
  public product: any;

   constructor(
    //,
    //private http: HttpClient
    private _productService: ProductService
  ) {
    this.producto = new Product('','','','',2,2);
  }

  ngOnInit(): void {
  }

  onSubmit(form){
    this._productService.saveProduct(this.producto).subscribe(
      response => {
        if(response.producto){

          form.reset();

          this.product = this.producto._id;
        }else{
        alert("No se ha podido");
      };
      }
    )
  }

}
</code>```

Service:

```<code>import { Injectable } from "@angular/core";
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Product } from '../models/product';
import { Global } from './global.service';

@Injectable()
export class ProductService{
    public url: String;

    constructor(
        private _http: HttpClient
    ){
        this.url = Global.url;
    }

    saveProduct(product: Product): Observable<any>{
        var params = JSON.stringify(product);
        let headers =  new HttpHeaders().set('Content-Type', 'application/json');

        return this._http.post(this.url+'save-project', params, {headers: headers});
    }
}
</code>```

Thanks for all

答:
Install cors middleware in your backend project:

```<code>npm install cors --save
</code>```

Then, in app.js, import cors package and use it:

```<code>var cors = require('cors');

var app = express();

app.use(cors());
</code>```

It's important to apply the cors middleware BEFORE any route declaration.

More info about cors middleware: https://github.com/expressjs/cors#readme

More info about cors: https://developer.mozilla.org/es/docs/Web/HTTP/Access_control_CORS

Body:
I'm doing a web app with Angular and when I connect the backend with the front it gives me a CORS error:
 Access to XMLHttpRequest at 'http://localhost:3700/api/save-project' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I know what the CORS is but I don't know why this error because in my app.js in the backend I have the code for blocking CORS

How can I fix this issue?

Code:

app.js
    'use strict'

var express = require('express');
var bodyParser = require('body-parser');

var app = express();

// cargar archivo Rutas
var routes = require('./routes/product');

// Middlewares
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json()); // Content-Type: image/jpg

// Configurar cabeceras y cors
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Authorization, X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Request-Method');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
    res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
    next();
});

// Rutas
app.use('/api', routes);

// exportar
module.exports = app;

component in Angular:

import { Component, OnInit } from '@angular/core';
import { ProductService } from 'src/app/services/products.service';
import { Product } from 'src/app/models/product';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'crear',
  templateUrl: './create.component.html',
  styleUrls: ['./create.component.css'],
  providers: [HttpClient, ProductService]
})
export class CreateComponent implements OnInit {
  public producto: Product;
  public product: any;

   constructor(
    //,
    //private http: HttpClient
    private _productService: ProductService
  ) {
    this.producto = new Product('','','','',2,2);
  }

  ngOnInit(): void {
  }

  onSubmit(form){
    this._productService.saveProduct(this.producto).subscribe(
      response => {
        if(response.producto){

          form.reset();

          this.product = this.producto._id;
        }else{
        alert("No se ha podido");
      };
      }
    )
  }

}

Service:

import { Injectable } from "@angular/core";
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Product } from '../models/product';
import { Global } from './global.service';

@Injectable()
export class ProductService{
    public url: String;

    constructor(
        private _http: HttpClient
    ){
        this.url = Global.url;
    }

    saveProduct(product: Product): Observable<any>{
        var params = JSON.stringify(product);
        let headers =  new HttpHeaders().set('Content-Type', 'application/json');

        return this._http.post(this.url+'save-project', params, {headers: headers});
    }
}

Thanks for all

Body:
Install cors middleware in your backend project:

npm install cors --save

Then, in app.js, import cors package and use it:

var cors = require('cors');

var app = express();

app.use(cors());

It's important to apply the cors middleware BEFORE any route declaration.

More info about cors middleware: https://github.com/expressjs/cors#readme

More info about cors: https://developer.mozilla.org/es/docs/Web/HTTP/Access_control_CORS


答:
You can use cors (https://www.npmjs.com/package/cors) to handle cors settings. Please follow the usage from documentation.
If you do not want to enable cors origin and you need to get this working only for local development, you can try launching chrome with --disable-web-security mode.</p>

Title: CORS error with the Access-Controll-Allow-Origin * - NodeJS and Angular


问:
Execute some calls to one API twice per day at 12.00 AM and 23:00 PM with Java and vertx
I've been playing a bit with vertx.setTimer and vertx.setPeriodic but I didn't find a simple way in java to get execute one scheduled task(call to one API in concrete period ,for instance at 12.00 AM and 23.00 PM).
I've looked as well a blog about vertx and chime ( https://vertx.io/blog/time-scheduling-with-chime/)  but I am not sure it's got support or consistency for vertx version 3.9.0.
Any idea ?
Thank you in advance.

答:
Try java.util.Timer, example run everyday at 21:00:</p>

```<code>    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            vertx.runOnContext(event -> { System.out.println("timer in vert.x context!"); });
        }
    };

    Timer timer = new Timer();
    Calendar today = Calendar.getInstance();
    today.set(Calendar.HOUR_OF_DAY, 21);
    today.set(Calendar.MINUTE, 0);
    today.set(Calendar.SECOND, 0);

    timer.schedule(timerTask, today.getTime(), TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS));
</code>```

Body:
Try java.util.Timer, example run everyday at 21:00:

    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            vertx.runOnContext(event -> { System.out.println("timer in vert.x context!"); });
        }
    };

    Timer timer = new Timer();
    Calendar today = Calendar.getInstance();
    today.set(Calendar.HOUR_OF_DAY, 21);
    today.set(Calendar.MINUTE, 0);
    today.set(Calendar.SECOND, 0);

    timer.schedule(timerTask, today.getTime(), TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS));


问:
Why do we need boxing and unboxing in C#?
Why do we need boxing and unboxing in C#?

I know what boxing and unboxing is, but I can't comprehend the real use of it. Why and where should I use it?

```<code>short s = 25;

object objshort = s;  //Boxing

short anothershort = (short)objshort;  //Unboxing
</code>```

答:
Boxing is the conversion of a value to a reference type with the data at some offset in an object on the heap.

As for what boxing actually does. Here are some examples

Mono C++

```<code>void* mono_object_unbox (MonoObject *obj)
 {
MONO_EXTERNAL_ONLY_GC_UNSAFE (void*, mono_object_unbox_internal (obj));
 }

#define MONO_EXTERNAL_ONLY_GC_UNSAFE(t, expr) \
    t result;       \
    MONO_ENTER_GC_UNSAFE;   \
    result = expr;      \
    MONO_EXIT_GC_UNSAFE;    \
    return result;

static inline gpointer
mono_object_unbox_internal (MonoObject *obj)
{
    /* add assert for valuetypes? */
    g_assert (m_class_is_valuetype (mono_object_class (obj)));
    return mono_object_get_data (obj);
}

static inline gpointer
mono_object_get_data (MonoObject *o)
{
    return (guint8*)o + MONO_ABI_SIZEOF (MonoObject);
}

#define MONO_ABI_SIZEOF(type) (MONO_STRUCT_SIZE (type))
#define MONO_STRUCT_SIZE(struct) MONO_SIZEOF_ ## struct
#define MONO_SIZEOF_MonoObject (2 * MONO_SIZEOF_gpointer)

typedef struct {
    MonoVTable *vtable;
    MonoThreadsSync *synchronisation;
} MonoObject;
</code>```

Unboxing an object in Mono is a process of casting a pointer at an offset of 2 gpointers in the object (e.g. 16 bytes). A gpointer is a void*. This makes sense when looking at the definition of MonoObject as it's clearly just a header for the data.

C++

To box a value in C++ you could do something like:

```<code>#include <iostream>
#define Object void*

template<class T> Object box(T j){
  return new T(j);
}

template<class T> T unbox(Object j){
  T temp = *(T*)j;
  delete j;
  return temp;
}

int main() {
  int j=2;
  Object o = box(j);
  int k = unbox<int>(o);
  std::cout << k;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Why do we need boxing and unboxing in C#?

I know what boxing and unboxing is, but I can't comprehend the real use of it. Why and where should I use it?

short s = 25;

object objshort = s;  //Boxing

short anothershort = (short)objshort;  //Unboxing

Body:
Boxing is the conversion of a value to a reference type with the data at some offset in an object on the heap.

As for what boxing actually does. Here are some examples

Mono C++

void* mono_object_unbox (MonoObject *obj)
 {
MONO_EXTERNAL_ONLY_GC_UNSAFE (void*, mono_object_unbox_internal (obj));
 }

#define MONO_EXTERNAL_ONLY_GC_UNSAFE(t, expr) \
    t result;       \
    MONO_ENTER_GC_UNSAFE;   \
    result = expr;      \
    MONO_EXIT_GC_UNSAFE;    \
    return result;

static inline gpointer
mono_object_unbox_internal (MonoObject *obj)
{
    /* add assert for valuetypes? */
    g_assert (m_class_is_valuetype (mono_object_class (obj)));
    return mono_object_get_data (obj);
}

static inline gpointer
mono_object_get_data (MonoObject *o)
{
    return (guint8*)o + MONO_ABI_SIZEOF (MonoObject);
}

#define MONO_ABI_SIZEOF(type) (MONO_STRUCT_SIZE (type))
#define MONO_STRUCT_SIZE(struct) MONO_SIZEOF_ ## struct
#define MONO_SIZEOF_MonoObject (2 * MONO_SIZEOF_gpointer)

typedef struct {
    MonoVTable *vtable;
    MonoThreadsSync *synchronisation;
} MonoObject;

Unboxing an object in Mono is a process of casting a pointer at an offset of 2 gpointers in the object (e.g. 16 bytes). A gpointer is a void*. This makes sense when looking at the definition of MonoObject as it's clearly just a header for the data.

C++

To box a value in C++ you could do something like:

#include <iostream>
#define Object void*

template<class T> Object box(T j){
  return new T(j);
}

template<class T> T unbox(Object j){
  T temp = *(T*)j;
  delete j;
  return temp;
}

int main() {
  int j=2;
  Object o = box(j);
  int k = unbox<int>(o);
  std::cout << k;
}


问:
How to set credentials on AWS SDK on NET Core?
I'm new to AWS SDK and I'm trying to follow the AWS documentation, but gives little to none on what exactly I need to setup.

The official docs tell me to add this to the appsettings.json:

```<code>{
  "AWS": {
    "Profile": "local-test-profile",
    "Region": "us-west-2"
  }
}
</code>```

And then create the client:

```<code>var options = Configuration.GetAWSOptions();
IAmazonS3 client = options.CreateServiceClient<IAmazonS3>();
</code>```

This causes an exception to be thrown saying it cannot find the credentials. Where do I put the Api ID and Key? What is this profile?

Please, bear in mind I have no preferences on how to set this up. I'm just trying to follow the official documentation for .NET Core, and their only example doesn't work. The docs seem to imply I should have prior knowledge of many of their terms and settings or that I'm migrating an existing app and already have everything setup.

Can someone please point me to what is missing from this example just to make the API correctly connect to AWS?

答:
This helps to avoid getting credentials from environment using the appsettings for development purpose</p>

```<code>var awsOption = Configuration.GetAWSOptions();
    awsOption.Credentials = new BasicAWSCredentials(Configuration["AWS:AccessKey"], Configuration["AWS:SecretKey"]);
    services.AddDefaultAWSOptions(awsOption);
</code>```

Body:
I'm new to AWS SDK and I'm trying to follow the AWS documentation, but gives little to none on what exactly I need to setup.

The official docs tell me to add this to the appsettings.json:

{
  "AWS": {
    "Profile": "local-test-profile",
    "Region": "us-west-2"
  }
}

And then create the client:

var options = Configuration.GetAWSOptions();
IAmazonS3 client = options.CreateServiceClient<IAmazonS3>();

This causes an exception to be thrown saying it cannot find the credentials. Where do I put the Api ID and Key? What is this profile?

Please, bear in mind I have no preferences on how to set this up. I'm just trying to follow the official documentation for .NET Core, and their only example doesn't work. The docs seem to imply I should have prior knowledge of many of their terms and settings or that I'm migrating an existing app and already have everything setup.

Can someone please point me to what is missing from this example just to make the API correctly connect to AWS?

Body:
This helps to avoid getting credentials from environment using the appsettings for development purpose

var awsOption = Configuration.GetAWSOptions();
    awsOption.Credentials = new BasicAWSCredentials(Configuration["AWS:AccessKey"], Configuration["AWS:SecretKey"]);
    services.AddDefaultAWSOptions(awsOption);


问:
In Opera the border on input button disappears when the text field becomes active, how can i prevent that?
I'm trying to style the submit button on the wordpress search widget, but Opera is giving me trouble.

I've set a 1px solid border on the button, and it appears fine until the text input is activated, then the border on the button seems to disappear (or becomes black, i can't tell).

This does not happen in firefox where the button appears the same even if the text field is activated.

This is the css i have now:

```<code>li.widget_search #searchform #searchsubmit
{
    height: 24px !important;
    border-color: #ff9900;
    border-width:1px;
    border-style: solid;
    background-color: #201300;
    font-family: Verdana,Geneva,Arial,Helvetica,sans-serif;
    font-size: 11px;
    letter-spacing: 1px;
    color: #FFB100;
    padding: 0px 3px 0px 3px;
    overflow: hidden;

}

li.widget_search #searchform #searchsubmit:active
{
    border: 0px;
}
</code>```

答:
This is an Opera issue. It always adds a black border if a border is specified on button focus, regardless of the settings of that border (color or style at least). All other browsers display a nice blue border here, inheriting all the settings from the normal button CSS rule.

You can prevent this on your own button by removing the border from the button:focus style.

Try...

```<code>a.button:active { border:0px; }
</code>```

Body:
I'm trying to style the submit button on the wordpress search widget, but Opera is giving me trouble.

I've set a 1px solid border on the button, and it appears fine until the text input is activated, then the border on the button seems to disappear (or becomes black, i can't tell).

This does not happen in firefox where the button appears the same even if the text field is activated.

This is the css i have now:

li.widget_search #searchform #searchsubmit
{
    height: 24px !important;
    border-color: #ff9900;
    border-width:1px;
    border-style: solid;
    background-color: #201300;
    font-family: Verdana,Geneva,Arial,Helvetica,sans-serif;
    font-size: 11px;
    letter-spacing: 1px;
    color: #FFB100;
    padding: 0px 3px 0px 3px;
    overflow: hidden;

}

li.widget_search #searchform #searchsubmit:active
{
    border: 0px;
}

Body:
This is an Opera issue. It always adds a black border if a border is specified on button focus, regardless of the settings of that border (color or style at least). All other browsers display a nice blue border here, inheriting all the settings from the normal button CSS rule.

You can prevent this on your own button by removing the border from the button:focus style.

Try...

a.button:active { border:0px; }


问:
Azure Application Gateway : Backend server certificate expired. Please upload a valid certificate
We have an Azure Application Gateway V2 setup with WAF feature enabled. We ran into trouble when suddenly, the health of all our backend pools (3 in our case) started showing unhealthy and the error was being shown when we checked backend health:

Backend server certificate expired. Please upload a valid certificate.

Now, the same certificate is applied on application gateway and on the backend pool servers/VMs. We had to switch to non-SSL port for our backend servers to make the problem go away.

I am not able to pinpoint the problem as if any certificate is expired when applied to backend pool VM should give the same error once applied to the application gateway itself. Can someone help to identify the actual root cause of the problem and why it is showing error only at the backend pool level?

Very important thing is that the certificates being shown in browser when the backend pool URL is opened is showing still more than 2 months before it expires.

Thanks.

答:
I'm not sure what the underlying issue is with Application Gateway at the moment, but a restart of the webapp worked for one of my apps, however an other one stayed unhealthy.  I could successfully connect to the webapp from the local server however, just not through the app gateway.

What worked for me in the end was removing the server from the backend pool and re-adding it.  Once it was added back, the Backend health changed to 'Healthy'.


问:
How can I check if a string contains repeated characters or not?
I'm wondering what is the best way to determine if a string contains repeated characters even when they are not adjacent together? I have tried changing the string into an array and then using nested for loops to compare each item in the array with the other one but for some reason it doesn't work.</p>

```<code>function hasRpeatedCharacters(str) {

    let array = [];
    for (let i = 0; i < str.length; i++) {
        array.push(str[i]);

    }

    for (let j = 0; j < array.length; j++) {

        for (let k = j + 1; k < array.length; k++) {

            if (array[j] != array[k]) {
                return true;
            } else {
                return false;
            }
        }

    }

}

hasRepeatedCharacters("abadan");
</code>```

答:
Create a Set from the string, and check if the Set's size is less than the string's length. A Set can only hold unique values, so if there are repeated characters the Set's size would be less than the string's length.

const hasRepeatedCharacters = str => new Set(str).size < str.length;

console.log(hasRepeatedCharacters("abadan"));
console.log(hasRepeatedCharacters("abc"));```

Body:
I'm wondering what is the best way to determine if a string contains repeated characters even when they are not adjacent together? I have tried changing the string into an array and then using nested for loops to compare each item in the array with the other one but for some reason it doesn't work.

function hasRpeatedCharacters(str) {

    let array = [];
    for (let i = 0; i < str.length; i++) {
        array.push(str[i]);

    }

    for (let j = 0; j < array.length; j++) {

        for (let k = j + 1; k < array.length; k++) {

            if (array[j] != array[k]) {
                return true;
            } else {
                return false;
            }
        }

    }

}

hasRepeatedCharacters("abadan");


问:
How can I deserialize using JSON.NET and preserve the parent object
I have some JSON like:

```<code>{
  "companyName": "Software Inc.",
  "employees": [
    {
      "employeeName": "Sally"
    },
    {
      "employeeName": "Jimmy"
    }
  ]
}
</code>```

I want to deserialize it into:

```<code>public class Company
{
  public string companyName { get; set; }
  public IList<Employee> employees { get; set; }
}

public class Employee
{
  public string employeeName { get; set; }
  public Company employer { get; set; }
}
</code>```

How can I have JSON.NET set the "employer" reference? I tried using a CustomCreationConverter, but the public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) method doesn't contain a any reference to the current parent object.

答:
Json.net solved this with PreserveReferencesHandling. Simply set PreserveReferencesHandling = PreserveReferencesHandling.Objects and Newtonsoft does it all for you.

https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_PreserveReferencesHandling.htm

Regards,
Fabianus

Body:
I have some JSON like:

{
  "companyName": "Software Inc.",
  "employees": [
    {
      "employeeName": "Sally"
    },
    {
      "employeeName": "Jimmy"
    }
  ]
}

I want to deserialize it into:

public class Company
{
  public string companyName { get; set; }
  public IList<Employee> employees { get; set; }
}

public class Employee
{
  public string employeeName { get; set; }
  public Company employer { get; set; }
}

How can I have JSON.NET set the "employer" reference? I tried using a CustomCreationConverter, but the public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) method doesn't contain a any reference to the current parent object.


问:
How to change required attribute in @RequestParam?
I have controller end point like this:

```<code>    @GetMapping
    public List<QuestionnaireModel> getQuestionnaireList (
        @PathVariable String userId,
        @RequestParam(required = false, value = "userId") Long orderId
    ){
</code>```

Now, how can I change my required attribute in @RequestParam depending on value that will be in @PathVariable?

For example :

```<code>if(userId==5){
    //My @RequestParam required must be true so I must provide `orderId`
}
</code>```

答:
This sounds like a bad API design.

```<code>/api/myUser/
/api/anotherUser?param=value
</code>```

For myUser the param is not required, but for anotherUser it must be present.

You can try to use a filter to address this requirement but I would suggest you to perhaps consider again the design for your API.

How will you decide for which user the param is valid and for which it is not ?
That would require you to do some validation on the userId. If this is just a dev project ,it might be ok. But if this some serious application, maybe you should go back to the drawing board.

Body:
I have controller end point like this:

    @GetMapping
    public List<QuestionnaireModel> getQuestionnaireList (
        @PathVariable String userId,
        @RequestParam(required = false, value = "userId") Long orderId
    ){

Now, how can I change my required attribute in @RequestParam depending on value that will be in @PathVariable?

For example :

if(userId==5){
    //My @RequestParam required must be true so I must provide `orderId`
}

Body:
This sounds like a bad API design.

/api/myUser/
/api/anotherUser?param=value

For myUser the param is not required, but for anotherUser it must be present.

You can try to use a filter to address this requirement but I would suggest you to perhaps consider again the design for your API.

How will you decide for which user the param is valid and for which it is not ?
That would require you to do some validation on the userId. If this is just a dev project ,it might be ok. But if this some serious application, maybe you should go back to the drawing board.


问:
How to input data in classes in python, if number of students I want to input is not known
I want to input data in a class. I don't know  the number of students I want to input. I can only write p1.name="John" p2.name="Jack" etc but if I want to input more students I have to write p3,p4,p5...

```<code>class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person
p1.name="John"
p1.age=15
print(p1.name)
print(p1.age)
</code>```

Is there a method to work like with arrays for example p[0].name="John"....... p[123].name="Jack" or something like that... Sorry for my bad english

答:
You probably meant

```<code>p1 = Person('John', 15)
p2 = Person('Jack', 42)
</code>```

If you needed an arbitrary number of objects, you can store them in a data structure like

```<code>people = [Person('John', 15), Person('Jack', 42)]
for person in people:
  print(person.name)
</code>```

You can read data into that array as well-

```<code>people = []
with open('people.txt') as f:
  for line in f:
    name, age = line.split()
    people.append(Person(name, age))
</code>```

But my advice would be to find a more introductory tutorial to follow, you're going to struggle :)

Body:
I want to input data in a class. I don't know  the number of students I want to input. I can only write p1.name="John" p2.name="Jack" etc but if I want to input more students I have to write p3,p4,p5...

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person
p1.name="John"
p1.age=15
print(p1.name)
print(p1.age)

Is there a method to work like with arrays for example p[0].name="John"....... p[123].name="Jack" or something like that... Sorry for my bad english

Body:
You probably meant

p1 = Person('John', 15)
p2 = Person('Jack', 42)

If you needed an arbitrary number of objects, you can store them in a data structure like

people = [Person('John', 15), Person('Jack', 42)]
for person in people:
  print(person.name)

You can read data into that array as well-

people = []
with open('people.txt') as f:
  for line in f:
    name, age = line.split()
    people.append(Person(name, age))

But my advice would be to find a more introductory tutorial to follow, you're going to struggle :)


问:
JavaScript removeChild input from the dom
I'm trying to delete the form input posted onto the DOM, but the removeChild code isn't functioning, When inspecting the console I will be given an error which is: materialize.min.js:6 Uncaught TypeError: Cannot read property 'M_Modal' of null at HTMLBodyElement.value (materialize.min.js:6)

// ----------------Models Materialize Framework----------------
document.addEventListener('DOMContentLoaded', () => {
    var elems = document.querySelectorAll('.modal');
    var instances = M.Modal.init(elems);
  });

//Delete Exercises
const delExerciseBtn = document.querySelector('.del-exercise-btn');

delExerciseBtn.addEventListener('click', (e) => {
if(e.target.className == 'delete'){
  const h6 = e.target.parentElement;
  h6.removeChild(e.target);
}
});

// Add User's To the Dom.
const addExerciseDom = document.querySelector('.exercise-dom');
const exerciseForm = document.querySelector('.exercises-form');

exerciseForm.addEventListener('submit', (e) => {
e.preventDefault();

  // Get Input Value
  const value = exerciseForm.querySelector('input[type="text"]').value;

  // Create Elements
  const h6 = document.createElement('h6');

  // Add Content
  h6.textContent = value;

  // Append To Dom
  addExerciseDom.appendChild(h6);

});```

答:
For Multiple Values of h6
Best to add id with each new h6
Check on weight and exercise

// Materialize Initialization Of Autocomplete, Exercise.
document.addEventListener('DOMContentLoaded', () => {
  var elems = document.querySelectorAll('.autocomplete');
  var instances = M.Autocomplete.init(elems,{
    data: {
      "Lat Pull Down": null,
      "Lat  Down": null,
    },
    limit:2,
    minLength:1,
  });
});

// Materialize Initialization Of Box Select, Sets and Reps.
document.addEventListener('DOMContentLoaded', () => {
  var elems = document.querySelectorAll('select');
  var instances = M.FormSelect.init(elems);
});

// Materialize Initialization Of Weights CharacterCount
document.addEventListener('DOMContentLoaded', () => {
  var textNeedCount = document.querySelectorAll('.weightcountercount');
  M.CharacterCounter.init(textNeedCount);
});
//need to put restrition on the number typed into the box without it submitting

// ----------------Models Materialize Framework----------------
document.addEventListener('DOMContentLoaded', function() {
  var elems = document.querySelectorAll('.modal');
  var instances = M.Modal.init(elems);
});

// ------------ Add Form's Inputs Onto The HomePage----------------

//-------------Exercises------------
// Delete Exercises From The Dom
const delExerciseBtn = document.querySelector('.del-exercise-btn');

delExerciseBtn.addEventListener('click', (e) => {
  // Remove Form Input
  const h6_e = document.getElementById('h6_exercise');
   h6_e.remove();
   // Remove Disable Btn
   disabledExersiceBtn.removeAttribute('disabled');
});

// Add User's Exercises To The Dom.
const addExerciseDom = document.querySelector('.exercise-dom');
const exerciseForm = document.querySelector('.exercises-form');
const disabledExersiceBtn = document.querySelector('.disabled-exersicebtn');

exerciseForm.addEventListener('submit', (e) => {
e.preventDefault();

  // Get Input Value
  const value = exerciseForm.querySelector('input[type="text"]').value;

  // Create Elements
  // const h6 = document.createElement('h6');

  //for exercise
  const h6_exercise = document.createElement('h6');

  // Add Content
  h6_exercise.textContent = value;
  //adding id
  h6_exercise.setAttribute("id", "h6_exercise");
  // Append To Dom
  addExerciseDom.appendChild(h6_exercise);

  //Disable Btn
  disabledExersiceBtn.setAttribute('disabled', 'disabled');

});

//---------------------Weight----------------------
// Delete Exercises From The Dom
const delWeightBtn = document.querySelector('.del-weight-btn');

delWeightBtn.addEventListener('click', (e) => {
  // Remove Form Input
  let h6_r = document.getElementById('h6_weight');
   h6_r.remove();
});

// Add User's Weight To The Dom.
const addWeightDom = document.querySelector('.weight-dom');
const weightForm = document.querySelector('.weight-form');

weightForm.addEventListener('submit', (e) => {
e.preventDefault();
 if(document.getElementById('h6_weight'))
  {
  let h6_r = document.getElementById('h6_weight');

  h6_r.remove();
 }
   // Get Input Value
   const value = weightForm.querySelector('input[type="number"]').value;
   const value1 = weightForm.querySelector('input[type="text"]').value;
   //console.log(value, value1);

   // Create Elements
   const h6_weight = document.createElement('h6');

  h6_weight.setAttribute('id','h6_weight')
   //h6.classList.add("center");// not working

   // Add Content
   h6_weight.textContent = value + " " + value1;

   // Append To Dom
   addWeightDom.appendChild(h6_weight);

  });

// ------------------Add Exercises Colum----------------------
//const addMoreBtn = document.getElementById("addmorebtn");
////const addColums = document.getElementById("addcolumns");

//addMoreBtn.addEventListener('click', (e) => {
   // e.preventDefault();

   // const text =
   // `

   //

   //

   //

   //

`

    //const position = "beforeend";
    //addColums.insertAdjacentHTML(position, text);
//});```

Body:
For Multiple Values of h6
Best to add id with each new h6
Check on weight and exercise

// Materialize Initialization Of Autocomplete, Exercise.
document.addEventListener('DOMContentLoaded', () => {
  var elems = document.querySelectorAll('.autocomplete');
  var instances = M.Autocomplete.init(elems,{
    data: {
      "Lat Pull Down": null,
      "Lat  Down": null,
    },
    limit:2,
    minLength:1,
  });
});

// Materialize Initialization Of Box Select, Sets and Reps.
document.addEventListener('DOMContentLoaded', () => {
  var elems = document.querySelectorAll('select');
  var instances = M.FormSelect.init(elems);
});

// Materialize Initialization Of Weights CharacterCount
document.addEventListener('DOMContentLoaded', () => {
  var textNeedCount = document.querySelectorAll('.weightcountercount');
  M.CharacterCounter.init(textNeedCount);
});
//need to put restrition on the number typed into the box without it submitting

// ----------------Models Materialize Framework----------------
document.addEventListener('DOMContentLoaded', function() {
  var elems = document.querySelectorAll('.modal');
  var instances = M.Modal.init(elems);
});

// ------------ Add Form's Inputs Onto The HomePage----------------

//-------------Exercises------------
// Delete Exercises From The Dom
const delExerciseBtn = document.querySelector('.del-exercise-btn');

delExerciseBtn.addEventListener('click', (e) => {
  // Remove Form Input
  const h6_e = document.getElementById('h6_exercise');
   h6_e.remove();
   // Remove Disable Btn
   disabledExersiceBtn.removeAttribute('disabled');
});

// Add User's Exercises To The Dom.
const addExerciseDom = document.querySelector('.exercise-dom');
const exerciseForm = document.querySelector('.exercises-form');
const disabledExersiceBtn = document.querySelector('.disabled-exersicebtn');

exerciseForm.addEventListener('submit', (e) => {
e.preventDefault();

  // Get Input Value
  const value = exerciseForm.querySelector('input[type="text"]').value;

  // Create Elements
  // const h6 = document.createElement('h6');

  //for exercise
  const h6_exercise = document.createElement('h6');

  // Add Content
  h6_exercise.textContent = value;
  //adding id
  h6_exercise.setAttribute("id", "h6_exercise");
  // Append To Dom
  addExerciseDom.appendChild(h6_exercise);

  //Disable Btn
  disabledExersiceBtn.setAttribute('disabled', 'disabled');

});

//---------------------Weight----------------------
// Delete Exercises From The Dom
const delWeightBtn = document.querySelector('.del-weight-btn');

delWeightBtn.addEventListener('click', (e) => {
  // Remove Form Input
  let h6_r = document.getElementById('h6_weight');
   h6_r.remove();
});

// Add User's Weight To The Dom.
const addWeightDom = document.querySelector('.weight-dom');
const weightForm = document.querySelector('.weight-form');

weightForm.addEventListener('submit', (e) => {
e.preventDefault();
 if(document.getElementById('h6_weight'))
  {
  let h6_r = document.getElementById('h6_weight');

  h6_r.remove();
 }
   // Get Input Value
   const value = weightForm.querySelector('input[type="number"]').value;
   const value1 = weightForm.querySelector('input[type="text"]').value;
   //console.log(value, value1);

   // Create Elements
   const h6_weight = document.createElement('h6');

  h6_weight.setAttribute('id','h6_weight')
   //h6.classList.add("center");// not working

   // Add Content
   h6_weight.textContent = value + " " + value1;

   // Append To Dom
   addWeightDom.appendChild(h6_weight);

  });

// ------------------Add Exercises Colum----------------------
//const addMoreBtn = document.getElementById("addmorebtn");
////const addColums = document.getElementById("addcolumns");

//addMoreBtn.addEventListener('click', (e) => {
   // e.preventDefault();

   // const text =
   // `<div class="col s4 height"></div>
   // <div class="col s2 height "></div>
   // <div class="col s2 height"></div>
   // <div class="col s2 height"></div>
   // <div class="col s2 height"></div>`

    //const position = "beforeend";
    //addColums.insertAdjacentHTML(position, text);
//});


问:
Import from different files node js
I trying to use functions from file 1 within file 2, when i run directly from File2.js works well, but when i try to run from File1, i got:
UnhandledPromiseRejectionWarning: TypeError: func1 is not a function

File 1:

```<code>const { func3 } = require("./File2.js")

function func1();
function func2();

func3(); //ok!

module.exports = {
    func1,
    func2
};
</code>```

File 2:

```<code>const { func1, func2 } = require("./File1.js")

function func3() {
  func1() //error
  func2() //error
}
module.exports = {
    func3,
};
</code>```

When i call node file 2, i can call func 1, func2 without problems, works well;

But when i run File 1 and call file2(), i got undefined to func1 and func2 within File 1

UnhandledPromiseRejectionWarning: TypeError: func1 is not a function

Anyone know how to solve it? I've tried change how to require, also remove avoid duplcation, but still didnt found a solution

答:
Avoid Circular Dependencies

This is the main reason it is best practice to strictly avoid circular dependencies in your code. They're almost never a good idea and the behavior you're seeking can be achieved much cleaner through other means.

To understand the issue, you should know that when you require a file, execution of the current file is paused while that new file is executed. This means when the interpreter hits this line:

```<code>const { func3 } = require("./File2.js")
</code>```

It pauses File1.js (before its module.exports has been assigned!) and starts executing File2.js immediately. Now, the first line of File2.js is a directive to execute File1.js, which we just came from. The interpreter recognizes that File1 is already mid-execution, so it simply returns the current value of module.exports - an empty object. Thus, its properties func1 and func2 are undefined at that time, and they are never re-assigned.

Export a Wrapper Function

Circular dependencies are pretty much always unnecessary. If you encounter a situation you think could be solved with a circular dependency, you should reframe your thinking and make the relationship strictly one-way.

To put this very simply: Your File2 needs func1 and func2 from File1. That doesn't mean File2 depends on File1. You can simply pass those two functions as arguments to a function exported from File2, and the need for circular dependencies vanishes.

Here's a sample:

File 1:

```<code>function func1();
function func2();

const { func3 } = require("./File2.js")(func1, func2);

func3(); //ok!
</code>```

File 2:

```<code>module.exports = function(func1, func2) {
  return {
    func3: function() {
      func1() //ok!
      func2() //ok!
    }
  }
};
</code>```

Title: Import from different files node js

Body:
I trying to use functions from file 1 within file 2, when i run directly from File2.js works well, but when i try to run from File1, i got:
UnhandledPromiseRejectionWarning: TypeError: func1 is not a function

File 1:

const { func3 } = require("./File2.js")

function func1();
function func2();

func3(); //ok!

module.exports = {
    func1,
    func2
};

File 2:

const { func1, func2 } = require("./File1.js")

function func3() {
  func1() //error
  func2() //error
}
module.exports = {
    func3,
};

When i call node file 2, i can call func 1, func2 without problems, works well;

But when i run File 1 and call file2(), i got undefined to func1 and func2 within File 1

UnhandledPromiseRejectionWarning: TypeError: func1 is not a function

Anyone know how to solve it? I've tried change how to require, also remove avoid duplcation, but still didnt found a solution

Body:
Avoid Circular Dependencies

This is the main reason it is best practice to strictly avoid circular dependencies in your code. They're almost never a good idea and the behavior you're seeking can be achieved much cleaner through other means.

To understand the issue, you should know that when you require a file, execution of the current file is paused while that new file is executed. This means when the interpreter hits this line:

const { func3 } = require("./File2.js")

It pauses File1.js (before its module.exports has been assigned!) and starts executing File2.js immediately. Now, the first line of File2.js is a directive to execute File1.js, which we just came from. The interpreter recognizes that File1 is already mid-execution, so it simply returns the current value of module.exports - an empty object. Thus, its properties func1 and func2 are undefined at that time, and they are never re-assigned.

Export a Wrapper Function

Circular dependencies are pretty much always unnecessary. If you encounter a situation you think could be solved with a circular dependency, you should reframe your thinking and make the relationship strictly one-way.

To put this very simply: Your File2 needs func1 and func2 from File1. That doesn't mean File2 depends on File1. You can simply pass those two functions as arguments to a function exported from File2, and the need for circular dependencies vanishes.

Here's a sample:

File 1:

function func1();
function func2();

const { func3 } = require("./File2.js")(func1, func2);

func3(); //ok!

File 2:

module.exports = function(func1, func2) {
  return {
    func3: function() {
      func1() //ok!
      func2() //ok!
    }
  }
};


答:
Sounds like you need a list.

A list is a data structure that you can use for zero or more elements, and you can access each element by iteration or by indexing the list.

You can do something like this:

```<code>persons = [
    Person("John", 15),
    Person("Adele", 16),
    ...
]
</code>```

and then you can access each person by an index: persons[0] will give you Jonh, and persons[1] will give Adele.

Title: How to input data in classes in python, if number of students I want to input is not known

Body:
Sounds like you need a list.

A list is a data structure that you can use for zero or more elements, and you can access each element by iteration or by indexing the list.

You can do something like this:

persons = [
    Person("John", 15),
    Person("Adele", 16),
    ...
]

and then you can access each person by an index: persons[0] will give you Jonh, and persons[1] will give Adele.


问:
How to trigger TweenMax Draggable event
I've a draggable bar, which can be drag horizontally. What i'm trying to do is, on page scroll Is it possible to trigger draggable event to drag?

I've provide the sample code below.

```<code><div class="bar">
  <div id="handler"></div>
</div>
</code>```

This is the initialisation.

```<code>Draggable.create("#handler",{
  type:"x",
  bounds: $('.bar')
});
</code>```

Is it possible to do like this,

```<code>$(window).scroll(function() {
  //move #handler horizontally
});
</code>```

Please check the codepen link.

答:
ZachSaucier (GreenSock member) helped me on this case.

In order to achieve this, you should upgrade to GSAP 3 and use the ScrollTrigger plugin.

```<code>const distObj = { x: 0, maxY: 0 };
let tween;
let ST;

function update() {
  // Update values as needed
  distObj.x = innerWidth - gsap.getProperty("#handler", "width");
  distObj.maxY = ScrollTrigger.maxScroll(window);

  // Kill off old things but keep the old progress
  let progress = 0;
  if(tween) {
    progress = tween.progress();
    ST.kill();
    drag.applyBounds({minX: 0, maxX: innerWidth});
  }

  // Create or recreate the tween and scroll trigger
  tween = gsap.fromTo("#handler", {x: 0}, {
    x: distObj.x,
    ease: "none",
    paused: true,
    overwrite: "auto"
  }).progress(progress);

  ST = ScrollTrigger.create({
    animation: tween,
    trigger: document.body,
    start: "top top",
    end: "bottom bottom",
    scrub: true
  });
}

update();
ScrollTrigger.addEventListener("refreshInit", update);

var drag = Draggable.create("#handler", {
  trigger: "#handler",
  type: "x",
  bounds: {minX: 0, maxX: innerWidth},
  onDrag: function() {
    const progress = this.x / distObj.x;
    tween.progress(progress);
    ST.scroll(progress * distObj.maxY);
  }
})[0];
</code>```

Here is the updated CodePen link. I hope this answer help someone. All credit goes to ZachSaucier.

Title: How to trigger TweenMax Draggable event

Body:
I've a draggable bar, which can be drag horizontally. What i'm trying to do is, on page scroll Is it possible to trigger draggable event to drag?

I've provide the sample code below.

This is the initialisation.

Draggable.create("#handler",{
  type:"x",
  bounds: $('.bar')
});

Is it possible to do like this,

$(window).scroll(function() {
  //move #handler horizontally
});

Please check the codepen link.

Body:
ZachSaucier (GreenSock member) helped me on this case.

In order to achieve this, you should upgrade to GSAP 3 and use the ScrollTrigger plugin.

const distObj = { x: 0, maxY: 0 };
let tween;
let ST;

function update() {
  // Update values as needed
  distObj.x = innerWidth - gsap.getProperty("#handler", "width");
  distObj.maxY = ScrollTrigger.maxScroll(window);

  // Kill off old things but keep the old progress
  let progress = 0;
  if(tween) {
    progress = tween.progress();
    ST.kill();
    drag.applyBounds({minX: 0, maxX: innerWidth});
  }

  // Create or recreate the tween and scroll trigger
  tween = gsap.fromTo("#handler", {x: 0}, {
    x: distObj.x,
    ease: "none",
    paused: true,
    overwrite: "auto"
  }).progress(progress);

  ST = ScrollTrigger.create({
    animation: tween,
    trigger: document.body,
    start: "top top",
    end: "bottom bottom",
    scrub: true
  });
}

update();
ScrollTrigger.addEventListener("refreshInit", update);

var drag = Draggable.create("#handler", {
  trigger: "#handler",
  type: "x",
  bounds: {minX: 0, maxX: innerWidth},
  onDrag: function() {
    const progress = this.x / distObj.x;
    tween.progress(progress);
    ST.scroll(progress * distObj.maxY);
  }
})[0];

Here is the updated CodePen link. I hope this answer help someone. All credit goes to ZachSaucier.


问:
React - How do you call a function from inside another function
Suppose I had this layout below:

```<code>class Navigation extends React.Component {
 primaryFun() { console.log('funn') }

 secondaryFun() {
  this.primaryFun();
 }
}
</code>```

I'd of expected this to then call primary but instead I get an undefined, Ok.

So I thought I'd add a constructor to bind the function to this:

```<code>constructor(props) {
 super(props)
 this.primaryFun = this.primaryFun.bind(this);
}
</code>```

but primary fun is still undefined.

In my real project I'm calling these on a mouseOut event.

Feels like the above should work and tbh the documentation for React is all over the shot so couldn't find much here.

答:
You must bind() both two functions.
You should that:</p>

```<code>class Navigation extends React.Component {

    constructor(props) {
        super(props)
        this.primaryFun = this.primaryFun.bind(this);
        this.secondaryFun = this.secondaryFun.bind(this);
    }

    primaryFun() {
        console.log('funn')
    }

    secondaryFun() {
        this.primaryFun();
    }
}
</code>```

Body:
Suppose I had this layout below:

class Navigation extends React.Component {
 primaryFun() { console.log('funn') }

 secondaryFun() {
  this.primaryFun();
 }
}

I'd of expected this to then call primary but instead I get an undefined, Ok.

So I thought I'd add a constructor to bind the function to this:

constructor(props) {
 super(props)
 this.primaryFun = this.primaryFun.bind(this);
}

but primary fun is still undefined.

In my real project I'm calling these on a mouseOut event.

Feels like the above should work and tbh the documentation for React is all over the shot so couldn't find much here.

Body:
You must bind() both two functions.
You should that:

class Navigation extends React.Component {

    constructor(props) {
        super(props)
        this.primaryFun = this.primaryFun.bind(this);
        this.secondaryFun = this.secondaryFun.bind(this);
    }

    primaryFun() {
        console.log('funn')
    }

    secondaryFun() {
        this.primaryFun();
    }
}


问:
Image to Text - Pytesseract struggles with digits on windows
I'm trying to preprocess frames of a game in real-time for a ML project.
I want to extract numbers from the frame, so I chose Pytesseract, since it looked quite good with text.
Though, no matter how clear I make the text, it won't read it correctly.
My code looks like this:

section = process_screen(screen_image)[1]
pixels = rgb_to_bw(section) #Makes the image grayscale
pixels[pixels < 200] = 0 #Makes all non-white pixels black
tess.image_to_string(pixels)

=> 'ye ml)'
```

At best it outputs "ye ml)" when I don't specify I want digits, and when I do, it outputs nothing at all.

The non-processed game image looks like so:

The "pixels" image looks like so :

Thanks to Alex Alex, I inverted the image, and got this

And got "2710", which is better, but still not perfect.

答: You must invert the image before recognition.</p>

Body:
I'm trying to preprocess frames of a game in real-time for a ML project.
I want to extract numbers from the frame, so I chose Pytesseract, since it looked quite good with text.
Though, no matter how clear I make the text, it won't read it correctly.
My code looks like this:

section = process_screen(screen_image)[1]
pixels = rgb_to_bw(section) #Makes the image grayscale
pixels[pixels < 200] = 0 #Makes all non-white pixels black
tess.image_to_string(pixels)

=> 'ye ml)'

At best it outputs "ye ml)" when I don't specify I want digits, and when I do, it outputs nothing at all.

The non-processed game image looks like so:

The "pixels" image looks like so :

Thanks to Alex Alex, I inverted the image, and got this

And got "2710", which is better, but still not perfect.


问:
Remove repetition from if-else statement
I have written an if...else statement which uses an array myArr and a string myStr as follows:

```<code>If myArr.Length > 0 AndAlso myArr(0) = "-1" Then
  'Do stuff 1
ElseIf myStr= "xyz" Then
  'Do stuff 2
ElseIf myArr.Length > 0 Then
  'Do Stuff 3
Else
  'Do Nothing
End If
</code>```

It works exactly as I need. But It looks really confusing, mostly because the array length is checked twice. There must be a clearer way to write it, but I can't think of one.

Just to clarify.... the order that each statement is executed is crucial. i.e. Stuff 1 has priority over stuff 2, which has priority over stuff 3.

答:
```<code>If myArr.Length > 0 Then
  If myArr(0) = "-1" Then
    ' Stuff 1
  Else
    ' Stuff 3
  End If
ElseIf myStr = "xyz"
' Stuff 2
End If
</code>```

<p>... no further else needed</p>

Body:
I have written an if...else statement which uses an array myArr and a string myStr as follows:

If myArr.Length > 0 AndAlso myArr(0) = "-1" Then
  'Do stuff 1
ElseIf myStr= "xyz" Then
  'Do stuff 2
ElseIf myArr.Length > 0 Then
  'Do Stuff 3
Else
  'Do Nothing
End If

It works exactly as I need. But It looks really confusing, mostly because the array length is checked twice. There must be a clearer way to write it, but I can't think of one.

Just to clarify.... the order that each statement is executed is crucial. i.e. Stuff 1 has priority over stuff 2, which has priority over stuff 3.

Body:
If myArr.Length > 0 Then
  If myArr(0) = "-1" Then
    ' Stuff 1
  Else
    ' Stuff 3
  End If
ElseIf myStr = "xyz"
' Stuff 2
End If

... no further else needed


问:
Groupby Row element and Tranpose a Panda Dataframe
In Python, I have the following Pandas dataframe:

```<code>     Factor     Value
0    a          1.2
1    b          3.4
2    b          4.5
3    b          5.6
4    c          1.3
5    d          4.6
</code>```

I would like to organize this where:

unique row identifiers (the factor col) become columns

Their respective values remain under the created columns

The factor values are not in an organized.

Target:

```<code>     A     B    C     D
0    1.2   3.4  1.3   4.6
1          4.5
2          5.6
3
4
5
</code>```

答:
Use, set_index and unstack with groupby:

```<code>df.set_index(['Factor', df.groupby('Factor').cumcount()])['Value'].unstack(0)
</code>```

Output:

```<code>Factor    a    b    c    d
0       1.2  3.4  1.3  4.6
1       NaN  4.5  NaN  NaN
2       NaN  5.6  NaN  NaN
</code>```

Body:
In Python, I have the following Pandas dataframe:

     Factor     Value
0    a          1.2
1    b          3.4
2    b          4.5
3    b          5.6
4    c          1.3
5    d          4.6

I would like to organize this where:

unique row identifiers (the factor col) become columns

Their respective values remain under the created columns

The factor values are not in an organized.

Target:

     A     B    C     D
0    1.2   3.4  1.3   4.6
1          4.5
2          5.6
3
4
5

Body:
Use, set_index and unstack with groupby:

df.set_index(['Factor', df.groupby('Factor').cumcount()])['Value'].unstack(0)

Output:

Factor    a    b    c    d
0       1.2  3.4  1.3  4.6
1       NaN  4.5  NaN  NaN
2       NaN  5.6  NaN  NaN


问:
Extract row value where the 2 columns are not equal in a data frame in R
Is there a way to extract values in the dataframe when the columns values are not equal

```<code>df
ColA  Colb  ColC
12     12    fs
23     24    fsd
34     34    dsf
21     22    dsf
</code>```

Here 2nd and 4th Row values(ColA and ColB are not equal), So is there a way to extract row values and cell values corresponding to that?

```<code>Row values
2, 4
</code>```

```<code>Cel_value_ColC  # Corresponding values
fsd, dsf
</code>```

答:
We can take the rows where colA-colB are not = 0</p>

```<code>df$ColC[df$ColA-df$Colb != 0]
[1] fsd dsf
</code>```

Body:
Is there a way to extract values in the dataframe when the columns values are not equal

df
ColA  Colb  ColC
12     12    fs
23     24    fsd
34     34    dsf
21     22    dsf

Here 2nd and 4th Row values(ColA and ColB are not equal), So is there a way to extract row values and cell values corresponding to that?

Row values
2, 4

Cel_value_ColC  # Corresponding values
fsd, dsf

Body:
We can take the rows where colA-colB are not = 0

df$ColC[df$ColA-df$Colb != 0]
[1] fsd dsf


问:
VBA: add a row in excel only if there's a value in a cell
I'm currently using the macro below so when I make a change in cells from column B, it adds a Line. I'd like to know how to change the code so it only adds a line when there's content in the cell and not when I make a change (like erasing content from that same cell).
Thanks!</p>

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

    'Test if change is in column B and only one cell changed
    If Not Intersect(Target, Me.Columns("B")) Is Nothing And _
            Target.Cells.Count = 1 Then

        Target.Offset(1, 0).EntireRow.Insert Shift:=xlDown      'Insert row below data entry

        'Target.EntireRow.Insert Shift:=xlDown       'Insert row above data entry

    End If
End Sub
</code>```

答:
There are various ways to check if a cell is empty, such as ...

```<code>Private Sub Worksheet_Change(ByVal Target As Range)

'Test if change is in column B and only one cell changed
If Not Intersect(Target, Me.Columns("B")) Is Nothing And _
        Target.Cells.Count = 1 Then

    If len(Target)>0 then
          Target.Offset(1, 0).EntireRow.Insert Shift:=xlDown      'Insert row below data entry
         'Target.EntireRow.Insert Shift:=xlDown       'Insert row above data entry
    End If
End If

End Sub
</code>```

Or you could Isempty(Target) or target<>vbnullstring.

Body:
I'm currently using the macro below so when I make a change in cells from column B, it adds a Line. I'd like to know how to change the code so it only adds a line when there's content in the cell and not when I make a change (like erasing content from that same cell).
Thanks!

Private Sub Worksheet_Change(ByVal Target As Range)

    'Test if change is in column B and only one cell changed
    If Not Intersect(Target, Me.Columns("B")) Is Nothing And _
            Target.Cells.Count = 1 Then

        Target.Offset(1, 0).EntireRow.Insert Shift:=xlDown      'Insert row below data entry

        'Target.EntireRow.Insert Shift:=xlDown       'Insert row above data entry

    End If
End Sub

Body:
There are various ways to check if a cell is empty, such as ...

Private Sub Worksheet_Change(ByVal Target As Range)

'Test if change is in column B and only one cell changed
If Not Intersect(Target, Me.Columns("B")) Is Nothing And _
        Target.Cells.Count = 1 Then

    If len(Target)>0 then
          Target.Offset(1, 0).EntireRow.Insert Shift:=xlDown      'Insert row below data entry
         'Target.EntireRow.Insert Shift:=xlDown       'Insert row above data entry
    End If
End If

End Sub

Or you could Isempty(Target) or target<>vbnullstring.


问:
Sylius Resource and Doctrine Filter
I'm new in Sylius and trying to extend it for my business. I'm currently facing an issue on admin part that I don't know how to solve.

I've an Basket entity which is One-To-One related with the Sylius Product entity:

/**
 * @ORM\Entity
 * @ORM\Table(name="app_basket")
 */
class Basket implements ResourceInterface, BasketInterface
{
    /**
     * @ORM\OneToOne(targetEntity="App\Entity\Product\Product", inversedBy="basket", cascade={"persist", "remove"})
     * @ORM\JoinColumn(nullable=false)
     */
    private $product;
}
```

<p>I created this relation to be able to deal with Order Management of Sylius much easier. I don't want to mix Basket and Product objects in my business, so I created a Doctrine filter to exclude Basket items from Products:</p>

<pre class="lang-php prettyprint-override"><code><?php

namespace App\Doctrine\Filter;

use App\Entity\Product\Product;
use Doctrine\ORM\Mapping\ClassMetadata;
use \Doctrine\ORM\Query\Filter\SQLFilter;

class ProductFilter extends SQLFilter
{

    /**
     * @inheritDoc
     */
    public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
    {
        if($targetEntity->getName() !== Product::class) {
            return '';
        }

        return "$targetTableAlias.id not in (select product_id from app_basket)";
    }

}
</code>```

On the admin products page, everything is great, I don't have the baskets. But, if I go the the Basket admin index page, I have the following error:

An exception has been thrown during the rendering of a template
  ("Entity of type 'App\Entity\Product\Product' for IDs id(4) was not
  found").

This is because of the grid I use. I want to display the name of the product included in the basket:

```<code>sylius_grid:
    grids:
        app_admin_basket:
            driver:
                name: doctrine/orm
                options:
                    class: App\Entity\Basket\Basket
            fields:
                id:
                    type: string
                    label: sylius.ui.id
                product.name:
                    type: string
                    label: sylius.ui.name
</code>```

To retrieve the basket.product.name, the generated query is querying directly to the product table instead of the basket one:

```<code>SELECT t0.code AS code_1, t0.created_at AS created_at_2, t0.updated_at AS updated_at_3, t0.enabled AS enabled_4, t0.id AS id_5, t0.variant_selection_method AS variant_selection_method_6, t0.average_rating AS average_rating_7, t0.main_taxon_id AS main_taxon_id_8, t9.id AS id_10, t9.product_id AS product_id_11
--problem here
FROM sylius_product t0
LEFT JOIN app_basket t9 ON t9.product_id = t0.id
WHERE t0.id = 4
--Doctrine SQL FIlter
AND ((t0.id not in (select product_id from app_basket)));
</code>```

I've also the same behavior if a get this in a twig template :

```<code>{{ basket.product.name }}
</code>```

With a fetch="EAGER" annotation I don't have the error but the targeted entity still not reflect what I want.

Is there a way to force Sylius Resource to pass through basket entity first and not directly to the embedded entity?

答:
Try this

```<code>sylius_grid:
    grids:
        app_admin_basket:
            driver:
                name: doctrine/orm
                options:
                    class: App\Entity\Basket\Basket
            fields:
                id:
                    type: string
                    label: sylius.ui.id
                product.name:
                    type: twig
                    label: sylius.ui.name
                    path: .
                    options:
                        template: thetemplate.html.twig
</code>```

The path: . property gives you access to the whole entity instead of a specific property. You should then be able to access it using data.product.name in the twig template.

You could also try this, altho I haven't tested it:

```<code>sylius_grid:
    grids:
        app_admin_basket:
            driver:
                name: doctrine/orm
                options:
                    class: App\Entity\Basket\Basket
            fields:
                id:
                    type: string
                    label: sylius.ui.id
                product.name:
                    type: string
                    label: sylius.ui.name
                    path: product.name
</code>```

Title: Sylius Resource and Doctrine Filter

Body:
I'm new in Sylius and trying to extend it for my business. I'm currently facing an issue on admin part that I don't know how to solve.

I've an Basket entity which is One-To-One related with the Sylius Product entity:

/**
 * @ORM\Entity
 * @ORM\Table(name="app_basket")
 */
class Basket implements ResourceInterface, BasketInterface
{
    /**
     * @ORM\OneToOne(targetEntity="App\Entity\Product\Product", inversedBy="basket", cascade={"persist", "remove"})
     * @ORM\JoinColumn(nullable=false)
     */
    private $product;
}

I created this relation to be able to deal with Order Management of Sylius much easier. I don't want to mix Basket and Product objects in my business, so I created a Doctrine filter to exclude Basket items from Products:

<?php

namespace App\Doctrine\Filter;

use App\Entity\Product\Product;
use Doctrine\ORM\Mapping\ClassMetadata;
use \Doctrine\ORM\Query\Filter\SQLFilter;

class ProductFilter extends SQLFilter
{

    /**
     * @inheritDoc
     */
    public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
    {
        if($targetEntity->getName() !== Product::class) {
            return '';
        }

        return "$targetTableAlias.id not in (select product_id from app_basket)";
    }

}

On the admin products page, everything is great, I don't have the baskets. But, if I go the the Basket admin index page, I have the following error:

An exception has been thrown during the rendering of a template
  ("Entity of type 'App\Entity\Product\Product' for IDs id(4) was not
  found").

This is because of the grid I use. I want to display the name of the product included in the basket:

sylius_grid:
    grids:
        app_admin_basket:
            driver:
                name: doctrine/orm
                options:
                    class: App\Entity\Basket\Basket
            fields:
                id:
                    type: string
                    label: sylius.ui.id
                product.name:
                    type: string
                    label: sylius.ui.name

To retrieve the basket.product.name, the generated query is querying directly to the product table instead of the basket one:

SELECT t0.code AS code_1, t0.created_at AS created_at_2, t0.updated_at AS updated_at_3, t0.enabled AS enabled_4, t0.id AS id_5, t0.variant_selection_method AS variant_selection_method_6, t0.average_rating AS average_rating_7, t0.main_taxon_id AS main_taxon_id_8, t9.id AS id_10, t9.product_id AS product_id_11
--problem here
FROM sylius_product t0
LEFT JOIN app_basket t9 ON t9.product_id = t0.id
WHERE t0.id = 4
--Doctrine SQL FIlter
AND ((t0.id not in (select product_id from app_basket)));

I've also the same behavior if a get this in a twig template :

{{ basket.product.name }}

With a fetch="EAGER" annotation I don't have the error but the targeted entity still not reflect what I want.

Is there a way to force Sylius Resource to pass through basket entity first and not directly to the embedded entity?

Body:
Try this

sylius_grid:
    grids:
        app_admin_basket:
            driver:
                name: doctrine/orm
                options:
                    class: App\Entity\Basket\Basket
            fields:
                id:
                    type: string
                    label: sylius.ui.id
                product.name:
                    type: twig
                    label: sylius.ui.name
                    path: .
                    options:
                        template: thetemplate.html.twig

The path: . property gives you access to the whole entity instead of a specific property. You should then be able to access it using data.product.name in the twig template.

You could also try this, altho I haven't tested it:

sylius_grid:
    grids:
        app_admin_basket:
            driver:
                name: doctrine/orm
                options:
                    class: App\Entity\Basket\Basket
            fields:
                id:
                    type: string
                    label: sylius.ui.id
                product.name:
                    type: string
                    label: sylius.ui.name
                    path: product.name


问:
When to use composite key instead of auto increment
I am creating a database and I am not sure about one of my tables. This table stores the users that are in each game, so one entry per user per game. The user is identified by their user_id which is a 36 character UUID4, and the game is identified by a session_id which is an 8 character alphanumeric string such as "ABK2RXN4". Currently, I have created an additional field just called id which is an integer that auto increments, and I have set that to be the primary key. These are the only 3 fields.

Since the combination of the session_id and the user_id will always result in a unique outcome, should I instead use those two as the composite private key and remove the id field?

Thanks.

EDIT:

Do things change if we have a more complicated table that will require more fields? Take this table for example.

```<code>| id  | voter    | voting_for | round    | category_id | acceptable |
|-----|----------|------------|----------|-------------|------------|
| int | char(36) | char(36)   | smallint | int         | boolean    |
</code>```

This is to do with votes within a game. Essentially after each round, the users in the game will vote on the answers of the other users within the game. So each entry has the user_id of the voter, the user_id of the person they are voting_for, the current round, the category_id of the category within the game and whether or not they agreed with the answer, acceptable. So, you could make a composite primary key using voter, voting_for, round and category_id. Is this any worse just because there are more fields, or should I still use the composite key instead of the existing auto increment id?

答:
That depends.

If the bridge table is going to contain any other columns that are attributes of the relationship between user and game (say, JoinedGameDate or what have you), then the rows should probably have IDs of their own, since it sounds like that's your design pattern, and table structure consistency has some value. Although throwing a UNIQUE index on those two values wouldn't be a bad idea.

On the other hand, if it's truly just a bridge defining the N:N relationship, you could get away with defining a composite key, which would take care of your indexing, and call it a day.

On the other, other hand, the overhead on that one extra auto increment is pretty minimal, so whichever way you go the performance impact of the decision will probably be negligible.

Body:
I am creating a database and I am not sure about one of my tables. This table stores the users that are in each game, so one entry per user per game. The user is identified by their user_id which is a 36 character UUID4, and the game is identified by a session_id which is an 8 character alphanumeric string such as "ABK2RXN4". Currently, I have created an additional field just called id which is an integer that auto increments, and I have set that to be the primary key. These are the only 3 fields.

Since the combination of the session_id and the user_id will always result in a unique outcome, should I instead use those two as the composite private key and remove the id field?

Thanks.

EDIT:

Do things change if we have a more complicated table that will require more fields? Take this table for example.

| id  | voter    | voting_for | round    | category_id | acceptable |
|-----|----------|------------|----------|-------------|------------|
| int | char(36) | char(36)   | smallint | int         | boolean    |

This is to do with votes within a game. Essentially after each round, the users in the game will vote on the answers of the other users within the game. So each entry has the user_id of the voter, the user_id of the person they are voting_for, the current round, the category_id of the category within the game and whether or not they agreed with the answer, acceptable. So, you could make a composite primary key using voter, voting_for, round and category_id. Is this any worse just because there are more fields, or should I still use the composite key instead of the existing auto increment id?


问:
How do I designate which compiler is called when running cmake + make?
I'm trying to compile a c++ project with cmake and make on OSX but it looks like make is using CXX or clang when I want to use g++ (gcc) so I can follow the answer here to tell the compiler where to find header files (#includes) for tbb used in the project: Need help getting intel TBB working?

brew list shows that I have up to date versions of cmake, make, gcc, and swig installed.

Here's the project I'm trying to compile for reference: https://github.com/nmoehrle/mvs-texturing/blob/master/README.md

答:
I came across this related answer and was able to get the project working! MacOS, CMake and OpenMP

I updated the cmakelists.txt with the following commands to set llvm as the compiler. Note, I needed to update the llvm file path to match the version number I have installed.

```<code>set(CMAKE_C_COMPILER "/usr/local/Cellar/llvm/5.0.1/bin/clang")
set(CMAKE_CXX_COMPILER "/usr/local/Cellar/llvm/5.0.1/bin/clang++")
set(OPENMP_LIBRARIES "/usr/local/Cellar/llvm/5.0.1/lib")
set(OPENMP_INCLUDES "/usr/local/Cellar/llvm/5.0.1/include")
</code>```

Then I was also having issues with OpenMP so I added this section to configure the OpenMP include directories and link directories.

```<code>if (OPENMP_FOUND)
    include_directories("${OPENMP_INCLUDES}")
    link_directories("${OPENMP_LIBRARIES}")
    set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
    set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
endif(OPENMP_FOUND)
</code>```

I'm a novice dev and wish I had more insight into why this worked but it fixed my issues!

Body:
I came across this related answer and was able to get the project working! MacOS, CMake and OpenMP

I updated the cmakelists.txt with the following commands to set llvm as the compiler. Note, I needed to update the llvm file path to match the version number I have installed.

set(CMAKE_C_COMPILER "/usr/local/Cellar/llvm/5.0.1/bin/clang")
set(CMAKE_CXX_COMPILER "/usr/local/Cellar/llvm/5.0.1/bin/clang++")
set(OPENMP_LIBRARIES "/usr/local/Cellar/llvm/5.0.1/lib")
set(OPENMP_INCLUDES "/usr/local/Cellar/llvm/5.0.1/include")

Then I was also having issues with OpenMP so I added this section to configure the OpenMP include directories and link directories.

if (OPENMP_FOUND)
    include_directories("${OPENMP_INCLUDES}")
    link_directories("${OPENMP_LIBRARIES}")
    set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
    set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
endif(OPENMP_FOUND)

I'm a novice dev and wish I had more insight into why this worked but it fixed my issues!


问:
django urls.py: two modules with similar paths
I have two modules in my django app, let's say cats and dogs, and I want to have urls like this:

/fluffy/meow.html  - Fluffy is a cat's name

/fluffy/eat.html

/jackie/bark.html  - Jackie is a dog

/jackie/eat.html   - same name as in cats module

There will be a lot of different cats and dogs, but it's guaranteed, that cat and dog can't have the same name.

If I make urls.py like this:

urlpatterns += [
    path('<slug:cat_name>/', include('cats.urls')),
    path('<slug:dog_name>/', include('dogs.urls')),
]
```

<p>request <code>/jackie/eat.html</code> wil be caught by <code>cats</code>
module, but there's no cat with name jackie, so it will give 404 error. Is it possible to make django check another url path instead of getting 404 error? </p>

<hr>

<p>I know, that I can use this <code>urls.py</code></p>

<pre class="lang-py prettyprint-override"><code>urlpatterns += [
    path('cats/<slug:cat_name>/', include('cats.urls')),
    path('dogs/<slug:dog_name>/', include('dogs.urls')),
]
</code>```

But I don't want it

there's about 1000 cats' names, and it's not frequently changing, so i can hardcode cat's names in huge re_path, but I hope that there's a better solution

```<code>urlpatterns += [
    re_path(r'^(?P<cat_name>fluffy|simon|thomas|etc..)/$', include('cats.urls')),
    path('<slug:dog_name>/', include('dogs.urls')),
]
</code>```

答:
First of all, create a model name animal, It contains

```<code>1. Category - Dog or cat
2. Name - animal name
3. ... if u want any values, add it here
</code>```

for example:

```<code>from django.db import models

class Animal(models.Model):
    ANIMAL_CHOICES= (
        ('cat', 'cat'),
        ('dog', 'dog'),
    )
    category = models.CharField(max_length=1, choices=ANIMAL_CHOICES)
    name = models.CharField(max_length=30)
</code>```

and then in your urls.py

```<code>urlpatterns += [
    path('cats/<slug:cat_name>/', cat, name="cats"),
    path('dogs/<slug:dog_name>/', dog, name="dogs"),
]
</code>```

In your views.py

```<code>def cat(request, cat_name):
    cat = Animals.objects.filter(category="cat", name=cat_name)
    context = { cat: cat }
    return render(request, "template_name.html", context=context)

def dog(request, dog_name):
    cat = Animals.objects.filter(category="dog", name=dog_name)
    context = { dog: dog }
    return render(request, "template_name.html", context=context)
</code>```

Body:
I have two modules in my django app, let's say cats and dogs, and I want to have urls like this:

/fluffy/meow.html  - Fluffy is a cat's name

/fluffy/eat.html

/jackie/bark.html  - Jackie is a dog

/jackie/eat.html   - same name as in cats module

There will be a lot of different cats and dogs, but it's guaranteed, that cat and dog can't have the same name.

If I make urls.py like this:

urlpatterns += [
    path('<slug:cat_name>/', include('cats.urls')),
    path('<slug:dog_name>/', include('dogs.urls')),
]

request /jackie/eat.html wil be caught by cats
module, but there's no cat with name jackie, so it will give 404 error. Is it possible to make django check another url path instead of getting 404 error?

I know, that I can use this urls.py

urlpatterns += [
    path('cats/<slug:cat_name>/', include('cats.urls')),
    path('dogs/<slug:dog_name>/', include('dogs.urls')),
]

But I don't want it

there's about 1000 cats' names, and it's not frequently changing, so i can hardcode cat's names in huge re_path, but I hope that there's a better solution

urlpatterns += [
    re_path(r'^(?P<cat_name>fluffy|simon|thomas|etc..)/$', include('cats.urls')),
    path('<slug:dog_name>/', include('dogs.urls')),
]

Body:
First of all, create a model name animal, It contains

1. Category - Dog or cat
2. Name - animal name
3. ... if u want any values, add it here

for example:

from django.db import models

class Animal(models.Model):
    ANIMAL_CHOICES= (
        ('cat', 'cat'),
        ('dog', 'dog'),
    )
    category = models.CharField(max_length=1, choices=ANIMAL_CHOICES)
    name = models.CharField(max_length=30)

and then in your urls.py

urlpatterns += [
    path('cats/<slug:cat_name>/', cat, name="cats"),
    path('dogs/<slug:dog_name>/', dog, name="dogs"),
]

In your views.py

def cat(request, cat_name):
    cat = Animals.objects.filter(category="cat", name=cat_name)
    context = { cat: cat }
    return render(request, "template_name.html", context=context)

def dog(request, dog_name):
    cat = Animals.objects.filter(category="dog", name=dog_name)
    context = { dog: dog }
    return render(request, "template_name.html", context=context)


问:
How to take incremental backup for firestore
Is there a way to take incremental backups for firestore? We need to take regular backups and taking full backup everyday will only get more expensive over time.
Also is there any plan of supporting point in time restore for firestore?</p>

答: Firestore does not have a backup mechanism.  It has an import/export mechanism, which is not really the same thing.  If you need backups, especially incremental backups, you will need to implement that yourself or find another solution.</p>


答:
if your objective is to store the students in an array-like structure, then you can definitely do this in Python. What you're currently doing is instantiating a new class object for each student. While this is totally valid, it may not be appropriate for the task you're trying to achieve. </p>

<p>Before mastering classes, I'd recommend familiarising yourself with python data structures like dictionaries, lists and tuples. </p>

Body:
I want to input data in a class. I don't know  the number of students I want to input. I can only write p1.name="John" p2.name="Jack" etc but if I want to input more students I have to write p3,p4,p5...

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person
p1.name="John"
p1.age=15
print(p1.name)
print(p1.age)

Is there a method to work like with arrays for example p[0].name="John"....... p[123].name="Jack" or something like that... Sorry for my bad english

Body:
if your objective is to store the students in an array-like structure, then you can definitely do this in Python. What you're currently doing is instantiating a new class object for each student. While this is totally valid, it may not be appropriate for the task you're trying to achieve.

Before mastering classes, I'd recommend familiarising yourself with python data structures like dictionaries, lists and tuples.


问:
Does pandas iterrows have performance issues?
I have noticed very poor performance when using iterrows from pandas.

Is it specific to iterrows and should this function be avoided for data of a certain size (I'm working with 2-3 million rows)?

This discussion on GitHub led me to believe it is caused when mixing dtypes in the dataframe, however the simple example below shows it is there even when using one dtype (float64). This takes 36 seconds on my machine:

```<code>import pandas as pd
import numpy as np
import time

s1 = np.random.randn(2000000)
s2 = np.random.randn(2000000)
dfa = pd.DataFrame({'s1': s1, 's2': s2})

start = time.time()
i=0
for rowindex, row in dfa.iterrows():
    i+=1
end = time.time()
print end - start
</code>```

Why are vectorized operations like apply so much quicker? I imagine there must be some row by row iteration going on there too.

I cannot figure out how to not use iterrows in my case (this I'll save for a future question). Therefore I would appreciate hearing if you have consistently been able to avoid this iteration. I'm making calculations based on data in separate dataframes.

A simplified version of what I want to run:

```<code>import pandas as pd
import numpy as np

#%% Create the original tables
t1 = {'letter':['a','b'],
      'number1':[50,-10]}

t2 = {'letter':['a','a','b','b'],
      'number2':[0.2,0.5,0.1,0.4]}

table1 = pd.DataFrame(t1)
table2 = pd.DataFrame(t2)

#%% Create the body of the new table
table3 = pd.DataFrame(np.nan, columns=['letter','number2'], index=[0])

#%% Iterate through filtering relevant data, optimizing, returning info
for row_index, row in table1.iterrows():
    t2info = table2[table2.letter == row['letter']].reset_index()
    table3.ix[row_index,] = optimize(t2info,row['number1'])

#%% Define optimization
def optimize(t2info, t1info):
    calculation = []
    for index, r in t2info.iterrows():
        calculation.append(r['number2']*t1info)
    maxrow = calculation.index(max(calculation))
    return t2info.ix[maxrow]
</code>```

答:
Details in this video

Benchmark

Body:
I have noticed very poor performance when using iterrows from pandas.

Is it specific to iterrows and should this function be avoided for data of a certain size (I'm working with 2-3 million rows)?

This discussion on GitHub led me to believe it is caused when mixing dtypes in the dataframe, however the simple example below shows it is there even when using one dtype (float64). This takes 36 seconds on my machine:

import pandas as pd
import numpy as np
import time

s1 = np.random.randn(2000000)
s2 = np.random.randn(2000000)
dfa = pd.DataFrame({'s1': s1, 's2': s2})

start = time.time()
i=0
for rowindex, row in dfa.iterrows():
    i+=1
end = time.time()
print end - start

Why are vectorized operations like apply so much quicker? I imagine there must be some row by row iteration going on there too.

I cannot figure out how to not use iterrows in my case (this I'll save for a future question). Therefore I would appreciate hearing if you have consistently been able to avoid this iteration. I'm making calculations based on data in separate dataframes.

A simplified version of what I want to run:

import pandas as pd
import numpy as np

#%% Create the original tables
t1 = {'letter':['a','b'],
      'number1':[50,-10]}

t2 = {'letter':['a','a','b','b'],
      'number2':[0.2,0.5,0.1,0.4]}

table1 = pd.DataFrame(t1)
table2 = pd.DataFrame(t2)

#%% Create the body of the new table
table3 = pd.DataFrame(np.nan, columns=['letter','number2'], index=[0])

#%% Iterate through filtering relevant data, optimizing, returning info
for row_index, row in table1.iterrows():
    t2info = table2[table2.letter == row['letter']].reset_index()
    table3.ix[row_index,] = optimize(t2info,row['number1'])

#%% Define optimization
def optimize(t2info, t1info):
    calculation = []
    for index, r in t2info.iterrows():
        calculation.append(r['number2']*t1info)
    maxrow = calculation.index(max(calculation))
    return t2info.ix[maxrow]

Body:
Details in this video

Benchmark


问:
Php array object check children array for value
I have the following object:

```<code>[335] =  WP_Post Object
  (
   [post_author] = 6
   [post_date] = 2018-03-12 14:33:06
   [page_id] = 333
   [wpse_children] = Array
       (
           [441] =  WP_Post Object
               (
                   [ID] = 441
                   [post_date] = 2018-03-16 20:47:14
                   [post_parent] = 333
                   [menu_item_parent] = 335
                   [page_id] = 385
               )

           [441] =  WP_Post Object
               (
                   [ID] = 452
                   [post_date] = 2018-03-16 20:47:14
                   [post_parent] = 333
                   [menu_item_parent] = 335
                   [page_id] = 442
               )

           [541] =  WP_Post Object
               (
                   [ID] = 480
                   [post_date] = 2018-03-16 20:47:14
                   [post_parent] = 333
                   [menu_item_parent] = 335
                   [page_id] = 680
               )

       )
)
</code>```

I'm using the object to create a navigation menu in HTML with children menu items as a dropdown:

Parent menu item

Submenu item 1

Submenu item 2

Submenu item 3

$menu_item is the main object.

I can get for example, the post author id value by using $menu_item->post_author.

For each menu item, I'm adding a class named active if it is on the current page:

```<code>if ($menu_item->page_id == $current_page_id) {
  array_push($class_names, 'current-menu-item');
}
</code>```

($class_names are later added to the menu item class attribute)

This works fine but I also want to keep the class active on the parent menu item if on a child item page.

How can I check the object's wpse_children array to see if page_id is equal to $current_page_id and menu_item_parent is equal to the main objcet id (in this case 335)?

If true, i want to add class active to the parent item.

答:
Given that $menu_item is the object you described you can just iterate over $menu_item->wpse_children.

foreach($menu_item->wpse_children as $child) {
    // do stuff with children
    if ($child->page_id === $current_page_id) {
        // do stuff
    }
}
```

Body:
I have the following object:

[335] =  WP_Post Object
  (
   [post_author] = 6
   [post_date] = 2018-03-12 14:33:06
   [page_id] = 333
   [wpse_children] = Array
       (
           [441] =  WP_Post Object
               (
                   [ID] = 441
                   [post_date] = 2018-03-16 20:47:14
                   [post_parent] = 333
                   [menu_item_parent] = 335
                   [page_id] = 385
               )

           [441] =  WP_Post Object
               (
                   [ID] = 452
                   [post_date] = 2018-03-16 20:47:14
                   [post_parent] = 333
                   [menu_item_parent] = 335
                   [page_id] = 442
               )

           [541] =  WP_Post Object
               (
                   [ID] = 480
                   [post_date] = 2018-03-16 20:47:14
                   [post_parent] = 333
                   [menu_item_parent] = 335
                   [page_id] = 680
               )

       )
)

I'm using the object to create a navigation menu in HTML with children menu items as a dropdown:

Parent menu item

Submenu item 1

Submenu item 2

Submenu item 3

$menu_item is the main object.

I can get for example, the post author id value by using $menu_item->post_author.

For each menu item, I'm adding a class named active if it is on the current page:

if ($menu_item->page_id == $current_page_id) {
  array_push($class_names, 'current-menu-item');
}

($class_names are later added to the menu item class attribute)

This works fine but I also want to keep the class active on the parent menu item if on a child item page.

How can I check the object's wpse_children array to see if page_id is equal to $current_page_id and menu_item_parent is equal to the main objcet id (in this case 335)?

If true, i want to add class active to the parent item.


问:
Disable redis persistence in docker
According to this link, persistence of redis instances can be prevented by setting --save ''. However when I try to use that argument in my docker-compose.yml the redis instance still loads a database from disk and persists all data:

```<code>version: '3'
services:
  redis:
    image: "redis:alpine"
    command: ["redis-server", "--save"]  # disable persistence
    ports:
      - "7777:6379"
</code>```

I also tried command: ["redis-server", "--save", ""] but the problem preserves.

How can I enforce non-persistence (empty redis on every restart)?

答:
--renew-anon-volumes addresses the underlying problem of Redis retrieving a volume from the previous container after being stopped.

```<code>docker-compose up --renew-anon-volumes
</code>```

Note that this affects other containers that keep their volumes around after being stopped, such as MySQL and Postgres.

Title: Disable redis persistence in docker

Body:
According to this link, persistence of redis instances can be prevented by setting --save ''. However when I try to use that argument in my docker-compose.yml the redis instance still loads a database from disk and persists all data:

version: '3'
services:
  redis:
    image: "redis:alpine"
    command: ["redis-server", "--save"]  # disable persistence
    ports:
      - "7777:6379"

I also tried command: ["redis-server", "--save", ""] but the problem preserves.

How can I enforce non-persistence (empty redis on every restart)?

Body:
--renew-anon-volumes addresses the underlying problem of Redis retrieving a volume from the previous container after being stopped.

docker-compose up --renew-anon-volumes

Note that this affects other containers that keep their volumes around after being stopped, such as MySQL and Postgres.