问:
How to sorting parent and child CoreData element in swift
I have 3 entity in my CoreData model.Category ,Subcategory ,inventory.inventory connected to subcategory and subcategory connected to category using relationships.so when I want to get inventory and subcategory than I get using category data.so my problem is I want to sorting all three entity data using alphabetical order.

```<code>class func getAllCategoriesObject() -> [DBCategories]?
    {
        let context = getContext()

        let fetchRequest:NSFetchRequest<DBCategories> = DBCategories.fetchRequest()
        fetchRequest.returnsObjectsAsFaults = false

        do{
            let fetchedData = try context.fetch(fetchRequest).sorted(by: { (objCategory1, objCategory2) -> Bool in
                (objCategory1.subcategories?.allObjects as? [DBSubCategories] ?? []).sorted { (objSubCategory1, objSubCategory2) -> Bool in

                    (objSubCategory1.inventories?.allObjects as? [DBInventories] ?? []).sorted { (objInventory1, objInventory2) -> Bool in

                        return objInventory1.title?.capitalized ?? "" < objInventory2.title?.capitalized ?? ""
                    }

                    return objSubCategory1.title?.capitalized ?? "" < objSubCategory2.title?.capitalized ?? ""
                }

                return objCategory1.title?.capitalized ?? "" < objCategory2.title?.capitalized ?? ""
            })

            return fetchedData
        }
        catch
        {
            print( error.localizedDescription)
        }
        return []
    }
</code>```

I had tried above code but not getting output.

答:
You can't do it like that - you're not allowed to sort Core Data relationships with sort blocks.
If you want to achieve alphabetical order, you can do it with:

```<code>NSSortDescriptor(key: [KEY NAME], ascending: true, selector: #selector(NSString.caseInsensitiveCompare))
</code>```

If you wish to do in one fetch then you must make sure the Core Data objects are already sorted when you save them - by using an ordered relationship (you can read more about it here).
So when you fetch the parent object the child object connected with the NSOrderedSet relationship are already sorted according to you wishes.

Just for quick example:

```<code>//Create context, create objects in context
let someChildsObject: [NSManagedObject] = //.. Objects with name property
someChildsObject.sorted(by: { $0.name > $1.name }) //Sorting according to name value
parent.children = NSOrderedSet(array: someChildsObject)
//Save context
</code>```

By Doing so the data will be already sorted in the database.

Body:
I have 3 entity in my CoreData model.Category ,Subcategory ,inventory.inventory connected to subcategory and subcategory connected to category using relationships.so when I want to get inventory and subcategory than I get using category data.so my problem is I want to sorting all three entity data using alphabetical order.

class func getAllCategoriesObject() -> [DBCategories]?
    {
        let context = getContext()

        let fetchRequest:NSFetchRequest<DBCategories> = DBCategories.fetchRequest()
        fetchRequest.returnsObjectsAsFaults = false

        do{
            let fetchedData = try context.fetch(fetchRequest).sorted(by: { (objCategory1, objCategory2) -> Bool in
                (objCategory1.subcategories?.allObjects as? [DBSubCategories] ?? []).sorted { (objSubCategory1, objSubCategory2) -> Bool in

                    (objSubCategory1.inventories?.allObjects as? [DBInventories] ?? []).sorted { (objInventory1, objInventory2) -> Bool in

                        return objInventory1.title?.capitalized ?? "" < objInventory2.title?.capitalized ?? ""
                    }

                    return objSubCategory1.title?.capitalized ?? "" < objSubCategory2.title?.capitalized ?? ""
                }

                return objCategory1.title?.capitalized ?? "" < objCategory2.title?.capitalized ?? ""
            })

            return fetchedData
        }
        catch
        {
            print( error.localizedDescription)
        }
        return []
    }

I had tried above code but not getting output.

Body:
You can't do it like that - you're not allowed to sort Core Data relationships with sort blocks.
If you want to achieve alphabetical order, you can do it with:

NSSortDescriptor(key: [KEY NAME], ascending: true, selector: #selector(NSString.caseInsensitiveCompare))

If you wish to do in one fetch then you must make sure the Core Data objects are already sorted when you save them - by using an ordered relationship (you can read more about it here).
So when you fetch the parent object the child object connected with the NSOrderedSet relationship are already sorted according to you wishes.

Just for quick example:

//Create context, create objects in context
let someChildsObject: [NSManagedObject] = //.. Objects with name property
someChildsObject.sorted(by: { $0.name > $1.name }) //Sorting according to name value
parent.children = NSOrderedSet(array: someChildsObject)
//Save context

By Doing so the data will be already sorted in the database.


来源: stackexchange

问:
javascript cannot find a method which exists
I have a pretty simple function declared in my JavaScript file, which is just supposed to return whether or not the validation has begun:

```<code>window.Validator = function(){
    this._started = false;
    this.started = function(){
        return this._started;
    };
}

Validator.started();
</code>```

However, when I call Validator.started(), even though it's literally directly after the declaration, it will throw the error:

Uncaught TypeError: Validator.started is not a function

Really scratching my head with this one and have no idea why it isn't working.

答:
You should create an instance of your Validator</p>

```<code>new Validator().started()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a pretty simple function declared in my JavaScript file, which is just supposed to return whether or not the validation has begun:

window.Validator = function(){
    this._started = false;
    this.started = function(){
        return this._started;
    };
}

Validator.started();

However, when I call Validator.started(), even though it's literally directly after the declaration, it will throw the error:

Uncaught TypeError: Validator.started is not a function

Really scratching my head with this one and have no idea why it isn't working.

Body:
You should create an instance of your Validator

new Validator().started()


问:
CircleCI error while testing (i think MongoDB related) - Cannot read property 'split' of null
i am getting:

TypeError: Cannot read property 'split' of null

in error object from mongoose.connect, in CircleCI, and later on tests timeout, first one fails with 500 error.
It seems like mongo/mongoose error, am i doing something wrong with tests, i mean i am sure i do, since with simple non-async test i am not getting this error.
Btw, this works fine locally, no errors, just fails at CircleCI tests.

app.ts Database(mongoose) connect code:

```<code>mongoose
  .connect(mongoUrl, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true,
    useFindAndModify: false,
    dbName: 'expressing-space',
  })

  .then(() => {
    // console.log('MongoDB connected..');
  })
  .catch((err) => {
    console.log(
      'MongoDB connection error. Please make sure MongoDB is running. ' + err,
    );
  });
</code>```

tests:

```<code>import request from 'supertest';
import mongoose from 'mongoose';
import app from '../src/app';

let token: string = '';
const email = 'x@x.com';
const password = '12345';

beforeAll((done) => {
  request(app)
    .post('/auth/login')
    .send({
      email,
      password,
    })
    .end((err, response) => {
      token = response.body.token;
      done();
    });
});

afterAll((done) => {
  // Closing the DB connection allows Jest to exit successfully.
  mongoose.connection.close();
  done();
});

describe('GET /likes/artists/', () => {
  // token not being sent - should respond with a 401
  it('should return require authorization - return 401', async (done) => {
    const res = await request(app)
      .get('/likes/artists/')
      .set('Content-Type', 'application/json');
    expect(res.status).toBe(401);
    done();
  });

  // send the token - should respond with a 200
  it('should respond with JSON data - 200', async (done) => {
    const res = await request(app)
      .get('/likes/artists/')
      .set('Authorization', `Bearer ${token}`)
      .set('Content-Type', 'application/json');
    expect(res.status).toBe(200);
    expect(res.type).toBe('application/json');
    done();
  });
});

describe('PUT /likes/artists/', () => {
  it('should return require authorization - return 401', async (done) => {
    const res = await request(app)
      .put('/likes/artists')
      .set('Content-Type', 'application/json');
    expect(res.status).toBe(401);
    done();
  });

  // #Todo: There is probalby better way to go about this. Re-check it!
  it('should return json data with either name prop for success or message prop for err', async (done) => {
    const name = 'dmx';
    const res = await request(app)
      .put('/likes/artists')
      .set('Authorization', `Bearer ${token}`)
      .set('Content-Type', 'application/json')
      .send({ name });

    if (res.status === 409) {
      expect(res.status).toBe(409);
      expect(res.body).toHaveProperty('message');
    } else if (res.status === 201) {
      expect(res.status).toBe(201);
      expect(res.body.artist).toHaveProperty('name');
    }
    done();
  });
});

// #Todo: There is probalby better way to go about this. Re-check it!
describe('DELETE /likes/artists/:artistId', () => {
  const artistId = '5e24d7350b68952acdcafc2e';
  it('should return require authorization - return 401', async (done) => {
    const res = await request(app).delete(`/likes/artists/${artistId}`);
    expect(res.status).toBe(401);
    done();
  });

  it('should delete userId from artist if it exists or return 404 if not', async (done) => {
    const res = await request(app)
      .delete(`/likes/artists/${artistId}`)
      .set('Authorization', `Bearer ${token}`);

    if (res.status === 404) {
      expect(res.status).toBe(404);
      expect(res.body).toHaveProperty('message');
    } else if (res.status === 202) {
      expect(res.status).toBe(202);
      expect(res.body).toHaveProperty('message');
    }
    done();
  });
});
</code>```

答: Just had this error happen when deploying an app with mongoose to Heroku. I've set the environment variables with quotation marks and the problem went away when I removed them. Hope this helps.</p>

Body:
i am getting:

TypeError: Cannot read property 'split' of null

in error object from mongoose.connect, in CircleCI, and later on tests timeout, first one fails with 500 error.
It seems like mongo/mongoose error, am i doing something wrong with tests, i mean i am sure i do, since with simple non-async test i am not getting this error.
Btw, this works fine locally, no errors, just fails at CircleCI tests.

app.ts Database(mongoose) connect code:

mongoose
  .connect(mongoUrl, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useUnifiedTopology: true,
    useFindAndModify: false,
    dbName: 'expressing-space',
  })

  .then(() => {
    // console.log('MongoDB connected..');
  })
  .catch((err) => {
    console.log(
      'MongoDB connection error. Please make sure MongoDB is running. ' + err,
    );
  });

tests:

import request from 'supertest';
import mongoose from 'mongoose';
import app from '../src/app';

let token: string = '';
const email = 'x@x.com';
const password = '12345';

beforeAll((done) => {
  request(app)
    .post('/auth/login')
    .send({
      email,
      password,
    })
    .end((err, response) => {
      token = response.body.token;
      done();
    });
});

afterAll((done) => {
  // Closing the DB connection allows Jest to exit successfully.
  mongoose.connection.close();
  done();
});

describe('GET /likes/artists/', () => {
  // token not being sent - should respond with a 401
  it('should return require authorization - return 401', async (done) => {
    const res = await request(app)
      .get('/likes/artists/')
      .set('Content-Type', 'application/json');
    expect(res.status).toBe(401);
    done();
  });

  // send the token - should respond with a 200
  it('should respond with JSON data - 200', async (done) => {
    const res = await request(app)
      .get('/likes/artists/')
      .set('Authorization', `Bearer ${token}`)
      .set('Content-Type', 'application/json');
    expect(res.status).toBe(200);
    expect(res.type).toBe('application/json');
    done();
  });
});

describe('PUT /likes/artists/', () => {
  it('should return require authorization - return 401', async (done) => {
    const res = await request(app)
      .put('/likes/artists')
      .set('Content-Type', 'application/json');
    expect(res.status).toBe(401);
    done();
  });

  // #Todo: There is probalby better way to go about this. Re-check it!
  it('should return json data with either name prop for success or message prop for err', async (done) => {
    const name = 'dmx';
    const res = await request(app)
      .put('/likes/artists')
      .set('Authorization', `Bearer ${token}`)
      .set('Content-Type', 'application/json')
      .send({ name });

    if (res.status === 409) {
      expect(res.status).toBe(409);
      expect(res.body).toHaveProperty('message');
    } else if (res.status === 201) {
      expect(res.status).toBe(201);
      expect(res.body.artist).toHaveProperty('name');
    }
    done();
  });
});

// #Todo: There is probalby better way to go about this. Re-check it!
describe('DELETE /likes/artists/:artistId', () => {
  const artistId = '5e24d7350b68952acdcafc2e';
  it('should return require authorization - return 401', async (done) => {
    const res = await request(app).delete(`/likes/artists/${artistId}`);
    expect(res.status).toBe(401);
    done();
  });

  it('should delete userId from artist if it exists or return 404 if not', async (done) => {
    const res = await request(app)
      .delete(`/likes/artists/${artistId}`)
      .set('Authorization', `Bearer ${token}`);

    if (res.status === 404) {
      expect(res.status).toBe(404);
      expect(res.body).toHaveProperty('message');
    } else if (res.status === 202) {
      expect(res.status).toBe(202);
      expect(res.body).toHaveProperty('message');
    }
    done();
  });
});


问:
How to delete an element from a 2D Numpy array without knowing its position
I have a 2D array:
[[0,0], [0,1], [1,0], [1,1]]

I want to delete the [0,1] element without knowing its position within the array (as the elements may be shuffled).

Result should be:
[[0,0], [1,0], [1,1]]

I've tried using numpy.delete but keep getting back a flattened array:

```<code>>>> arr = np.array([[0,0], [0,1], [1,0], [1,1]])
>>> arr
array([[0, 0],
       [0, 1],
       [1, 0],
       [1, 1]])
>>> np.delete(arr, [0,1])
array([0, 1, 1, 0, 1, 1])
</code>```

Specifying the axis removes the 0, 1 elements rather than searching for the element (which makes sense):

```<code>>>> np.delete(arr, [0,1], axis=0)
array([[1, 0],
       [1, 1]])
</code>```

And trying to find the location (as has been suggested) seems equally problematic:

```<code>>>> np.where(arr==[0,1])
(array([0, 1, 1, 3]), array([0, 0, 1, 1]))
</code>```

(Where did that 3 come from?!?)

答:
```<code>mask = (arr==np.array([0,1])).all(axis=1)
arr1 = arr[~mask,:]
</code>```

Look at mask.. It should be [False, True,...].

Body:
I have a 2D array:
[[0,0], [0,1], [1,0], [1,1]]

I want to delete the [0,1] element without knowing its position within the array (as the elements may be shuffled).

Result should be:
[[0,0], [1,0], [1,1]]

I've tried using numpy.delete but keep getting back a flattened array:

>>> arr = np.array([[0,0], [0,1], [1,0], [1,1]])
>>> arr
array([[0, 0],
       [0, 1],
       [1, 0],
       [1, 1]])
>>> np.delete(arr, [0,1])
array([0, 1, 1, 0, 1, 1])

Specifying the axis removes the 0, 1 elements rather than searching for the element (which makes sense):

>>> np.delete(arr, [0,1], axis=0)
array([[1, 0],
       [1, 1]])

And trying to find the location (as has been suggested) seems equally problematic:

>>> np.where(arr==[0,1])
(array([0, 1, 1, 3]), array([0, 0, 1, 1]))

(Where did that 3 come from?!?)

Body:
mask = (arr==np.array([0,1])).all(axis=1)
arr1 = arr[~mask,:]

Look at mask.. It should be [False, True,...].


问:
powershell: remove characters in string
I have a list of files in this format NameSerie.S0E1.randomcharacters.mkv where i want to remove the randomcharacters to get NameSerie.S0E1.mkv

I have the following but for this i need to know the randomcharacters which sadly are random.

```<code>#rename files
Get-ChildItem $Location | Rename-Item -NewName {$_.Name.Replace("[480p]","") }
</code>```

Does someone have an idea?

答:
You could use

```<code>(.*?)[^.]+\.([^.]+)$
</code>```

And replace this with

```<code>$1$2
</code>```

See a demo on regex101.com.

Alternatively, you could split on the dot and glue the array back together programatically.

Title: powershell: remove characters in string

Body:
I have a list of files in this format NameSerie.S0E1.randomcharacters.mkv where i want to remove the randomcharacters to get NameSerie.S0E1.mkv

I have the following but for this i need to know the randomcharacters which sadly are random.

#rename files
Get-ChildItem $Location | Rename-Item -NewName {$_.Name.Replace("[480p]","") }

Does someone have an idea?

Body:
You could use

(.*?)[^.]+\.([^.]+)$

And replace this with

$1$2

See a demo on regex101.com.

Alternatively, you could split on the dot and glue the array back together programatically.


问:
Y-Axis with different colors
I have tried to add different colors to the Y-axis but without success.
Is it possible to achive something like attached image shows?

In the chartjs-plugin-annotation plugin you can set the background but not scale colors.

Describing image

        var config = {
            type: 'line',
            data: {
                labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
                datasets: [{
                    label: 'Dataset',
                    data: [1,2,3,4,5,6,7],
                    fill: false,
                }]
            },
            options: {
                responsive: true,
                scales: {
                    yAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'Colored scale'
                        },
                        gridLines: { color: ['rgba(255, 0, 0, 1)', 'rgba(0, 255, 0, 1)', 'rgba(0, 0, 255, 1)']  }
                    }]
                }
            }
        };

        window.onload = function () {
            var ctx = document.getElementById('canvas').getContext('2d');
            window.myLine = new Chart(ctx, config);
        };```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.bundle.min.js"></script>
</head>
<body>
    <div style="width:75%;"><canvas id="canvas"></canvas></div>
</body></code>```

答:
In case you want the colored rectangles spread over the entire chart, you can draw individual boxes of different background color using  chartjs-plugin-annotation.js.

new Chart(document.getElementById('canvas'), {
  type: 'line',
  data: {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
    datasets: [{
      label: 'Dataset',
      data: [1, 2, 3, 4, 5, 6, 7],
      fill: false,
      backgroundColor: 'rgb(0, 0, 0)',
      borderColor: 'rgb(0, 0, 0)'
    }]
  },
  options: {
    responsive: true,
    scales: {
      yAxes: [{
        display: true,
        scaleLabel: {
          display: true,
          labelString: 'Colored scale'
        }
      }]
    },
    annotation: {
      annotations: [{
          drawTime: "beforeDatasetsDraw",
          type: "box",
          xScaleID: "x-axis-0",
          yScaleID: "y-axis-0",
          yMin: 4.5,
          yMax: 8,
          backgroundColor: "rgba(255, 0, 0, 1)",
          borderWidth: 0
        },
        {
          drawTime: "beforeDatasetsDraw",
          type: "box",
          xScaleID: "x-axis-0",
          yScaleID: "y-axis-0",
          yMin: 3.5,
          yMax: 4.5,
          backgroundColor: "rgba(255, 165, 0, 1)",
          borderWidth: 0
        },
        {
          drawTime: "beforeDatasetsDraw",
          type: "box",
          xScaleID: "x-axis-0",
          yScaleID: "y-axis-0",
          xMin: 0,
          xMax: 100,
          yMin: 0,
          yMax: 3.5,
          backgroundColor: "rgba(50, 250, 50, 1)",
          borderWidth: 0
        }
      ]
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.js"></script>
<canvas id="canvas" height="90"></code>```

ContentLicense: CC BY-SA 3.0

Title: Y-Axis with different colors

Body:
I have tried to add different colors to the Y-axis but without success.
Is it possible to achive something like attached image shows?

In the chartjs-plugin-annotation plugin you can set the background but not scale colors.

Describing image

        var config = {
            type: 'line',
            data: {
                labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
                datasets: [{
                    label: 'Dataset',
                    data: [1,2,3,4,5,6,7],
                    fill: false,
                }]
            },
            options: {
                responsive: true,
                scales: {
                    yAxes: [{
                        display: true,
                        scaleLabel: {
                            display: true,
                            labelString: 'Colored scale'
                        },
                        gridLines: { color: ['rgba(255, 0, 0, 1)', 'rgba(0, 255, 0, 1)', 'rgba(0, 0, 255, 1)']  }
                    }]
                }
            }
        };

        window.onload = function () {
            var ctx = document.getElementById('canvas').getContext('2d');
            window.myLine = new Chart(ctx, config);
        };

<!DOCTYPE html>

<canvas id="canvas"></canvas>

Body:
In case you want the colored rectangles spread over the entire chart, you can draw individual boxes of different background color using  chartjs-plugin-annotation.js.

new Chart(document.getElementById('canvas'), {
  type: 'line',
  data: {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
    datasets: [{
      label: 'Dataset',
      data: [1, 2, 3, 4, 5, 6, 7],
      fill: false,
      backgroundColor: 'rgb(0, 0, 0)',
      borderColor: 'rgb(0, 0, 0)'
    }]
  },
  options: {
    responsive: true,
    scales: {
      yAxes: [{
        display: true,
        scaleLabel: {
          display: true,
          labelString: 'Colored scale'
        }
      }]
    },
    annotation: {
      annotations: [{
          drawTime: "beforeDatasetsDraw",
          type: "box",
          xScaleID: "x-axis-0",
          yScaleID: "y-axis-0",
          yMin: 4.5,
          yMax: 8,
          backgroundColor: "rgba(255, 0, 0, 1)",
          borderWidth: 0
        },
        {
          drawTime: "beforeDatasetsDraw",
          type: "box",
          xScaleID: "x-axis-0",
          yScaleID: "y-axis-0",
          yMin: 3.5,
          yMax: 4.5,
          backgroundColor: "rgba(255, 165, 0, 1)",
          borderWidth: 0
        },
        {
          drawTime: "beforeDatasetsDraw",
          type: "box",
          xScaleID: "x-axis-0",
          yScaleID: "y-axis-0",
          xMin: 0,
          xMax: 100,
          yMin: 0,
          yMax: 3.5,
          backgroundColor: "rgba(50, 250, 50, 1)",
          borderWidth: 0
        }
      ]
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.js"></script>
<canvas id="canvas" height="90">


问:
Hi smart people, i have problem with (many to many) assocation with sequelize orm
i have problem with (many to many) assocation with sequelize orm

In my case i have 3 tables

products,
categories,
products_categories

and here are assocation in nodeJS

```<code>Product.belongsToMany(Categories, {
  through: {
    model: ProductsCategories,
    as: 'products_categories',
  },
  foreignKey: "category_id"
})

Categories.belongsToMany(Product, {
  through: {
    model: ProductsCategories,
    as: 'products_categories',
  },
  foreignKey: "product_id"
})
</code>```

when i'm trying to fetch products with categories
sequelize not gives me back categories of the product

here are example

```<code> const products = await Product.findAll({
      include:{
        model:Categories,
        nested:true,
        through:{
            model: ProductsCategories,
            as: 'products_categories',
        }
      }
    });
</code>```

please help me understand where are my mistak ))

答:
Please correct your model definitions as:

```<code>Product.belongsToMany(Categories, {
  through: ProductsCategories,
  as: 'products_categories',
  foreignKey: "category_id"
})

Categories.belongsToMany(Product, {
  through: ProductsCategories,
  as: 'products_categories',
  foreignKey: "product_id"
})
</code>```

and findAll:

```<code> const products = await Product.findAll({
      include:{
        model:Categories,
        as: 'products_categories'
      }
    });
</code>```

Body:
i have problem with (many to many) assocation with sequelize orm

In my case i have 3 tables

products,
categories,
products_categories

and here are assocation in nodeJS

Product.belongsToMany(Categories, {
  through: {
    model: ProductsCategories,
    as: 'products_categories',
  },
  foreignKey: "category_id"
})

Categories.belongsToMany(Product, {
  through: {
    model: ProductsCategories,
    as: 'products_categories',
  },
  foreignKey: "product_id"
})

when i'm trying to fetch products with categories
sequelize not gives me back categories of the product

here are example

 const products = await Product.findAll({
      include:{
        model:Categories,
        nested:true,
        through:{
            model: ProductsCategories,
            as: 'products_categories',
        }
      }
    });

please help me understand where are my mistak ))

Body:
Please correct your model definitions as:

Product.belongsToMany(Categories, {
  through: ProductsCategories,
  as: 'products_categories',
  foreignKey: "category_id"
})

Categories.belongsToMany(Product, {
  through: ProductsCategories,
  as: 'products_categories',
  foreignKey: "product_id"
})

and findAll:

 const products = await Product.findAll({
      include:{
        model:Categories,
        as: 'products_categories'
      }
    });


问:
Python Tkinter and MySQL Error: AttributeError: 'NoneType' object has no attribute 'get'
I'm getting an error : AttributeError: 'NoneType' object has no attribute 'get'.

```<code>
def submit():
    a=e1.get()
    b=e2.get()
    import mysql.connector
    mydb = mysql.connector.connect(
      host="localhost",
      user="root",
      passwd="root",
      database="login"
    )
    sql="INSERT INTO log (name, password) VALUES (%s, %s)"
    val= (a,b)
    mycursor.execute(sql, val)
    mydb.commit()
    print(mycursor.rowcount, "record inserted")

form=Tk()
form.geometry("500x100")

name=Label(form,text="Enter Username").place(x=5,y=0)
e1=Entry(form).place(x=150,y=0)
password=Label(form,text="Enter Password").place(x=5,y=35)
e2=Entry(form).place(x=150,y=35)

submit=Button(form,text="Submit", command=submit).place(x=5,y=70)

form.mainloop()

</code>```

答:
You are calling the place function's output to the e1 and e2. Those function doesn't return anything and that's why your variable e1 and e2 are getting assinged as None.

You can change the e1 & e2 lines as below:

```<code>e1 = Entry(form)
e1.place(x=150,y=0)
</code>```

And Same for e2.

Body:
I'm getting an error : AttributeError: 'NoneType' object has no attribute 'get'.

def submit():
    a=e1.get()
    b=e2.get()
    import mysql.connector
    mydb = mysql.connector.connect(
      host="localhost",
      user="root",
      passwd="root",
      database="login"
    )
    sql="INSERT INTO log (name, password) VALUES (%s, %s)"
    val= (a,b)
    mycursor.execute(sql, val)
    mydb.commit()
    print(mycursor.rowcount, "record inserted")

form=Tk()
form.geometry("500x100")

name=Label(form,text="Enter Username").place(x=5,y=0)
e1=Entry(form).place(x=150,y=0)
password=Label(form,text="Enter Password").place(x=5,y=35)
e2=Entry(form).place(x=150,y=35)

submit=Button(form,text="Submit", command=submit).place(x=5,y=70)

form.mainloop()

Body:
You are calling the place function's output to the e1 and e2. Those function doesn't return anything and that's why your variable e1 and e2 are getting assinged as None.

You can change the e1 & e2 lines as below:

e1 = Entry(form)
e1.place(x=150,y=0)

And Same for e2.


问:
Why do I need a 'return' and a new variable?
I am a newbie in Python programming and I would like to understand better the logic of programming. The code below is intended to create a function that assigns its parameters to a dictionary, prompt the user about an artist and a title name, call the function back passing the arguments (given by the user) to the parameters and print the function (the dictionary).

```<code>def make_album(artist, album_name):
    entry = {'name' : artist, 'album' : album_name}
    return entry

while True:
    print("\nPlease, write your fav artist and title: ")
    print("\nType 'q' to quit.")
    band_name = input('Artist name: ')
    if band_name == 'q':
        break
    title_name = input('Title name: ')
    if title_name == 'q':
        break

comp_entry = make_album(band_name, title_name)
print(comp_entry)
</code>```

The code runs perfectly. But there are two points that I can not understand:

Why do I need the 'return entry' line? The function creates a dictionary and it is done. Why a return?

Why do I need to create a variable in the end, assign the result of the function and print it? There is already a variable (entry) addressed as the dictionary! I would like to just write instead:

```<code>make_album(band_name, title_name):
    print(entry)
</code>```

I know, the code will not run, but I would be very happy with some words explaining me the reason of why these 2 points.

答:
You can directly print the value this way too

```<code>print(make_album(band_name, title_name))
</code>```

The variable comp_entry is used to store the value returned from the make_album function. So, if you want a function to return back a value on calling the function, provide a return statement

It will print None if no return is provided.

Body:
I am a newbie in Python programming and I would like to understand better the logic of programming. The code below is intended to create a function that assigns its parameters to a dictionary, prompt the user about an artist and a title name, call the function back passing the arguments (given by the user) to the parameters and print the function (the dictionary).

def make_album(artist, album_name):
    entry = {'name' : artist, 'album' : album_name}
    return entry

while True:
    print("\nPlease, write your fav artist and title: ")
    print("\nType 'q' to quit.")
    band_name = input('Artist name: ')
    if band_name == 'q':
        break
    title_name = input('Title name: ')
    if title_name == 'q':
        break

comp_entry = make_album(band_name, title_name)
print(comp_entry)

The code runs perfectly. But there are two points that I can not understand:

Why do I need the 'return entry' line? The function creates a dictionary and it is done. Why a return?

Why do I need to create a variable in the end, assign the result of the function and print it? There is already a variable (entry) addressed as the dictionary! I would like to just write instead:

make_album(band_name, title_name):
    print(entry)

I know, the code will not run, but I would be very happy with some words explaining me the reason of why these 2 points.

Body:
You can directly print the value this way too

print(make_album(band_name, title_name))

The variable comp_entry is used to store the value returned from the make_album function. So, if you want a function to return back a value on calling the function, provide a return statement

It will print None if no return is provided.


问:
When using TypeScript in Visual Studio Code, how do I configure TS warnings to be shown as errors?
For example, this example

```<code>async function a() { await null; }
</code>```

has a small warning on await in VS Code

```<code>'await' has no effect on the type of this expression. ts(80007)
</code>```

How do I make that warning behave like an error in VS Code and tsc (be more visible, fail compilation)?

答:
In order for tsc to treat this as an error, there would need to be a compiler flag that you could set pertaining to async-await which I wasn't able to find looking through their docs.

There is, however, a linting rule (assuming you have eslint set up) which would cause your linter to complain in precisely this situation. See the eslint docs for an explanation of how it works.

All of that said, if you really want this behavior specifically. I think you could edit the category of this diagnostic message to be "Error" in your node_modules for typescript. That approach feels a bit brittle to me so I would definitely encourage the linter approach!

As far as integrating eslint with VSCode, there is a plugin which should integrate the linting warnings directly into the editor. I suspect you can add this to your VScode directly from their marketplace from within VSCode itself.

Body:
For example, this example

async function a() { await null; }

has a small warning on await in VS Code

'await' has no effect on the type of this expression. ts(80007)

How do I make that warning behave like an error in VS Code and tsc (be more visible, fail compilation)?


问:
how to efficiently find if a linux directory including sudirectories has at least 1 file
In my project various jobs are created as files in directories inside subdirectories.
But usually the case is I find that the jobs are mostly in some dirs and not in the most others

currently I use

```<code>find $DIR -type f | head -n 1
</code>```

to know if the directory has atleast 1 file , but this is a waste

how to efficiently  find if a linux directory including sudirectories  has at least 1 file

答:
Your code is already efficient, but perhaps the reason is not obvious.  When you pipe the output of find to head -n 1 you probably assume that find lists all the files and then head discards everything after the first one.  But that's not quite what head does.

When find lists the first file, head will print it, but when find lists the second file, head will terminate itself, which sends SIGPIPE to find because the pipe between them is closed.  Then find will stop running, because the default signal handler for SIGPIPE terminates the program which receives it.

So the cost of your pipelined commands is only the cost of finding two files, not the cost of finding all files.  For most obvious use cases this should be good enough.

Body:
In my project various jobs are created as files in directories inside subdirectories.
But usually the case is I find that the jobs are mostly in some dirs and not in the most others

currently I use

find $DIR -type f | head -n 1

to know if the directory has atleast 1 file , but this is a waste

how to efficiently  find if a linux directory including sudirectories  has at least 1 file


问:
Parse multilingual json file into C# dictionary
How do I read into a C# dictionary, a multilingual json lexicon in the form:

```<code>[{
  "Top": {
    "de-DE": "Oben",
    "fr-FR": "haut"
  }
},    {
  "Football": {
    "de-DE": "Fußball",
  },
},
{
  "Taxi": {
  }
}]
</code>```

In the json file there is a key, and for each supported language, a property and value. Where the word in the target language is the same as the key, there is no property for that language under that key in the json file.

At startup we load into a C# dictionary only those entries for the user language. In this snippet, the dictionary for German should be

```<code>Top, Oben
Football, Fußball
Taxi, Taxi
</code>```

In French

```<code>Top, Haut
Football, Football,
Taxi, Taxi
</code>```

How do I read the json file into a C# dictionary? The dictionary is not huge ... hundreds rather than millions of entries, so performance is not critical.

答:
The types

```<code>public class LocalizationInfo : Dictionary<string, string>
{
    public LocalizationInfo() : base( StringComparer.InvariantCultureIgnoreCase ) { }
}

public class LocalizationItem : Dictionary<string, LocalizationInfo>
{ }

public class LocalizationCollection : List<LocalizationItem>
{
    public Dictionary<string, string> GetLocalizedDict( string cultureName )
    {
        if ( cultureName is null )
        {
            throw new ArgumentNullException( nameof( cultureName ) );
        }

        return this
            .Where( e => e.Count == 1 )
            .Select( e => e.First() )
            .ToDictionary( e => e.Key, e => e.Value == null ? e.Key : e.Value.TryGetValue( cultureName, out var localizedValue ) ? localizedValue : e.Key );
    }

    public Dictionary<string, string> GetLocalizedDict( CultureInfo cultureInfo )
    {
        if ( cultureInfo is null )
        {
            throw new ArgumentNullException( nameof( cultureInfo ) );
        }

        return GetLocalizedDict(cultureInfo.Name);
    }

    public Dictionary<string, string> GetLocalizedDict(  )
    {
        return GetLocalizedDict( CultureInfo.CurrentCulture );
    }
}
</code>```

and the use case

```<code>class Program
{
    static readonly string _json =
        "[{" + Environment.NewLine +
        "  \"Top\": {" + Environment.NewLine +
        "    \"de-DE\": \"Oben\"," + Environment.NewLine +
        "    \"fr-FR\": \"haut\"" + Environment.NewLine +
        "  }" + Environment.NewLine +
        "},    {" + Environment.NewLine +
        "  \"Football\": {" + Environment.NewLine +
        "    \"de-DE\": \"Fußball\"" + Environment.NewLine +
        "  }" + Environment.NewLine +
        "}," + Environment.NewLine +
        "{" + Environment.NewLine +
        "  \"Taxi\": {" + Environment.NewLine +
        "  }" + Environment.NewLine +
        "}]";

    static void Main( string[] args )
    {
        var data = JsonSerializer.Deserialize<LocalizationCollection>( _json );

        var frDict = data.GetLocalizedDict( "fr-fr" );
        var deDict = data.GetLocalizedDict( "de-de" );

        var dict = data.GetLocalizedDict();
    }
}
</code>```

and a live example

BTW

I had choosen a structure like this

```<code>{
  "Top": {
    "de-DE": "Oben",
    "fr-FR": "haut"
  },
  "Football": {
    "de-DE": "Fußball"
  },
  "Taxi": {}
}
</code>```

There is no need for an array with objects which only contain a single property.

Body:
How do I read into a C# dictionary, a multilingual json lexicon in the form:

[{
  "Top": {
    "de-DE": "Oben",
    "fr-FR": "haut"
  }
},    {
  "Football": {
    "de-DE": "Fußball",
  },
},
{
  "Taxi": {
  }
}]

In the json file there is a key, and for each supported language, a property and value. Where the word in the target language is the same as the key, there is no property for that language under that key in the json file.

At startup we load into a C# dictionary only those entries for the user language. In this snippet, the dictionary for German should be

Top, Oben
Football, Fußball
Taxi, Taxi

In French

Top, Haut
Football, Football,
Taxi, Taxi

How do I read the json file into a C# dictionary? The dictionary is not huge ... hundreds rather than millions of entries, so performance is not critical.

Body:
The types

public class LocalizationInfo : Dictionary<string, string>
{
    public LocalizationInfo() : base( StringComparer.InvariantCultureIgnoreCase ) { }
}

public class LocalizationItem : Dictionary<string, LocalizationInfo>
{ }

public class LocalizationCollection : List<LocalizationItem>
{
    public Dictionary<string, string> GetLocalizedDict( string cultureName )
    {
        if ( cultureName is null )
        {
            throw new ArgumentNullException( nameof( cultureName ) );
        }

        return this
            .Where( e => e.Count == 1 )
            .Select( e => e.First() )
            .ToDictionary( e => e.Key, e => e.Value == null ? e.Key : e.Value.TryGetValue( cultureName, out var localizedValue ) ? localizedValue : e.Key );
    }

    public Dictionary<string, string> GetLocalizedDict( CultureInfo cultureInfo )
    {
        if ( cultureInfo is null )
        {
            throw new ArgumentNullException( nameof( cultureInfo ) );
        }

        return GetLocalizedDict(cultureInfo.Name);
    }

    public Dictionary<string, string> GetLocalizedDict(  )
    {
        return GetLocalizedDict( CultureInfo.CurrentCulture );
    }
}

and the use case

class Program
{
    static readonly string _json =
        "[{" + Environment.NewLine +
        "  \"Top\": {" + Environment.NewLine +
        "    \"de-DE\": \"Oben\"," + Environment.NewLine +
        "    \"fr-FR\": \"haut\"" + Environment.NewLine +
        "  }" + Environment.NewLine +
        "},    {" + Environment.NewLine +
        "  \"Football\": {" + Environment.NewLine +
        "    \"de-DE\": \"Fußball\"" + Environment.NewLine +
        "  }" + Environment.NewLine +
        "}," + Environment.NewLine +
        "{" + Environment.NewLine +
        "  \"Taxi\": {" + Environment.NewLine +
        "  }" + Environment.NewLine +
        "}]";

    static void Main( string[] args )
    {
        var data = JsonSerializer.Deserialize<LocalizationCollection>( _json );

        var frDict = data.GetLocalizedDict( "fr-fr" );
        var deDict = data.GetLocalizedDict( "de-de" );

        var dict = data.GetLocalizedDict();
    }
}

and a live example

BTW

I had choosen a structure like this

{
  "Top": {
    "de-DE": "Oben",
    "fr-FR": "haut"
  },
  "Football": {
    "de-DE": "Fußball"
  },
  "Taxi": {}
}

There is no need for an array with objects which only contain a single property.


问:
How could I print out the nth letter of the alphabet in Python?
ASCII math doesn't seem to work in Python:

'a' + 5
    DOESN'T WORK

How could I quickly print out the nth letter of the alphabet without having an array of letters?

My naive solution is this:

```
letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
print letters[5]
```

答:
if u want to go really out of the way (probably not very good) you could create a new class CharMath:

```<code>class CharMath:
    def __init__(self,char):
        if len(char) > 1: raise IndexError("Not a single character provided")
        else: self.char = char
    def __add__(self,num):
        if type(num) == int or type(num) == float: return chr(ord(self.char) + num)
        raise TypeError("Number not provided")
</code>```

The above can be used:

```<code>>>> CharMath("a") + 5
'f'
</code>```

ContentLicense: CC BY-SA 2.5

Body:
ASCII math doesn't seem to work in Python:

'a' + 5
    DOESN'T WORK

How could I quickly print out the nth letter of the alphabet without having an array of letters?

My naive solution is this:

letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
print letters[5]

Body:
if u want to go really out of the way (probably not very good) you could create a new class CharMath:

class CharMath:
    def __init__(self,char):
        if len(char) > 1: raise IndexError("Not a single character provided")
        else: self.char = char
    def __add__(self,num):
        if type(num) == int or type(num) == float: return chr(ord(self.char) + num)
        raise TypeError("Number not provided")

The above can be used:

>>> CharMath("a") + 5
'f'


问:
upgraded moodle 2.7.1 to php 7.0 and mysql 5.6. But unable to connect to mysql 8.0 if upgrading mysql
Moodle app is runnung with php 7 and mysql 5.6.

Whenm updating mysql version from 5.6 to 8.0.

Moodle does not connects to database for mysql 8.0

答:
Which version of PHP is it?

If you are using 7.1 then you'll need at least 7.1.16 or at least 7.2.4 for 7.2.

https://www.php.net/manual/en/mysqli.requirements.php

Is the new MySql 8 server using the same port?

Check the port by running this in MySql

```<code>SHOW GLOBAL VARIABLES LIKE 'PORT';
</code>```

The default in Moodle is 3306. If its different then you can change this in the config.php

```<code>$CFG->dboptions = array(
    'dbport' => 'yournewport'
);
</code>```

Upgrade Moodle 2.7

Finally, Moodle 2.7 is no longer supported. The last update was May 2017.

The recommended upgrade route is first upgrade to 2.7.20 then to 3.2.9 then to 3.8.x

https://docs.moodle.org/38/en/Upgrading

Body:
Which version of PHP is it?

If you are using 7.1 then you'll need at least 7.1.16 or at least 7.2.4 for 7.2.

https://www.php.net/manual/en/mysqli.requirements.php

Is the new MySql 8 server using the same port?

Check the port by running this in MySql

SHOW GLOBAL VARIABLES LIKE 'PORT';

The default in Moodle is 3306. If its different then you can change this in the config.php

$CFG->dboptions = array(
    'dbport' => 'yournewport'
);

Upgrade Moodle 2.7

Finally, Moodle 2.7 is no longer supported. The last update was May 2017.

The recommended upgrade route is first upgrade to 2.7.20 then to 3.2.9 then to 3.8.x

https://docs.moodle.org/38/en/Upgrading


问:
Do I need " ConfigurationChanges = ConfigChanges.ScreenSize .. " in the Android activity of a Xamarin Forms application?
I just installed Rg.Plugins.Popup into my application and in the wiki example I see that it has:

```<code>"ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)"

[Activity(Label = "X", MainLauncher = true,
    ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
</code>```

My current Activity is this:

```<code>[Activity(Label = "X", Theme = "@style/MainTheme", MainLauncher = false)]
</code>```

For an XF app is it important to have the additional entry for ConfigurationChanges in the activity?

答:
If you remove it and you rotate the device, it will probably re-create the activity, meaning your App will appear to restart on rotation. Hence it is a good idea to keep those configuration change flags.

There are other flags you can use as well for resizing of activities when the software keyboard appears on screen as well. You can read more about handling configuration changes on Android in their documentation.

Body:
I just installed Rg.Plugins.Popup into my application and in the wiki example I see that it has:

"ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)"

[Activity(Label = "X", MainLauncher = true,
    ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]

My current Activity is this:

[Activity(Label = "X", Theme = "@style/MainTheme", MainLauncher = false)]

For an XF app is it important to have the additional entry for ConfigurationChanges in the activity?


问:
Module not found while compiling in React
While trying to import the collection-preview.components.jsx file in the shop-page.jsx, there occurs an error saying:

```<code>"Module not found: Can't resolve '../../components/collection-preview/collection-preview'"
</code>```

URL of the code and the error is shared in the link:

I would like to know what am I missing here and why the files are not getting compiled.

答:
Your file called collection-preview.component but you import collection-preview, just change the name to collection-preview.component, it should work

You could also drop js and jsx ending for files when importing :)

Body:
While trying to import the collection-preview.components.jsx file in the shop-page.jsx, there occurs an error saying:

"Module not found: Can't resolve '../../components/collection-preview/collection-preview'"

URL of the code and the error is shared in the link:

I would like to know what am I missing here and why the files are not getting compiled.


问:
How to set up kaggle api in colab
I am uploading the kaggle.json file for every new session in Google Colab. Is there any way to permanently configure it using Google Drive.

答:
You can save kaggle.json in gdrive, mount it, then download from there.

You can also embed kaggle.json directly in Colab.

```<code>!mkdir ~/.kaggle
!echo '{"username":"korakot","key":"xxxxxxxxxxxxxxxx"}' > ~/.kaggle/kaggle.json
!chmod 600 ~/.kaggle/kaggle.json
</code>```

If your notebook is private(not shared), this is the most convenient way.

Title: How to set up kaggle api in colab

Body:
You can save kaggle.json in gdrive, mount it, then download from there.

You can also embed kaggle.json directly in Colab.

!mkdir ~/.kaggle
!echo '{"username":"korakot","key":"xxxxxxxxxxxxxxxx"}' > ~/.kaggle/kaggle.json
!chmod 600 ~/.kaggle/kaggle.json

If your notebook is private(not shared), this is the most convenient way.


问:
How to get correct day number in my country?
I'm using date('j') function in calendar. The problem is that it returns not correct day. For example in my country today is day 17 and this function return day 16. How to fix this?

答:
By default date returns the date and time based on the server's time. Check out the output to the following:

```<code><?php
echo date(DATE_RSS);
?>
</code>```

This will tell you the current exact time and date that the sever is set to.

Remember, the server is a computer just like your own - only it is probably located somewhere half-way around the world. Just as your computer's clock is set to the local time where your are located, the server's clock is probably set to the local time where it is located.

However, you can use date_default_timezone_set in PHP to set the time and date you want to use in a script. This will change the default timezone used in that script.

Body:
By default date returns the date and time based on the server's time. Check out the output to the following:

<?php
echo date(DATE_RSS);
?>

This will tell you the current exact time and date that the sever is set to.

Remember, the server is a computer just like your own - only it is probably located somewhere half-way around the world. Just as your computer's clock is set to the local time where your are located, the server's clock is probably set to the local time where it is located.

However, you can use date_default_timezone_set in PHP to set the time and date you want to use in a script. This will change the default timezone used in that script.


问:
Can you get the response data from Volley outside of the stringRequest variable in Kotlin?
I want to get the Volley stringRequest response from my website outside of the variable.

```<code>val queue = Volley.newRequestQueue(this)
val url = ""

// Request a string response from the provided URL.
val stringRequest = StringRequest(
    Request.Method.GET, url,
    Response.Listener<String> { response ->
        var obj = JSONObject(response) <-- cant access this variable outside of stringRequest
    },
    Response.ErrorListener { textView3.text = "That didn't work!" })

stringRequest.body.toString() <-- cant covert null to string

stringRequest.headers.toString() <-- output is {}

//here i want to do something like

if (response == "True") {
    //do something
}
</code>```

On the website that I'm accessing there is nothing more than {"check":"True"}

答:
This implementation is asynchronous in the way its built in, What you actually can do to look it more like synchronous is if you use coroutines in your project, You can use suspendCoroutine, see
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/suspend-coroutine.html

Example:

```<code>suspend fun getData(url: String) = suspendCoroutine<String?> { cont ->
    val queue = Volley.newRequestQueue(this)

    val stringRequest = StringRequest(Request.Method.GET, url,
        Response.Listener<String> { response ->
            cont.resume(response)
        },
        Response.ErrorListener { cont.resume(null) })

    queue.add(stringRequest)
}
</code>```

Now you can access the response string out of Response.Listener()

Edit: Additionally you can do cont.resumeWithException(e) instead if you dont want to return nullable expression and check nullability every time you use this function.

Body:
I want to get the Volley stringRequest response from my website outside of the variable.

val queue = Volley.newRequestQueue(this)
val url = ""

// Request a string response from the provided URL.
val stringRequest = StringRequest(
    Request.Method.GET, url,
    Response.Listener<String> { response ->
        var obj = JSONObject(response) <-- cant access this variable outside of stringRequest
    },
    Response.ErrorListener { textView3.text = "That didn't work!" })

stringRequest.body.toString() <-- cant covert null to string

stringRequest.headers.toString() <-- output is {}

//here i want to do something like

if (response == "True") {
    //do something
}

On the website that I'm accessing there is nothing more than {"check":"True"}

Body:
This implementation is asynchronous in the way its built in, What you actually can do to look it more like synchronous is if you use coroutines in your project, You can use suspendCoroutine, see
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines.experimental/suspend-coroutine.html

Example:

suspend fun getData(url: String) = suspendCoroutine<String?> { cont ->
    val queue = Volley.newRequestQueue(this)

    val stringRequest = StringRequest(Request.Method.GET, url,
        Response.Listener<String> { response ->
            cont.resume(response)
        },
        Response.ErrorListener { cont.resume(null) })

    queue.add(stringRequest)
}

Now you can access the response string out of Response.Listener()

Edit: Additionally you can do cont.resumeWithException(e) instead if you dont want to return nullable expression and check nullability every time you use this function.


问:
computed locals from variable in terraform v12 syntax
I am trying to create a computed local from a variable.

Is this syntax correct?

If I call for_each = locals.db_services in a resource, will terraform automatically add it to the dependency graph?

```<code>variable "services" {
    type = list(object)
}

locals {
    db_services = {
        for service in var.services:
        service.name => service
        if index(lookup(service, "storage", []), "postgres") > 0 && service.cluster == "service"
    }
}

resource "aws_ecs_task_definition" "rds_dump_task" {
  for_each = local.db_services

  family                = format("rds-dump-task-%s-%s", each.value.name, var.environment)
  container_definitions = data.template_file.container_definition[each.key].rendered
  task_role_arn         = format("arn:aws:iam::%s:role/%s-ecs-task-%s",
    var.account_id,
    each.value.name,
    var.environment
  )
}

</code>```

答:
The syntax works!
Also, var.services is stored in .json.tf file format and it works very nicely.</p>

Body:
I am trying to create a computed local from a variable.

Is this syntax correct?

If I call for_each = locals.db_services in a resource, will terraform automatically add it to the dependency graph?

variable "services" {
    type = list(object)
}

locals {
    db_services = {
        for service in var.services:
        service.name => service
        if index(lookup(service, "storage", []), "postgres") > 0 && service.cluster == "service"
    }
}

resource "aws_ecs_task_definition" "rds_dump_task" {
  for_each = local.db_services

  family                = format("rds-dump-task-%s-%s", each.value.name, var.environment)
  container_definitions = data.template_file.container_definition[each.key].rendered
  task_role_arn         = format("arn:aws:iam::%s:role/%s-ecs-task-%s",
    var.account_id,
    each.value.name,
    var.environment
  )
}


问:
Using Cloudfront to expose ElasticSearch REST API in read only (GET/HEAD)
I want to let my clients speak directly with ElasticSearch REST API, obviously preventing them from performing any data or configuration change.

I had a look at ElasticSearch REST interface and I noticed the pattern: HTTP GET requests are pretty safe (harmless queries and status of cluster).

So I thought I can use Cloudfront as a CDN/Proxy that only allows GET/HEAD methods (you can impose such restrict it in the main configuration).

So far so good, all is set up. But things don't work because I would need to open my EC2 security group to the world in order to be reachable from Cloudfront! I don't want this, really!

When I use EC2 with RDS, I can simply allow access to my EC2 security group in RDS security groups. Why can't I do this with CloudFront? Or can I?

Ideas?

edit: It's not documented, but ES accepts facets query, which involve a (JSON) body, not only with POST, but also with GET. This simply breaks HTTP recommendation (as for RFC3616) by not ignoring the body for GET request (source).
This relates because, as pointed out, exposing ES REST interface directly can lead to easy DOS attacks using complex queries. I'm still convinced though, having one less proxy is still worth it.

edit: Other option for me would be to skip CloudFront and adding a security layer as an ElasticSearch plugin as shown here

答:
A way to do this in AWS would be:

Set up an Application Load Balancer in front of your ES cluster. Create a TLS cert for the ALB and serve https. Open the ES security group to the ALB.

Set up CloudFront and use the ALB as origin. Pass a custom header with a secret value (for WAF, see next point).

Set up WAF on your ALB to only allow requests that contain the custom header with the secret value. Now all requests have to go through CloudFront.

Set up a Lambda@Edge function on your CloudFront distribution to either remove the body from GET requests, or DENY such requests.

It’s quite some work, but there’s advantages over the plugin, e.g.:

CloudFront comes with free network DDOS protection

CloudFront gives your users lower latency to ES because of the fast CloudFront network and global PoP’s.

Opens many options to use CloudFront, WAF and Lamba@Edge to further protect your ES cluster.

I’m working on sample code in CDK to set all of this up. Will report back when that’s ready.


问:
Open specific tab with  and save to localStorage
I have a table whose current value is stored in localStorage (see JSfiddle). How do I set up a link in href> to open the desired table, e.g. second in order?

For example: I'm on the Home page and clicking href> redirects me to the List page, where tab Teacher is opened, and this option is also saved to localStorage (that is, when the List page is refreshed, the Teacher tab remains open).

Thank you!

答:
If I understand correctly, you want to create a link to an HTML page, which, on that page, there are various options for a current tab to be selected, and you want, that when someone clicks on a particular link, that tab will already be open.

Am I right?

If so, then let's do the following.

If you're setting the value when the page loads based on localStorage, then by definition it will only open that which was opened last.

So the question is how do you make the particular link open only one tab, and another link open the other? It seems from your example that you want a link to the "student" tab and a separate link to the "teacher" tab.

To do this just with client side JavaScript, you can use the window location hash, and read it with JavaScript, and do the respective function based on the hash value.

Say you have some URL like example.com, which brings you to a default tab. Then, if you want a link to a non default tab, simply add something to the end of the URL preceded by a "#" symbol, then you can read it in JavaScript with location.hash

So the new URL may look like: example.com/#teacher, then somewhere in your page with JavaScript, do:

```<code>var page = location.hash //== "#teacher"
    activateTab(page.replace("#", "")); //activates "teacher" tab, assuming that function would do something, but you get the idea
</code>```

Title: Open specific tab with <a href> and save to localStorage

Body:
I have a table whose current value is stored in localStorage (see JSfiddle). How do I set up a link in  to open the desired table, e.g. second in order?

For example: I'm on the Home page and clicking  redirects me to the List page, where tab Teacher is opened, and this option is also saved to localStorage (that is, when the List page is refreshed, the Teacher tab remains open).

Thank you!

Body:
If I understand correctly, you want to create a link to an HTML page, which, on that page, there are various options for a current tab to be selected, and you want, that when someone clicks on a particular link, that tab will already be open.

Am I right?

If so, then let's do the following.

If you're setting the value when the page loads based on localStorage, then by definition it will only open that which was opened last.

So the question is how do you make the particular link open only one tab, and another link open the other? It seems from your example that you want a link to the "student" tab and a separate link to the "teacher" tab.

To do this just with client side JavaScript, you can use the window location hash, and read it with JavaScript, and do the respective function based on the hash value.

Say you have some URL like example.com, which brings you to a default tab. Then, if you want a link to a non default tab, simply add something to the end of the URL preceded by a "#" symbol, then you can read it in JavaScript with location.hash

So the new URL may look like: example.com/#teacher, then somewhere in your page with JavaScript, do:

var page = location.hash //== "#teacher"
    activateTab(page.replace("#", "")); //activates "teacher" tab, assuming that function would do something, but you get the idea


问:
Joining records of a Python dictionary (read from JSON) depending on key values and adjust the values of the remaining keys
I produce a JSON file out of a web service I have no control of, and the result is approximately like this:

```<code>{
      "steps": [
        {
          "start_station": "TOYOCHO",
          "end_station": "NIHOMBASHI",
          "start_time": 1598317440.0,
          "end_time": 1598317920.0,
          "duration": 8,
          "train_name": "Tokyo Metro Tozai Line Rapid\u00a0for\u00a0NAKANO",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        },
        {
          "start_station": "NIHOMBASHI",
          "end_station": "OSHIAGE",
          "start_time": 1598318340.0,
          "end_time": 1598319000.0,
          "duration": 11,
          "train_name": "Toei Subway Asakusa Line\u00a0for\u00a0NARITA AIRPORT TERMINAL 1",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        },
        {
          "start_station": "OSHIAGE",
          "end_station": "AOTO",
          "start_time": 1598319120.0,
          "end_time": 1598319420.0,
          "duration": 5,
          "train_name": "Line name change, train goes through",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        },
        {
          "start_station": "AOTO",
          "end_station": "KEISEI-TAKASAGO",
          "start_time": 1598319480.0,
          "end_time": 1598319600.0,
          "duration": 2,
          "train_name": "Line name change, train goes through",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        },
        {
          "start_station": "KEISEI-TAKASAGO",
          "end_station": "SHIBAMATA",
          "start_time": 1598320080.0,
          "end_time": 1598320260.0,
          "duration": 3,
          "train_name": "Keisei Kanamachi Line\u00a0for\u00a0KEISEI-KANAMACHI",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        }
</code>```

Now, I'm reading this as a dictionary with simplejson and I need to remove all the steps where train_name is "Line name change, train goes through", but I need to take into account the fact that they exist.

In other words:

No "train goes through" records should be removed from the final result;

The first record after "train goes through", shoud have the "start_station" field changed to the previous "end_station" of the preceding non-"train goes through" record.

The "end_station" before a "train goes through" entry should be put as the "start_station" of the first following non-"train goes through" entry.

Do the same for "start_time", "end_time"

IOW, if I output the modified JSON, this is what I should expect:

```<code>{
      "steps": [
        {
          "start_station": "TOYOCHO",
          "end_station": "NIHOMBASHI",
          "start_time": 1598317440.0,
          "end_time": 1598317920.0,
          "duration": 8,
          "train_name": "Tokyo Metro Tozai Line Rapid\u00a0for\u00a0NAKANO",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        },
        {
          "start_station": "NIHOMBASHI",
          "end_station": "KEISEI-TAKASAGO",
          "start_time": 1598318340.0,
          "end_time": 1598319600.0,
          "duration": 11, # Will get recalculated
          "train_name": "Toei Subway Asakusa Line\u00a0for\u00a0NARITA AIRPORT TERMINAL 1",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null,
        }
        {
          "start_station": "KEISEI-TAKASAGO",
          "end_station": "SHIBAMATA",
          "start_time": 1598320080.0,
          "end_time": 1598320260.0,
          "duration": 3,
          "train_name": "Keisei Kanamachi Line\u00a0for\u00a0KEISEI-KANAMACHI",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        }
</code>```

The number of "goes through" can be anything, so I can't expect a specific length.

Currently I'm iterating record by record as I need to do some processing:

```<code>import simplejson as json

with open("results.json", "r") as handle:
    data = json.load(handle)

for step in data["steps"]:
    # Process stuff

</code>```

Hence why I'm stuck, because I got lost trying to keep track of the previous "non go through" record.

Is there a non-hacky solution? Note that I also avoid iterating over the dictionary if need be. What I can't do is changing the data (I can add a field to the JSON saying it's a "go through", but no more than that).

Also apologies for the perhaps poorly-worded title, but it's hard to describe in a few words what I mean.

答:
This is what worked for me: I'm not marking at accepted as I'm sure there are better ways to do it. I ended up using peekable from more_itertools to inspect the next record. I also added a go_through field to the JSON (that I can do) to point which records are to be merged.

So I applied the following logic:

If the current record is not a "go through" record and the next one isn't either, handle it normally

If the current record is not a "go through" but the next one is, store away the important bits (start and time, most importantly) and skip the rest of the processing

If the current record is a "go through" but the next one isn't, note down the end place and time and combine them from the previously stored record to generate a "merged" record.

If both the current and the next record are "go through" (can happen), don't do anything and skip to the next iteration

```<code>import more_itertools as mlt

iter_records = mlt.peekable(record["steps"])
previous_record = None

for record in iter_records:

    # Extract some stuff from the data
    # Unrelated to the actual problem
    parsed = _parse_record(record)
    start_station, start_date, start_time, *rest = parsed
    end_station, end_date, end_time, *rest = rest
    train_type, train_number = rest
    # Doesn't raise StopIteration with a default value set
    next_record = iter_records.peek(None)

    if next_record is not None:

        if not record["go_through"] and next_record["go_through"]:
            # Next one is going through: set the start,
            # but don't add anything
            previous_record = record
            continue
        elif not next_record["go_through"] and record["go_through"]:
            # The next one is a "real" one, set the end, and
            # use the previous non-go-through record to extract the data
            parsed = _parse_record(previous_record)
            start_station, start_date, start_time, *_ = parsed
            *_, train_type, train_number = parsed
            previous_record = None
        elif record["go_through"] and next_record["go_through"]:
            # Nothing useful, skip processing
            continue
        # More processing....
</code>```

Body:
I produce a JSON file out of a web service I have no control of, and the result is approximately like this:

{
      "steps": [
        {
          "start_station": "TOYOCHO",
          "end_station": "NIHOMBASHI",
          "start_time": 1598317440.0,
          "end_time": 1598317920.0,
          "duration": 8,
          "train_name": "Tokyo Metro Tozai Line Rapid\u00a0for\u00a0NAKANO",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        },
        {
          "start_station": "NIHOMBASHI",
          "end_station": "OSHIAGE",
          "start_time": 1598318340.0,
          "end_time": 1598319000.0,
          "duration": 11,
          "train_name": "Toei Subway Asakusa Line\u00a0for\u00a0NARITA AIRPORT TERMINAL 1",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        },
        {
          "start_station": "OSHIAGE",
          "end_station": "AOTO",
          "start_time": 1598319120.0,
          "end_time": 1598319420.0,
          "duration": 5,
          "train_name": "Line name change, train goes through",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        },
        {
          "start_station": "AOTO",
          "end_station": "KEISEI-TAKASAGO",
          "start_time": 1598319480.0,
          "end_time": 1598319600.0,
          "duration": 2,
          "train_name": "Line name change, train goes through",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        },
        {
          "start_station": "KEISEI-TAKASAGO",
          "end_station": "SHIBAMATA",
          "start_time": 1598320080.0,
          "end_time": 1598320260.0,
          "duration": 3,
          "train_name": "Keisei Kanamachi Line\u00a0for\u00a0KEISEI-KANAMACHI",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        }

Now, I'm reading this as a dictionary with simplejson and I need to remove all the steps where train_name is "Line name change, train goes through", but I need to take into account the fact that they exist.

In other words:

No "train goes through" records should be removed from the final result;

The first record after "train goes through", shoud have the "start_station" field changed to the previous "end_station" of the preceding non-"train goes through" record.

The "end_station" before a "train goes through" entry should be put as the "start_station" of the first following non-"train goes through" entry.

Do the same for "start_time", "end_time"

IOW, if I output the modified JSON, this is what I should expect:

{
      "steps": [
        {
          "start_station": "TOYOCHO",
          "end_station": "NIHOMBASHI",
          "start_time": 1598317440.0,
          "end_time": 1598317920.0,
          "duration": 8,
          "train_name": "Tokyo Metro Tozai Line Rapid\u00a0for\u00a0NAKANO",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        },
        {
          "start_station": "NIHOMBASHI",
          "end_station": "KEISEI-TAKASAGO",
          "start_time": 1598318340.0,
          "end_time": 1598319600.0,
          "duration": 11, # Will get recalculated
          "train_name": "Toei Subway Asakusa Line\u00a0for\u00a0NARITA AIRPORT TERMINAL 1",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null,
        }
        {
          "start_station": "KEISEI-TAKASAGO",
          "end_station": "SHIBAMATA",
          "start_time": 1598320080.0,
          "end_time": 1598320260.0,
          "duration": 3,
          "train_name": "Keisei Kanamachi Line\u00a0for\u00a0KEISEI-KANAMACHI",
          "is_transfer": false,
          "start_track_number": null,
          "end_track_number": null
        }

The number of "goes through" can be anything, so I can't expect a specific length.

Currently I'm iterating record by record as I need to do some processing:

import simplejson as json

with open("results.json", "r") as handle:
    data = json.load(handle)

for step in data["steps"]:
    # Process stuff

Hence why I'm stuck, because I got lost trying to keep track of the previous "non go through" record.

Is there a non-hacky solution? Note that I also avoid iterating over the dictionary if need be. What I can't do is changing the data (I can add a field to the JSON saying it's a "go through", but no more than that).

Also apologies for the perhaps poorly-worded title, but it's hard to describe in a few words what I mean.

Body:
This is what worked for me: I'm not marking at accepted as I'm sure there are better ways to do it. I ended up using peekable from more_itertools to inspect the next record. I also added a go_through field to the JSON (that I can do) to point which records are to be merged.

So I applied the following logic:

If the current record is not a "go through" record and the next one isn't either, handle it normally

If the current record is not a "go through" but the next one is, store away the important bits (start and time, most importantly) and skip the rest of the processing

If the current record is a "go through" but the next one isn't, note down the end place and time and combine them from the previously stored record to generate a "merged" record.

If both the current and the next record are "go through" (can happen), don't do anything and skip to the next iteration

import more_itertools as mlt

iter_records = mlt.peekable(record["steps"])
previous_record = None

for record in iter_records:

    # Extract some stuff from the data
    # Unrelated to the actual problem
    parsed = _parse_record(record)
    start_station, start_date, start_time, *rest = parsed
    end_station, end_date, end_time, *rest = rest
    train_type, train_number = rest
    # Doesn't raise StopIteration with a default value set
    next_record = iter_records.peek(None)

    if next_record is not None:

        if not record["go_through"] and next_record["go_through"]:
            # Next one is going through: set the start,
            # but don't add anything
            previous_record = record
            continue
        elif not next_record["go_through"] and record["go_through"]:
            # The next one is a "real" one, set the end, and
            # use the previous non-go-through record to extract the data
            parsed = _parse_record(previous_record)
            start_station, start_date, start_time, *_ = parsed
            *_, train_type, train_number = parsed
            previous_record = None
        elif record["go_through"] and next_record["go_through"]:
            # Nothing useful, skip processing
            continue
        # More processing....


问:
How to Query value and filter data with value only?
I am using a query formula to import data from a different sheet. However, after querying the data, I only need it to show data with value only. How to remove data without value when I query?

My query formula is the following:

```<code>=QUERY(Paste!A:G,"SELECT A,B,C,D WHERE B ='"&$C$6&"' or B ='"&$C$7&"' or B ='"&$C$8&"' or B ='"&$C$9&"' or B ='"&$C$10&"' or B ='"&$C$11&"' ORDER BY D DESC")
</code>```

My spreadsheet link is the following:

https://docs.google.com/spreadsheets/d/1A6lGIlU147Y_0WFD7Btkq4IMuY-Z3D1HsNiTgjLjm0o/edit?usp=sharing

At above image can see data without value also showing. I want to Query data with value only.

Body:
I am using a query formula to import data from a different sheet. However, after querying the data, I only need it to show data with value only. How to remove data without value when I query?

My query formula is the following:

=QUERY(Paste!A:G,"SELECT A,B,C,D WHERE B ='"&$C$6&"' or B ='"&$C$7&"' or B ='"&$C$8&"' or B ='"&$C$9&"' or B ='"&$C$10&"' or B ='"&$C$11&"' ORDER BY D DESC")

My spreadsheet link is the following:

https://docs.google.com/spreadsheets/d/1A6lGIlU147Y_0WFD7Btkq4IMuY-Z3D1HsNiTgjLjm0o/edit?usp=sharing

At above image can see data without value also showing. I want to Query data with value only.

Body:
use:

=QUERY(Paste!A:G,
 "select A,B,C,D
  where D <> 0
    and D is not null
    and (B ='"&$C$6&"'
     or B ='"&$C$7&"'
     or B ='"&$C$8&"'
     or B ='"&$C$9&"'
     or B ='"&$C$10&"'
     or B ='"&$C$11&"')
  order by D desc")


问:
Using codable with value that is sometimes an Int and other times a String
I have an API that will sometimes return a specific key value (in this case id) in the JSON as an Int and other times it will return that same key value as a String. How do I use codable to parse that JSON?

```<code>struct GeneralProduct: Codable {
    var price: Double!
    var id: String?
    var name: String!

    private enum CodingKeys: String, CodingKey {
        case price = "p"
        case id = "i"
        case name = "n"
    }

    init(price: Double? = nil, id: String? = nil, name: String? = nil) {
        self.price = price
        self.id = id
        self.name = name
    }
}
</code>```

I keep getting this error message: Expected to decode String but found a number instead. The reason that it returns a number is because the id field is empty and when the id field is empty it defaults to returning 0 as an ID which codable identifies as a number. I can basically ignore the ID key but codable does not give me the option to ignore it to my knowledge. What would be the best way to handle this?

Here is the JSON. It is super simple

Working

```<code>{
  "p":2.12,
  "i":"3k3mkfnk3",
  "n":"Blue Shirt"
}
</code>```

Error - because there is no id in the system, it returns 0 as a default which codable obviously sees as a number opposed to string.

```<code>{
  "p":2.19,
  "i":0,
  "n":"Black Shirt"
}
</code>```

答:
Seamlessly decoding from either Int or String into the same property requires writing some code.

However, thanks to a (somewhat) new addition to the language,(property wrappers), you can make it quite easy to reuse this logic wherever you need it:

// note this is only `Decodable`
struct GeneralProduct: Decodable {
    var price: Double
    @Flexible var id: Int // note this is an Int
    var name: String
}
```
<p>The property wrapper and its supporting code can be implemented like this:</p>
<pre class="lang-swift prettyprint-override"><code>@propertyWrapper struct Flexible<T: FlexibleDecodable>: Decodable {
    var wrappedValue: T

    init(from decoder: Decoder) throws {
        wrappedValue = try T(container: decoder.singleValueContainer())
    }
}

protocol FlexibleDecodable {
    init(container: SingleValueDecodingContainer) throws
}

extension Int: FlexibleDecodable {
    init(container: SingleValueDecodingContainer) throws {
        if let int = try? container.decode(Int.self) {
            self = int
        } else if let string = try? container.decode(String.self), let int = Int(string) {
            self = int
        } else {
            throw DecodingError.dataCorrupted(.init(codingPath: container.codingPath, debugDescription: "Invalid int value"))
        }
    }
}
</code>```

Original answer

You can use a wrapper over a string that knows how to decode from any of the basic JSON data types: string, number, boolean:

struct RelaxedString: Codable {
    let value: String

    init(_ value: String) {
        self.value = value
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        // attempt to decode from all JSON primitives
        if let str = try? container.decode(String.self) {
            value = str
        } else if let int = try? container.decode(Int.self) {
            value = int.description
        } else if let double = try? container.decode(Double.self) {
            value = double.description
        } else if let bool = try? container.decode(Bool.self) {
            value = bool.description
        } else {
            throw DecodingError.typeMismatch(String.self, .init(codingPath: decoder.codingPath, debugDescription: ""))
        }
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(value)
    }
}
```
<p>You can then use this new type in your struct. One minor disadvantage would be that consumer of the struct will need to make another indirection to access the wrapped string. However that can be avoided by declaring the decoded <code>RelaxedString</code> property as private, and use a computed one for the public interface:</p>
<pre class="lang-swift prettyprint-override"><code>struct GeneralProduct: Codable {
    var price: Double!
    var _id: RelaxedString?
    var name: String!

    var id: String? {
        get { _id?.value }
        set { _id = newValue.map(RelaxedString.init) }
    }

    private enum CodingKeys: String, CodingKey {
        case price = "p"
        case _id = "i"
        case name = "n"
    }

    init(price: Double? = nil, id: String? = nil, name: String? = nil) {
        self.price = price
        self._id = id.map(RelaxedString.init)
        self.name = name
    }
}
</code>```

Advantages of the above approach:

no need to write custom init(from decoder: Decoder) code, which can become tedious if the number of properties to be decoded increase

reusability - RelaxedString can be seamlessly used in other structs

the fact that the id can be decoded from a string or an int remains an implementation detail, consumers of GeneralProduct don't know/care that the id can come from a string or an int

the public interface exposes string values, which keeps the consumer code simple as it will not have to deal with multiple types of data

Body:
I have an API that will sometimes return a specific key value (in this case id) in the JSON as an Int and other times it will return that same key value as a String. How do I use codable to parse that JSON?

struct GeneralProduct: Codable {
    var price: Double!
    var id: String?
    var name: String!

    private enum CodingKeys: String, CodingKey {
        case price = "p"
        case id = "i"
        case name = "n"
    }

    init(price: Double? = nil, id: String? = nil, name: String? = nil) {
        self.price = price
        self.id = id
        self.name = name
    }
}

I keep getting this error message: Expected to decode String but found a number instead. The reason that it returns a number is because the id field is empty and when the id field is empty it defaults to returning 0 as an ID which codable identifies as a number. I can basically ignore the ID key but codable does not give me the option to ignore it to my knowledge. What would be the best way to handle this?

Here is the JSON. It is super simple

Working

{
  "p":2.12,
  "i":"3k3mkfnk3",
  "n":"Blue Shirt"
}

Error - because there is no id in the system, it returns 0 as a default which codable obviously sees as a number opposed to string.

{
  "p":2.19,
  "i":0,
  "n":"Black Shirt"
}

Body:
Seamlessly decoding from either Int or String into the same property requires writing some code.

However, thanks to a (somewhat) new addition to the language,(property wrappers), you can make it quite easy to reuse this logic wherever you need it:

// note this is only `Decodable`
struct GeneralProduct: Decodable {
    var price: Double
    @Flexible var id: Int // note this is an Int
    var name: String
}

The property wrapper and its supporting code can be implemented like this:

@propertyWrapper struct Flexible<T: FlexibleDecodable>: Decodable {
    var wrappedValue: T

    init(from decoder: Decoder) throws {
        wrappedValue = try T(container: decoder.singleValueContainer())
    }
}

protocol FlexibleDecodable {
    init(container: SingleValueDecodingContainer) throws
}

extension Int: FlexibleDecodable {
    init(container: SingleValueDecodingContainer) throws {
        if let int = try? container.decode(Int.self) {
            self = int
        } else if let string = try? container.decode(String.self), let int = Int(string) {
            self = int
        } else {
            throw DecodingError.dataCorrupted(.init(codingPath: container.codingPath, debugDescription: "Invalid int value"))
        }
    }
}

Original answer

You can use a wrapper over a string that knows how to decode from any of the basic JSON data types: string, number, boolean:

struct RelaxedString: Codable {
    let value: String

    init(_ value: String) {
        self.value = value
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        // attempt to decode from all JSON primitives
        if let str = try? container.decode(String.self) {
            value = str
        } else if let int = try? container.decode(Int.self) {
            value = int.description
        } else if let double = try? container.decode(Double.self) {
            value = double.description
        } else if let bool = try? container.decode(Bool.self) {
            value = bool.description
        } else {
            throw DecodingError.typeMismatch(String.self, .init(codingPath: decoder.codingPath, debugDescription: ""))
        }
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(value)
    }
}

You can then use this new type in your struct. One minor disadvantage would be that consumer of the struct will need to make another indirection to access the wrapped string. However that can be avoided by declaring the decoded RelaxedString property as private, and use a computed one for the public interface:

struct GeneralProduct: Codable {
    var price: Double!
    var _id: RelaxedString?
    var name: String!

    var id: String? {
        get { _id?.value }
        set { _id = newValue.map(RelaxedString.init) }
    }

    private enum CodingKeys: String, CodingKey {
        case price = "p"
        case _id = "i"
        case name = "n"
    }

    init(price: Double? = nil, id: String? = nil, name: String? = nil) {
        self.price = price
        self._id = id.map(RelaxedString.init)
        self.name = name
    }
}

Advantages of the above approach:

no need to write custom init(from decoder: Decoder) code, which can become tedious if the number of properties to be decoded increase

reusability - RelaxedString can be seamlessly used in other structs

the fact that the id can be decoded from a string or an int remains an implementation detail, consumers of GeneralProduct don't know/care that the id can come from a string or an int

the public interface exposes string values, which keeps the consumer code simple as it will not have to deal with multiple types of data


问:
adding sound to an OpenGL app
i am creating an OpenGL application and decided to look into adding sound...
what is the best sound(api?) i was thinking about using OpenAL but i had issues finding any good resources...
if possible could you please provide tutorial/info of some sort.</p>

答:
Here is one i used a while ago for 3D sound.

http://www.ambiera.com/irrklang/

It is called IrrKlang, it has good documentation for the API and it really easy to integrate. You should be able to get sound playing within an hour or so of downloading it.

Title: adding sound to an OpenGL app


问:
Can I scale iframe according to the width of page?
I try to scale iframe according to the size of page.

If I visit below page in mobile then, I got desired results. (Properly scaled page)

http://www.jobautomationindex.com/skill_dna_view

However, if I load the page in iframe in below link, the page isn't rescaled.

http://www.jobautomationindex.com/skill_dna/

Why these two pages behave differently?

========================================================================

For note, here is my code

I think one solution could be related with the scale factor in css.

```<code><style>
.wrap {
    width: 400;
    height: 400;
    overflow: hidden;
}

iframe {
    width: 100% !important;
    height: 700px !important;
    -webkit-transform: scale(1);
    transform: scale(1);
    -webkit-transform-origin: 0 0;
    transform-origin: 0 0;
}
</style>

<div class="wrap" style="width:400; height:400;">

    <iframe src="/skill_dna_view" scrolling="no" width="100%" height="700px" frameborder="0" tabindex="-1" allowfullscreen>
    </iframe>

</div>
</code>```

答:
add this meta in head </p>

```<code><meta name="viewport" content="width=device-width,initial-scale=1.0">
</code>```

Body:
add this meta in head

<meta name="viewport" content="width=device-width,initial-scale=1.0">


问:
How do I set data attribute value by the index of element in jQuery?
I have multiple sibling elements, some that are added dynamically and others manually or using JS. Each one has a data attribute of "data-sec_number" with a number value that increases by one for each new element down the page. At the moment I am manually writing these in.
E.g.

```<code><div class="container">
<div class="row resource_sec" data-sec_number=1>
<div class="content sec_number" data-sec_number=1></div>
</div>

<div class="row resource_sec" data-sec_number=2>
<div class="content sec_number" data-sec_number=2></div>
</div>

<div class="row resource_sec" data-sec_number=3>
<div class="content sec_number" data-sec_number=3></div>
</div>
</div>
</code>```

How can I get the value of attribute "data-sec_number" to match the index of the element .resource_sec within the .container element? E.g. the 3rd .resource_sec element will always have a "data-sec_number" value of 3.
I also have the child element of .resource_sec called .sec_number, which has the same data attribute that should mirror the parent.

The JS I have been trying to use is:

var items = $('.container .resource_sec');
var lastItem = $('.container .resource_sec:last');
var index = items.index(lastItem);

$('.resource_sec').attr('data-sec_number', index);
$('.sec_number').attr('data-sec_number', index);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="row resource_sec" data-sec_number=1>
    <div class="content sec_number" data-sec_number=1></div>
  </div>

  <div class="row resource_sec" data-sec_number=2>
    <div class="content sec_number" data-sec_number=2></div>
  </div>

  <div class="row resource_sec" data-sec_number=3>
    <div class="content sec_number" data-sec_number=3></div>
  </div>
</div></code>```

答:
The meaning of this line

```<code>$('.resource_sec').attr('data-sec_number', index);
</code>```

is to set the attribute value. to select (query) a specific index please use:

```<code>$('.resource_sec[data-sec_number=' + index + ']')
</code>```

or

```<code>$(`.resource_sec[data-sec_number=${index}]`)
</code>```

If you support ES6

UPDATE:

To add a new element in jQuery you may use:

```<code>var container = $('.container')
var newElement = $('<div class="row resource_sec"></div>').appendTo(container)
</code>```

Then, you can fetch the new element index by passing it to the index method,according to Jquery documentation:

If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.

```<code>var index = container.index(newElement)
</code>```

To append index to the new element attribute:

```<code>newElement.attr('data-sec_number', index)
</code>```

Body:
I have multiple sibling elements, some that are added dynamically and others manually or using JS. Each one has a data attribute of "data-sec_number" with a number value that increases by one for each new element down the page. At the moment I am manually writing these in.
E.g.

How can I get the value of attribute "data-sec_number" to match the index of the element .resource_sec within the .container element? E.g. the 3rd .resource_sec element will always have a "data-sec_number" value of 3.
I also have the child element of .resource_sec called .sec_number, which has the same data attribute that should mirror the parent.

The JS I have been trying to use is:

var items = $('.container .resource_sec');
var lastItem = $('.container .resource_sec:last');
var index = items.index(lastItem);

$('.resource_sec').attr('data-sec_number', index);
$('.sec_number').attr('data-sec_number', index);

Body:
The meaning of this line

$('.resource_sec').attr('data-sec_number', index);

is to set the attribute value. to select (query) a specific index please use:

$('.resource_sec[data-sec_number=' + index + ']')

or

$(`.resource_sec[data-sec_number=${index}]`)

If you support ES6

UPDATE:

To add a new element in jQuery you may use:

var container = $('.container')
var newElement = $('<div class="row resource_sec"></div>').appendTo(container)

Then, you can fetch the new element index by passing it to the index method,according to Jquery documentation:

If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.

var index = container.index(newElement)

To append index to the new element attribute:

newElement.attr('data-sec_number', index)