问:
Can I django filter a CharField by range?
How can I filter the prices between 5 and 15 for all the products?

I have this model:

class Product(models.Model):
    price = models.CharField(max_length=150, default= 12)
```

<p>I tried</p>

<pre class="lang-py prettyprint-override"><code>Products.objects.all().filter(price__range=(5, 15))
</code>```

but I get no objects.

Any idea on how to do this?

答:
For those finding this question on Google looking to actually implement a RangeFilter on a CharField, this is also possible but not by default. First create this class before your filter:

```<code>from django import forms
from django_filters import rest_framework as filters, fields

class CharRangeFilter(filters.RangeFilter):
    class CharRangeField(fields.RangeField):
        def __init__(self, *args, **kwargs):
            super().__init__(fields=(
                forms.CharField(),
                forms.CharField()
            ), *args, **kwargs)
        field_class = CharRangeField
</code>```

And then use it in your filter, like this for example:

```<code>class MyFilter(filters.FilterSet):
    my_char_field = CharRangeFilter()

    class Meta:
        model = MyModel
        fields = ['my_char_field']
</code>```

The reason creating your own RangeField class is because RangeFilter dynamically creates a RangeField, which by default uses two DecimalField objects, and the default can't be changed from the RangeFilter object because RangeFilter is only aware of RangeField via field_class.

Body:
How can I filter the prices between 5 and 15 for all the products?

I have this model:

class Product(models.Model):
    price = models.CharField(max_length=150, default= 12)

I tried

Products.objects.all().filter(price__range=(5, 15))

but I get no objects.

Any idea on how to do this?

Body:
For those finding this question on Google looking to actually implement a RangeFilter on a CharField, this is also possible but not by default. First create this class before your filter:

from django import forms
from django_filters import rest_framework as filters, fields

class CharRangeFilter(filters.RangeFilter):
    class CharRangeField(fields.RangeField):
        def __init__(self, *args, **kwargs):
            super().__init__(fields=(
                forms.CharField(),
                forms.CharField()
            ), *args, **kwargs)
        field_class = CharRangeField

And then use it in your filter, like this for example:

class MyFilter(filters.FilterSet):
    my_char_field = CharRangeFilter()

    class Meta:
        model = MyModel
        fields = ['my_char_field']

The reason creating your own RangeField class is because RangeFilter dynamically creates a RangeField, which by default uses two DecimalField objects, and the default can't be changed from the RangeFilter object because RangeFilter is only aware of RangeField via field_class.


来源: stackexchange

问:
EF6 - How to assert at runtime which columns have Concurrency mode = fixed
In the Entity Framework Edmx editor (e.g. EF6), sometimes developers will completely delete an entity (table) and then re-import it (DB to C# model).  This often has the side effect of dropping properties that were manually set on columns such as Concurrency = fixed.

Is there a way to add a runtime check that can inspect such properties to verify they still are set as originally designed?  Especially the Concurrency mode.

If no runtime check is possible, maybe then a compile time check?

答:
Constructed a Unit Test by modifying answer to similar question from @narayana (https://stackoverflow.com/a/21863827/538763).  Thanks to @jojess for link.</p>

```<code>using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace CompanyName.UnitTests
{
    [TestClass]
    public class EntityFreameworkDbTests
    {
        public TestContext TestContext { get; set; }

        [TestMethod]
        public void VerifyEdmxConcurrencyColumns()
        {
            const int minExpectedEdmxPathCount = 65;

            // Expected Output:  List all columns in all edmx that set ConcurrencyMode = fixed
            //
            List<Tuple<string, string, string>> expected = new List<Tuple<string, string, string>>
            {
                // EMDX, TableName, ColumnName
                Tuple.Create("TheFileName.edmx", "ActivityLog", "Successes"),
                Tuple.Create("TheFileName.edmx", "ActivityLog", "Fails")
            };

            // use top of source tree to include all edmx files
            string serverSourceDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            string [] edmxPaths = Directory.GetFiles(serverSourceDir, "*.edmx", SearchOption.AllDirectories);

            Assert.IsTrue(edmxPaths.Count() >= minExpectedEdmxPathCount, "Under the expected min count of edmx paths: Actual = {0}, Expected = {1}"
                .FormatExt(edmxPaths.Count(), minExpectedEdmxPathCount));

            List<Tuple<string, string, string>> actual = new List<Tuple<string, string, string>>();

            TestContext.WriteLine("All Actuals:");

            foreach (string edmxPath in edmxPaths)
            {
                XDocument xmlDoc = XDocument.Load(edmxPath);

                IEnumerable<XElement> concurrencyFixedColumns = xmlDoc.Descendants()
                    .Where(el => (string)el.Attribute("ConcurrencyMode") == "Fixed");

                foreach (XElement el in concurrencyFixedColumns)
                {
                    string value = el.Attribute("ConcurrencyMode")?.Value;                   //modified = true;

                    if (value != null)
                    {
                        string edmxFile = Path.GetFileName(edmxPath);
                        string tableName = (string)el.Parent.Attribute("Name");

                        actual.Add(Tuple.Create(edmxFile, tableName, (string)el.Attribute("Name")));
                        TestContext.WriteLine("\t{0},{1},{2}", edmxFile, tableName, el.Attribute("Name"));
                    }
                }
            }

            StringBuilder errors = new StringBuilder();

            actual.Except(expected).ToList().ForEach(edmxColumn =>
                errors.AppendLine("Actual but not expected: " + edmxColumn.Item1 + "," + edmxColumn.Item2 + "," + edmxColumn.Item3));

            expected.Except(actual).ToList().ForEach(edmxColumn =>
                errors.AppendLine("Expected but not actual: " + edmxColumn.Item1 + "," + edmxColumn.Item2 + "," + edmxColumn.Item3));

            Assert.AreEqual(0, errors.Length, "\n\nEF Concurrency=fixed columns:\n" + errors.ToString() + "\n");
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Constructed a Unit Test by modifying answer to similar question from @narayana (https://stackoverflow.com/a/21863827/538763).  Thanks to @jojess for link.

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace CompanyName.UnitTests
{
    [TestClass]
    public class EntityFreameworkDbTests
    {
        public TestContext TestContext { get; set; }

        [TestMethod]
        public void VerifyEdmxConcurrencyColumns()
        {
            const int minExpectedEdmxPathCount = 65;

            // Expected Output:  List all columns in all edmx that set ConcurrencyMode = fixed
            //
            List<Tuple<string, string, string>> expected = new List<Tuple<string, string, string>>
            {
                // EMDX, TableName, ColumnName
                Tuple.Create("TheFileName.edmx", "ActivityLog", "Successes"),
                Tuple.Create("TheFileName.edmx", "ActivityLog", "Fails")
            };

            // use top of source tree to include all edmx files
            string serverSourceDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            string [] edmxPaths = Directory.GetFiles(serverSourceDir, "*.edmx", SearchOption.AllDirectories);

            Assert.IsTrue(edmxPaths.Count() >= minExpectedEdmxPathCount, "Under the expected min count of edmx paths: Actual = {0}, Expected = {1}"
                .FormatExt(edmxPaths.Count(), minExpectedEdmxPathCount));

            List<Tuple<string, string, string>> actual = new List<Tuple<string, string, string>>();

            TestContext.WriteLine("All Actuals:");

            foreach (string edmxPath in edmxPaths)
            {
                XDocument xmlDoc = XDocument.Load(edmxPath);

                IEnumerable<XElement> concurrencyFixedColumns = xmlDoc.Descendants()
                    .Where(el => (string)el.Attribute("ConcurrencyMode") == "Fixed");

                foreach (XElement el in concurrencyFixedColumns)
                {
                    string value = el.Attribute("ConcurrencyMode")?.Value;                   //modified = true;

                    if (value != null)
                    {
                        string edmxFile = Path.GetFileName(edmxPath);
                        string tableName = (string)el.Parent.Attribute("Name");

                        actual.Add(Tuple.Create(edmxFile, tableName, (string)el.Attribute("Name")));
                        TestContext.WriteLine("\t{0},{1},{2}", edmxFile, tableName, el.Attribute("Name"));
                    }
                }
            }

            StringBuilder errors = new StringBuilder();

            actual.Except(expected).ToList().ForEach(edmxColumn =>
                errors.AppendLine("Actual but not expected: " + edmxColumn.Item1 + "," + edmxColumn.Item2 + "," + edmxColumn.Item3));

            expected.Except(actual).ToList().ForEach(edmxColumn =>
                errors.AppendLine("Expected but not actual: " + edmxColumn.Item1 + "," + edmxColumn.Item2 + "," + edmxColumn.Item3));

            Assert.AreEqual(0, errors.Length, "\n\nEF Concurrency=fixed columns:\n" + errors.ToString() + "\n");
        }
    }
}


问:
React scripts issue: loop loading chunk.js
I'm using React scripts v3. I have this issue whenever I do an action of in the page ( mouse event, forms...) the application keeps downloading chunk.js

This my package.json

```<code>{
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "babel-polyfill": "^6.26.0",
    "bootstrap": "^4.3.1",
    "cors": "^2.8.5",
    "lodash.flatten": "^4.4.0",
    "lodash.get": "^4.4.2",
    "lodash.intersection": "^4.4.0",
    "mockdate": "^2.0.2",
    "moment": "^2.24.0",
    "prop-types": "^15.7.2",
    "react": "^16.8.6",
    "react-app-polyfill": "^1.0.1",
    "react-dom": "^16.8.6",
    "react-router": "4.3.1",
    "react-router-dom": "4.3.1",
    "react-scripts": "^3.0.1",
    "recompose": "^0.30.0",
    "url-search-params-polyfill": "^6.0.0",
    "uuid": "^3.3.2"
  },
  "scripts": {
    "mocks": "cd mocks && npm start",
    "start-dotnet": "react-scripts start",
    "start": "concurrently \"npm run mocks\" \"react-scripts start\"",
    "build": "react-scripts build",
    "test": "set NODE_ICU_DATA=node_modules/full-icu&& react-scripts test --env=jsdom",
    "test:staged": "npm run test -- --coverage --findRelatedTests --watchAll=false",
    "test-coverage": "npm run test -- --coverage --watchAll=false"
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged",
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
    }
  },
  "lint-staged": {
    "*src/**/*.js": [
      "prettier --write",
      "npm run test:coverage",
      "git add"
    ]
  },
  "commitlint": {
    "extends": [
      "@commitlint/config-conventional"
    ]
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "jest": {
    "snapshotSerializers": [
      "enzyme-to-json/serializer"
    ]
  },
  "browserslist": [
    ">0.2%",
    "ie 11",
    "not dead",
    "not op_mini all"
  ],
  "devDependencies": {
    "@commitlint/cli": "^8.0.0",
    "@commitlint/config-conventional": "^8.0.0",
    "concurrently": "^4.1.0",
    "enzyme": "^3.9.0",
    "enzyme-adapter-react-16": "^1.12.1",
    "enzyme-to-json": "^3.3.5",
    "eslint-plugin-react-hooks": "^1.6.0",
    "full-icu": "^1.3.0",
    "husky": "^2.4.1",
    "jest": "^24.7.1",
    "jest-cucumber": "^2.0.11",
    "lint-staged": "^8.2.1",
    "node-sass": "^4.11.0",
    "prettier": "^1.18.2"
  }
}
</code>```

Does anyone have an idea about this issue?

答: I ran into this problem today. I had incorrectly set the onChange action to a string instead of a function, so changing it to a function worked for me.</p>

Body:
I'm using React scripts v3. I have this issue whenever I do an action of in the page ( mouse event, forms...) the application keeps downloading chunk.js

This my package.json

{
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "babel-polyfill": "^6.26.0",
    "bootstrap": "^4.3.1",
    "cors": "^2.8.5",
    "lodash.flatten": "^4.4.0",
    "lodash.get": "^4.4.2",
    "lodash.intersection": "^4.4.0",
    "mockdate": "^2.0.2",
    "moment": "^2.24.0",
    "prop-types": "^15.7.2",
    "react": "^16.8.6",
    "react-app-polyfill": "^1.0.1",
    "react-dom": "^16.8.6",
    "react-router": "4.3.1",
    "react-router-dom": "4.3.1",
    "react-scripts": "^3.0.1",
    "recompose": "^0.30.0",
    "url-search-params-polyfill": "^6.0.0",
    "uuid": "^3.3.2"
  },
  "scripts": {
    "mocks": "cd mocks && npm start",
    "start-dotnet": "react-scripts start",
    "start": "concurrently \"npm run mocks\" \"react-scripts start\"",
    "build": "react-scripts build",
    "test": "set NODE_ICU_DATA=node_modules/full-icu&& react-scripts test --env=jsdom",
    "test:staged": "npm run test -- --coverage --findRelatedTests --watchAll=false",
    "test-coverage": "npm run test -- --coverage --watchAll=false"
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged",
      "commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
    }
  },
  "lint-staged": {
    "*src/**/*.js": [
      "prettier --write",
      "npm run test:coverage",
      "git add"
    ]
  },
  "commitlint": {
    "extends": [
      "@commitlint/config-conventional"
    ]
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "jest": {
    "snapshotSerializers": [
      "enzyme-to-json/serializer"
    ]
  },
  "browserslist": [
    ">0.2%",
    "ie 11",
    "not dead",
    "not op_mini all"
  ],
  "devDependencies": {
    "@commitlint/cli": "^8.0.0",
    "@commitlint/config-conventional": "^8.0.0",
    "concurrently": "^4.1.0",
    "enzyme": "^3.9.0",
    "enzyme-adapter-react-16": "^1.12.1",
    "enzyme-to-json": "^3.3.5",
    "eslint-plugin-react-hooks": "^1.6.0",
    "full-icu": "^1.3.0",
    "husky": "^2.4.1",
    "jest": "^24.7.1",
    "jest-cucumber": "^2.0.11",
    "lint-staged": "^8.2.1",
    "node-sass": "^4.11.0",
    "prettier": "^1.18.2"
  }
}

Does anyone have an idea about this issue?


问:
Overflow:hidden - is there any way to make a specific child visible?
I need the grey half-circle to include the quote so that it will be the correct height, but I also need that line to be able to overflow from it's containers.

.CONTAINER {
  width: 70%;
  position: relative;
  margin-left: 15%;
  margin-right: 15%;
  margin-top: 25%;
  margin-bottom: -10px;
  overflow: hidden;
}

.halfCircle {
  max-width: 100%;
  background: darkgray;
  border-top-left-radius: 100%;
  border-top-right-radius: 100%;
  border-bottom: 0;
  text-align: center;
  overflow: visible;
  margin-bottom: -10px;
}

#QUOTE22 {
  text-align: center;
  margin-top: -32px;
  font-size: 1.3em;
  letter-spacing: 2px;
  font-weight: 30;
}

#PLogo {
  position: relative;
  margin-left: auto;
  margin-right: auto;
  height: 200px;
  width: 200px;
}

#FrontQuote {
  height: 1.3em;
  width: 1.3em;
  position: relative;
  right: -5px;
}

#QUOTE {
  text-align: center;
  line-height: 100%;
  letter-spacing: 1px;
  font-size: 1.3em;
}

#QUOTE12 {
  text-align: center;
  line-height: 100%;
  letter-spacing: 0px;
  font-size: 1.3em;
  margin-top: 10px;
  z-index: 100;
  overflow: visible;
}

#BackQuote {
  height: 1.7em;
  width: 1.7em;
  transform: rotate(180deg);
  z-index: 100;
  overflow: visible;
}

#stock1 {
  position: absolute;
  margin-top: -52.5px;
  margin-left: -8px;
  width: 101.5vw;
  height: auto;
  max-height: 500px;
  filter: grayscale(1);
  opacity: .5;
  background: #121212;
  z-index: -1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="CONTAINER">
  <div class="halfCircle">
    <img id="PLogo" src="https://static.wixstatic.com/media/058e45_e590acfd22c440f4b5c89450738f321d~mv2.png/v1/fill/w_438,h_438,al_c,q_85,usm_0.66_1.00_0.01/058e45_e590acfd22c440f4b5c89450738f321d~mv2.webp">
    <p id="QUOTE12"><img id="FrontQuote" src="https://static.wixstatic.com/media/058e45_df55c46642a94f489cf76fa18cc13cb8~mv2.png/v1/fill/w_50,h_50,al_c,q_85,usm_0.66_1.00_0.01/Logo%20Quotes.webp"> WHAT WE LEARN WITH PLEASURE, WE NEVER FORGET

      <sub><sub><img id="BackQuote" src="https://static.wixstatic.com/media/058e45_df55c46642a94f489cf76fa18cc13cb8~mv2.png/v1/fill/w_50,h_50,al_c,q_85,usm_0.66_1.00_0.01/Logo%20Quotes.webp"></sub></sub>
    </p>
  </div>
</div>
</section>

<section id="SKILLS">

  <p id="QUOTE22">- ALFRED MERCIER</p>

  <img id="stock1" src="https://media.istockphoto.com/photos/graphic-designer-drawing-on-graphics-tablet-at-workplace-picture-id865230556"></code>```

Some additional information, since the bot says I need more words:

I read on another post that someone suggested having a container around the half circle and have that be overflow:hidden so that the child of the child wouldn't be effected, but that hasn't worked for me below.

I'd prefer HTML or CSS answers only, since that's all I know at the moment... but if there's no other way, I'll try other languages.

It's going to be difficult for me to adjust position too much, but I read another comment somewhere that position might be an issue, so I tried to take position tags off of as many elements as I could.

答:
position:relative; should bring it on top. You may add a z-index value if that is not efficient.

example

.CONTAINER {
  width: 70%;
  position: relative;
  margin-left: 15%;
  margin-right: 15%;
  margin-top: 25%;
  margin-bottom: -10px;
  overflow: hidden;
}

.halfCircle {
  max-width: 100%;
  background: darkgray;
  border-top-left-radius: 100%;
  border-top-right-radius: 100%;
  border-bottom: 0;
  text-align: center;
  overflow: visible;
  margin-bottom: -10px;
}

#QUOTE22 {
  text-align: center;
  margin-top: -1em;
  font-size: 1.3em;
  letter-spacing: 2px;
  font-weight: 30;
  position:relative;/* added <====== */
}

#PLogo {
  position: relative;
  margin-left: auto;
  margin-right: auto;
  height: 200px;
  width: 200px;
}

#FrontQuote {
  height: 1.3em;
  width: 1.3em;
  position: relative;
  right: -5px;
}

#QUOTE {
  text-align: center;
  line-height: 100%;
  letter-spacing: 1px;
  font-size: 1.3em;
}

#QUOTE12 {
  text-align: center;
  line-height: 100%;
  letter-spacing: 0px;
  font-size: 1.3em;
  margin-top: 10px;
  z-index: 100;
  overflow: visible;
}

#BackQuote {
  height: 1.7em;
  width: 1.7em;
  transform: rotate(180deg);
  z-index: 100;
  overflow: visible;
}

#stock1 {
  position: absolute;
  margin-top: -52.5px;
  margin-left: -8px;
  width: 101.5vw;
  height: auto;
  max-height: 500px;
  filter: grayscale(1);
  opacity: .5;
  background: #121212;
  z-index: -1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="CONTAINER">
  <div class="halfCircle">
    <img id="PLogo" src="https://static.wixstatic.com/media/058e45_e590acfd22c440f4b5c89450738f321d~mv2.png/v1/fill/w_438,h_438,al_c,q_85,usm_0.66_1.00_0.01/058e45_e590acfd22c440f4b5c89450738f321d~mv2.webp">
    <p id="QUOTE12"><img id="FrontQuote" src="https://static.wixstatic.com/media/058e45_df55c46642a94f489cf76fa18cc13cb8~mv2.png/v1/fill/w_50,h_50,al_c,q_85,usm_0.66_1.00_0.01/Logo%20Quotes.webp"> WHAT WE LEARN WITH PLEASURE, WE NEVER FORGET

      <sub><sub><img id="BackQuote" src="https://static.wixstatic.com/media/058e45_df55c46642a94f489cf76fa18cc13cb8~mv2.png/v1/fill/w_50,h_50,al_c,q_85,usm_0.66_1.00_0.01/Logo%20Quotes.webp"></sub></sub>
    </p>
  </div>
</div>
</section>

<section id="SKILLS">

  <p id="QUOTE22">- ALFRED MERCIER</p>

  <img id="stock1" src="https://media.istockphoto.com/photos/graphic-designer-drawing-on-graphics-tablet-at-workplace-picture-id865230556"></code>```

Body:
I need the grey half-circle to include the quote so that it will be the correct height, but I also need that line to be able to overflow from it's containers.

.CONTAINER {
  width: 70%;
  position: relative;
  margin-left: 15%;
  margin-right: 15%;
  margin-top: 25%;
  margin-bottom: -10px;
  overflow: hidden;
}

.halfCircle {
  max-width: 100%;
  background: darkgray;
  border-top-left-radius: 100%;
  border-top-right-radius: 100%;
  border-bottom: 0;
  text-align: center;
  overflow: visible;
  margin-bottom: -10px;
}

#QUOTE22 {
  text-align: center;
  margin-top: -32px;
  font-size: 1.3em;
  letter-spacing: 2px;
  font-weight: 30;
}

#PLogo {
  position: relative;
  margin-left: auto;
  margin-right: auto;
  height: 200px;
  width: 200px;
}

#FrontQuote {
  height: 1.3em;
  width: 1.3em;
  position: relative;
  right: -5px;
}

#QUOTE {
  text-align: center;
  line-height: 100%;
  letter-spacing: 1px;
  font-size: 1.3em;
}

#QUOTE12 {
  text-align: center;
  line-height: 100%;
  letter-spacing: 0px;
  font-size: 1.3em;
  margin-top: 10px;
  z-index: 100;
  overflow: visible;
}

#BackQuote {
  height: 1.7em;
  width: 1.7em;
  transform: rotate(180deg);
  z-index: 100;
  overflow: visible;
}

#stock1 {
  position: absolute;
  margin-top: -52.5px;
  margin-left: -8px;
  width: 101.5vw;
  height: auto;
  max-height: 500px;
  filter: grayscale(1);
  opacity: .5;
  background: #121212;
  z-index: -1;
}

 WHAT WE LEARN WITH PLEASURE, WE NEVER FORGET

- ALFRED MERCIER

Some additional information, since the bot says I need more words:

I read on another post that someone suggested having a container around the half circle and have that be overflow:hidden so that the child of the child wouldn't be effected, but that hasn't worked for me below.

I'd prefer HTML or CSS answers only, since that's all I know at the moment... but if there's no other way, I'll try other languages.

It's going to be difficult for me to adjust position too much, but I read another comment somewhere that position might be an issue, so I tried to take position tags off of as many elements as I could.

Body:
position:relative; should bring it on top. You may add a z-index value if that is not efficient.

example

.CONTAINER {
  width: 70%;
  position: relative;
  margin-left: 15%;
  margin-right: 15%;
  margin-top: 25%;
  margin-bottom: -10px;
  overflow: hidden;
}

.halfCircle {
  max-width: 100%;
  background: darkgray;
  border-top-left-radius: 100%;
  border-top-right-radius: 100%;
  border-bottom: 0;
  text-align: center;
  overflow: visible;
  margin-bottom: -10px;
}

#QUOTE22 {
  text-align: center;
  margin-top: -1em;
  font-size: 1.3em;
  letter-spacing: 2px;
  font-weight: 30;
  position:relative;/* added <====== */
}

#PLogo {
  position: relative;
  margin-left: auto;
  margin-right: auto;
  height: 200px;
  width: 200px;
}

#FrontQuote {
  height: 1.3em;
  width: 1.3em;
  position: relative;
  right: -5px;
}

#QUOTE {
  text-align: center;
  line-height: 100%;
  letter-spacing: 1px;
  font-size: 1.3em;
}

#QUOTE12 {
  text-align: center;
  line-height: 100%;
  letter-spacing: 0px;
  font-size: 1.3em;
  margin-top: 10px;
  z-index: 100;
  overflow: visible;
}

#BackQuote {
  height: 1.7em;
  width: 1.7em;
  transform: rotate(180deg);
  z-index: 100;
  overflow: visible;
}

#stock1 {
  position: absolute;
  margin-top: -52.5px;
  margin-left: -8px;
  width: 101.5vw;
  height: auto;
  max-height: 500px;
  filter: grayscale(1);
  opacity: .5;
  background: #121212;
  z-index: -1;
}

<div class="CONTAINER">
  <div class="halfCircle">
    <img id="PLogo" src="https://static.wixstatic.com/media/058e45_e590acfd22c440f4b5c89450738f321d~mv2.png/v1/fill/w_438,h_438,al_c,q_85,usm_0.66_1.00_0.01/058e45_e590acfd22c440f4b5c89450738f321d~mv2.webp">
    <p id="QUOTE12"><img id="FrontQuote" src="https://static.wixstatic.com/media/058e45_df55c46642a94f489cf76fa18cc13cb8~mv2.png/v1/fill/w_50,h_50,al_c,q_85,usm_0.66_1.00_0.01/Logo%20Quotes.webp"> WHAT WE LEARN WITH PLEASURE, WE NEVER FORGET

      <sub><sub><img id="BackQuote" src="https://static.wixstatic.com/media/058e45_df55c46642a94f489cf76fa18cc13cb8~mv2.png/v1/fill/w_50,h_50,al_c,q_85,usm_0.66_1.00_0.01/Logo%20Quotes.webp"></sub></sub>
    </p>
  </div>
</div>
</section>

<section id="SKILLS">

  <p id="QUOTE22">- ALFRED MERCIER</p>

  <img id="stock1" src="https://media.istockphoto.com/photos/graphic-designer-drawing-on-graphics-tablet-at-workplace-picture-id865230556">


问:
How to make sure the public key's authenticity
I'm new to asymmetric cryptography (public-private keys) and has a fundamental confusion:
  I understand that once a person has broadcast his public key to the network, the following communications become safe using the public-private key paradigm.
  However, how do you make sure the public key received is valid at the first place? For example, if Bob wants to establish a secure communication with Alice, with Eve eavesdropping in the middle, how do you make sure that Bob receives the real public key from Alice, instead of the fake public key forged by Eve?
  Thanks!

Cheers,
M.

答:
The public key would be signed by another authority. Check if this authority is genuine and renowned. If it is unknown then try to further check its signing authority and see if its a renowned one.

The concept of trusting this public key is based on basing your inherent trust in authority which signs this certificate. Signatures are mathematically verifiable so they cannot be forged unless there's an issue with implementation or mathematical algorithm itself.

So in a nutshell, try to see the signing authority of the certificate and if it is something you trust.


问:
Optimize WPF ComboBox search with thousands items
I have a WPF ComboBox control with an itemsSource of 66000 items. To improve loading performance I've used VirtualizingStackPanel and it's ok but now I've another problem.

The ComboBox is editable and when I type on TextBox it start search for SelectedItem to match...but it is slow and don't immediately respond to character typed.

How can avoid this behavior?

答: Using VirtualizingStackPanel only ensure that you will have UI Vitualization but in your case, as BoltClock probably wanted to point out, you might need to consider implementing DataVirtualization as well...

ContentLicense: CC BY-SA 3.0


问:
How to check date format in a pandas column
Ok, so I have a column in a pandas table that I created from a CSV file that I am trying to go through and check to see if each cell is a date. Most of them are but there are a few exceptions that I would like to discard from the column. I am able to use the dateutil tool and the following code taken from another forum to insert a single cell and check if it is a date:

```<code>from dateutil.parser import parse

def is_date(string, fuzzy = False):
    try:
        parse(string, fuzzy = fuzzy)
        return True

    except ValueError:
        return False

print(is_date(df.loc[0, 'Column_Name']))
</code>```

This will return "True" when I run the code. What I want to do is use a try loop to check each cell in the column, and if the value is "False" then to delete that row entirely. Im new to coding and am having trouble with the looping part. I appreciate the help!

Edit:
It is month first then day. I can see now that that was not the best example for the format but it doesn't really matter as all date entries will be in that same format. Some of the cells will be other things like a comment by the user which I want to exclude. But, I was able to find a way to loop through the column and print the datetime formated string if it is a date and pass over non date strings:

```<code>def is_date(date_str, fuzzy = False):
    try:
        parse(date_str, fuzzy = fuzzy)
        return date_str

    except ValueError:
        pass

i = 0
while i < len(df['Column_Name']):
    date_group = is_date(str(df.loc[i, 'Column_Name']))
    try:
        date_change = datetime.datetime.strptime(date_group, '%m/%d/%y').date()
        print(date_change)
    except:
        pass
    i = i + 1
</code>```

Now I need to write to a new column and if T then write the date and if F exclude from the new column

答:
What I would do is to create another column by applying your function and then drop the rows which returned false</p>

```<code>df['return_label'] = df['Column_Name'].apply(is_date)

df = df[df['return_label']==True]
</code>```

Body:
Ok, so I have a column in a pandas table that I created from a CSV file that I am trying to go through and check to see if each cell is a date. Most of them are but there are a few exceptions that I would like to discard from the column. I am able to use the dateutil tool and the following code taken from another forum to insert a single cell and check if it is a date:

from dateutil.parser import parse

def is_date(string, fuzzy = False):
    try:
        parse(string, fuzzy = fuzzy)
        return True

    except ValueError:
        return False

print(is_date(df.loc[0, 'Column_Name']))

This will return "True" when I run the code. What I want to do is use a try loop to check each cell in the column, and if the value is "False" then to delete that row entirely. Im new to coding and am having trouble with the looping part. I appreciate the help!

Edit:
It is month first then day. I can see now that that was not the best example for the format but it doesn't really matter as all date entries will be in that same format. Some of the cells will be other things like a comment by the user which I want to exclude. But, I was able to find a way to loop through the column and print the datetime formated string if it is a date and pass over non date strings:

def is_date(date_str, fuzzy = False):
    try:
        parse(date_str, fuzzy = fuzzy)
        return date_str

    except ValueError:
        pass

i = 0
while i < len(df['Column_Name']):
    date_group = is_date(str(df.loc[i, 'Column_Name']))
    try:
        date_change = datetime.datetime.strptime(date_group, '%m/%d/%y').date()
        print(date_change)
    except:
        pass
    i = i + 1

Now I need to write to a new column and if T then write the date and if F exclude from the new column

Body:
What I would do is to create another column by applying your function and then drop the rows which returned false

df['return_label'] = df['Column_Name'].apply(is_date)

df = df[df['return_label']==True]


问:
mysql throws me an error with the IF what should I do?
```<code> create trigger TR_03
  before update
  on empleados
  for each row
 begin
  if updating('idempleado') then
   insert into controlCambio values("superusuarioalber",now(), old.idempleado, new.idempleado);
  end if;
  if updating('nombre') then
   insert into controlCambios values("superusuarioalber",now(), old.nombre, new.nombre);
  end if;
  if updating('documento') then
   insert into controlCambios values("superusuarioalber",now(), old.documento, new.documento);
  end if;
  if updating('cargo') then
   insert into controlCambios values("superusuarioalber",now(), old.cargo, new.cargo);
  end if;
 end TR_03;
</code>```

答:
You have it almost right your end TR_03 is not allowed in mysql.
And i also think that updating() is a fucntion in your database
so use</p>

```<code>DELIMITER $$
create trigger TR_03
before update on empleados
for each row
begin
  if updating('idempleado') then
    insert into controlCambio values("superusuarioalber",now(), old.idempleado, new.idempleado);
  end if;
  if updating('nombre') then
    insert into controlCambios values("superusuarioalber",now(), old.nombre, new.nombre);
  end if;
  if updating('documento') then
    insert into controlCambios values("superusuarioalber",now(), old.documento, new.documento);
  end if;
  if updating('cargo') then
    insert into controlCambios values("superusuarioalber",now(), old.cargo, new.cargo);
  end if;
end $$
DELIMITER ;
</code>```

Body:
You have it almost right your end TR_03 is not allowed in mysql.
And i also think that updating() is a fucntion in your database
so use

DELIMITER $$
create trigger TR_03
before update on empleados
for each row
begin
  if updating('idempleado') then
    insert into controlCambio values("superusuarioalber",now(), old.idempleado, new.idempleado);
  end if;
  if updating('nombre') then
    insert into controlCambios values("superusuarioalber",now(), old.nombre, new.nombre);
  end if;
  if updating('documento') then
    insert into controlCambios values("superusuarioalber",now(), old.documento, new.documento);
  end if;
  if updating('cargo') then
    insert into controlCambios values("superusuarioalber",now(), old.cargo, new.cargo);
  end if;
end $$
DELIMITER ;


问:
RAD Studio 10.2.3 Jedi JVCL Install Problem
I've uninstalled my RAD Studio 10.2.2 and installed 10.2.3 in my Win10 development VM.  Along the way I uninstalled all the previous 3rd-party libs, including the Jedi GetIt packages, and per the instructions got rid of all the old Jedi source and DCP/DCLs.  I'm attempting to install them back into 10.2.3 via GetIt.  The JCL libs install fine, but when I try to install JVCL, the installation batch file hangs after compiling the installer and the VM comes to its knees.  I rebooted, started taskmgr and watched as the batch file ran - it appears to go into a loop creating many instances of msgfmt.  I've tried removing it all again, downloading and installing the 3.8 version myself and running the install batch file by itself, same problem; then backing up to the 3.6 version that had installed OK in 10.2.2, and it does the same thing.  If I edit the batch file to skip the language-setup section, the batch file completes OK, but trying to re-run the GetIt update causes it to re-download and replace that batch file. :(

The installer does compile before the languages part of the batch file is reached, so I tried running the installer directly.  I assume I'm not passing it cmd line info it needs, because it compiles the 64-bit libs fine but chokes immediately on compiling the 32-bit version of JvCore250.bpl with an unspecified compile error.

Anyone else run into this? Is a solution known?

答: Turns out to ultimately be a pathing problem.  When multiple installations of the IDE exist on a machine (e.g. my VM has or previously had D2007, XE2 and 10.1 on it), the PATH environment variable can be too long - edit the PATH in the system to remove the old/stale paths.  Then make sure that the library paths in the IDE includes $(BDSLIB)\$(PLATFORM)\release or you'll get "can't find RTL" when building the packages.


问:
ng-modal button click to main window data not passing (Angular)
I was working on NG-Model window. Initially my code was working; when my code was applied in select element that is radio button, it was working perfectly fine, but when I changed my code to Click method for the button it was not working.

Here is my HTML code:

 <input type="radio" name="age" (change)="getageValue(columns)" value="ageValue">
```

<p>But If I changed to onClick of Button </p>

<pre class="lang-html prettyprint-override"><code><button type="button" class="btn btn-secondary" (click)="getageValue(columns)">Match</button>
</code>```

My guess was that column property was not there.

How can I solve this?

答:
Here is demo that I create based on your question. and I can't find any errors on it.

Am I missing something?

(Sample code applied to last column as "Example Columns".)

Body:
I was working on NG-Model window. Initially my code was working; when my code was applied in select element that is radio button, it was working perfectly fine, but when I changed my code to Click method for the button it was not working.

Here is my HTML code:

 <input type="radio" name="age" (change)="getageValue(columns)" value="ageValue">

But If I changed to onClick of Button

<button type="button" class="btn btn-secondary" (click)="getageValue(columns)">Match</button>

My guess was that column property was not there.

How can I solve this?


问:
How do I fix this css problem with the header on mobile?
I am having an issue with my logo on the mobile screen. It's too big and doesn't fit properly inline. Please help. I have attached what it looks like now and what it should look like. You can check the website here.

Before/Now:

After (how it should look):

答:
You could play with the max-width parameter of the logo setting also height: auto that way you can control the maximum size of the logo.

I tried modifying your code and what worked for me was

@media only screen and (max-width: 640px) {
    #header .header-main .custom-html img {
        max-width: 45vw;
        height: auto;
    }
}
```

The vw units represent viewport width percentage, so it's a variable unit, based on the viewport width.

I would prefer fixing a size though to avoid it look strange on different cell phones.

Body:
You could play with the max-width parameter of the logo setting also height: auto that way you can control the maximum size of the logo.

I tried modifying your code and what worked for me was

@media only screen and (max-width: 640px) {
    #header .header-main .custom-html img {
        max-width: 45vw;
        height: auto;
    }
}

The vw units represent viewport width percentage, so it's a variable unit, based on the viewport width.

I would prefer fixing a size though to avoid it look strange on different cell phones.


问:
Cannot drag and drop object in xcode 9.2
I am using xcode 9.2 and one day I can't drag and drop all the things like below objects.
Does anyone know what is the problem about that. thanks.

I would like to use below object.

答:
Just a couple of troubleshooting thoughts:

Restart Xcode

Are you able to drag and it just doesn't "take" in the storyboard? If so, double check that you're dropping it in a view controller that can accept the object


问:
How to parse a string in command line format in golang
I have some command line strings:

```<code>ffmpeg -i input.mp4 output.avi
ffmpeg -i "my input.mp4" output_2.api
</code>```

I'd like to parse them to slice: [ffmpeg, -i, input.mp4, output.avi] and [ffmpeg, -i, "my input.mp4", output_2.avi]. Is there any stable way to do that?

答:
https://github.com/google/shlex seems meet my requirement, I'll try it :)

Thanks very much for your support!

-- Klaus

Body:
I have some command line strings:

ffmpeg -i input.mp4 output.avi
ffmpeg -i "my input.mp4" output_2.api

I'd like to parse them to slice: [ffmpeg, -i, input.mp4, output.avi] and [ffmpeg, -i, "my input.mp4", output_2.avi]. Is there any stable way to do that?


问:
Registration/authorization form with class-based generic views in django
Could someone please help with reg/auth/auth using class-based generic views? It is clear how to do this with function-based views, but not with classes. Cannot understand the philosophy of CBV when rendering forms.</p>

答:
Why should it be necessarily Class-based if it works well with functional view ?

For registration I used this :

```<code>class SignUpFormView(FormView):
    form_class = SignUpForm
    template_name  = 'authentication/registration_form.html'

    def form_valid(self, form):
        """ What to do with the valid form ?
              - Create the user and a default website
              - Send a mail to confirm the email and the account creation

        """

        user = User.objects.create_user(form.cleaned_data['username'],
                                        form.cleaned_data['email'],
                                        form.cleaned_data['password'])
        user.is_active = False
        user.save()

        date = user.date_joined.replace(microsecond=0)
        key = hashlib.sha1((u'%s%s%s' % (settings.SECRET_KEY, user.email, date)
                            ).encode('utf-8')).hexdigest()

        subject = _(u'[%s] : Subscription') % settings.SITE_NAME

        mail = render_to_string('authentication/mails/registration_confirmation.html',
                                { 'titre': subject,
                                  'pseudo': user.username,
                                  'site': settings.SITE_NAME,
                                  'user_id': user.id,
                                  'user_key': key })

        msg = EmailMessage(subject, mail, '%(site)s <%(email)s>' % {
                'site': settings.SITE_NAME, 'email': settings.DEFAULT_FROM_EMAIL
                }, [user.email])

        msg.content_subtype = "html"  # Main content is now text/html
        try:
            msg.send()
        except:
            # In debug we display the url
            print reverse('auth_activation', args=[user.id, key])

        return render_to_response("authentication/check_your_mail.html",
                                  context_instance=RequestContext(self.request))
</code>```

Body:
Why should it be necessarily Class-based if it works well with functional view ?

For registration I used this :

class SignUpFormView(FormView):
    form_class = SignUpForm
    template_name  = 'authentication/registration_form.html'

    def form_valid(self, form):
        """ What to do with the valid form ?
              - Create the user and a default website
              - Send a mail to confirm the email and the account creation

        """

        user = User.objects.create_user(form.cleaned_data['username'],
                                        form.cleaned_data['email'],
                                        form.cleaned_data['password'])
        user.is_active = False
        user.save()

        date = user.date_joined.replace(microsecond=0)
        key = hashlib.sha1((u'%s%s%s' % (settings.SECRET_KEY, user.email, date)
                            ).encode('utf-8')).hexdigest()

        subject = _(u'[%s] : Subscription') % settings.SITE_NAME

        mail = render_to_string('authentication/mails/registration_confirmation.html',
                                { 'titre': subject,
                                  'pseudo': user.username,
                                  'site': settings.SITE_NAME,
                                  'user_id': user.id,
                                  'user_key': key })

        msg = EmailMessage(subject, mail, '%(site)s <%(email)s>' % {
                'site': settings.SITE_NAME, 'email': settings.DEFAULT_FROM_EMAIL
                }, [user.email])

        msg.content_subtype = "html"  # Main content is now text/html
        try:
            msg.send()
        except:
            # In debug we display the url
            print reverse('auth_activation', args=[user.id, key])

        return render_to_response("authentication/check_your_mail.html",
                                  context_instance=RequestContext(self.request))


问:
How can I render all inline formulas in $..$ with KaTeX?
So I want to have KaTeX inline formulas like with MathJax.

But so far I've found only render() function which "draws" a string to an element.

And I need to modify a part of a text node in DOM.

I really couldn't find how to do this with KaTeX. Does it have such functionality?

MathJax could do this.

答:
As of early 2020, it seems that KaTeX 0.11.1 supports inline maths without using the "hack" in the answer by Vincent. The single dollar delimiters $ ... $ do not work but the escaped brackets \( ... \) instead do, as in the following minimal code and snippet:

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Katex 0.11.1</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css" integrity="sha384-zB1R0rpPzHqg7Kpt0Aljp8JPLqbXI3bhnPWROx27a9N0Ll6ZP/+DiW/UqRcLbRjq" crossorigin="anonymous">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.js" integrity="sha384-y23I5Q6l+B6vatafAwxRu/0oK/79VlbSz7Q9aiSZUvyWYIYsd+qj+o24G5ZU2zJz" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/auto-render.min.js" integrity="sha384-kWPLUVMOks5AQFrykwIup5lo0m3iMkkHrD0uJ4H5cjeGihAutqP0yW0J6dpFiVkI" crossorigin="anonymous" onload="renderMathInElement(document.body);"></script>
</head>

<body>
Lorem ipsum
$e^{i\pi}+1=0$ <!-- does not work -->
dolor sit amet,
\(e^{i\pi}+1=0\) <!-- this works -->
consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</body>
</html>
</code>```

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css" integrity="sha384-zB1R0rpPzHqg7Kpt0Aljp8JPLqbXI3bhnPWROx27a9N0Ll6ZP/+DiW/UqRcLbRjq" crossorigin="anonymous">

Lorem ipsum
$e^{i\pi}+1=0$
dolor sit amet,
\(e^{i\pi}+1=0\)
consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.```

After some tests, I couldn't make dollar delimiters $ ... $ work but the brackets \( ... \) here working by default are an update respect to version 0.7.1 of KaTeX (anyway still available).

Body:
As of early 2020, it seems that KaTeX 0.11.1 supports inline maths without using the "hack" in the answer by Vincent. The single dollar delimiters $ ... $ do not work but the escaped brackets \( ... \) instead do, as in the following minimal code and snippet:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Katex 0.11.1</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css" integrity="sha384-zB1R0rpPzHqg7Kpt0Aljp8JPLqbXI3bhnPWROx27a9N0Ll6ZP/+DiW/UqRcLbRjq" crossorigin="anonymous">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.js" integrity="sha384-y23I5Q6l+B6vatafAwxRu/0oK/79VlbSz7Q9aiSZUvyWYIYsd+qj+o24G5ZU2zJz" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/auto-render.min.js" integrity="sha384-kWPLUVMOks5AQFrykwIup5lo0m3iMkkHrD0uJ4H5cjeGihAutqP0yW0J6dpFiVkI" crossorigin="anonymous" onload="renderMathInElement(document.body);"></script>
</head>

<body>
Lorem ipsum
$e^{i\pi}+1=0$ <!-- does not work -->
dolor sit amet,
\(e^{i\pi}+1=0\) <!-- this works -->
consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</body>
</html>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css" integrity="sha384-zB1R0rpPzHqg7Kpt0Aljp8JPLqbXI3bhnPWROx27a9N0Ll6ZP/+DiW/UqRcLbRjq" crossorigin="anonymous">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.js" integrity="sha384-y23I5Q6l+B6vatafAwxRu/0oK/79VlbSz7Q9aiSZUvyWYIYsd+qj+o24G5ZU2zJz" crossorigin="anonymous"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/contrib/auto-render.min.js" integrity="sha384-kWPLUVMOks5AQFrykwIup5lo0m3iMkkHrD0uJ4H5cjeGihAutqP0yW0J6dpFiVkI" crossorigin="anonymous" onload="renderMathInElement(document.body);"></script>
Lorem ipsum
$e^{i\pi}+1=0$ <!-- does not work -->
dolor sit amet,
\(e^{i\pi}+1=0\) <!-- this works -->
consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

After some tests, I couldn't make dollar delimiters $ ... $ work but the brackets \( ... \) here working by default are an update respect to version 0.7.1 of KaTeX (anyway still available).


问:
Python code comparison with if validates False when it should be True
I have the following Python code below. I'm expecting the code to return True but when I run it, it seems to always return False. It seems to fail when checking if 361 is 361 but I can't work out why:

```<code>def comp(array1, array2):
    if array1 is None or array2 is None or len(array1) is 0 or len(array2) is 0 or len(array1) is not len(array2):
        return False

    aListSquared = [x * x for x in sorted(array1)]
    array2.sort()

    print(aListSquared)
    print(array2)

    for x in range(len(aListSquared)):
        print('{0}:{1}'.format(aListSquared[x], type(aListSquared[x])))
        print('{0}:{1}'.format(array2[x], type(array2[x])))

        if int(aListSquared[x]) is not int(array2[x]):
            return False

    return True

a1 = [121, 144, 19, 161, 19, 144, 19, 11]
a2 = [11 * 11, 121 * 121, 144 * 144, 19 * 19, 161 * 161, 19 * 19, 144 * 144, 19 * 19]
print(comp(a1, a2))

</code>```

Can anyone tell me what i'm doing wrong or why the validation doesn't seem to be working correctly?

Many Thanks

答:
This syntax

```<code>if int(aListSquared[x]) is not int(array2[x]):
</code>```

is not the same as

```<code>if int(aListSquared[x]) != int(array2[x]):
</code>```

please refer to this Python != operation vs "is not"

Body:
I have the following Python code below. I'm expecting the code to return True but when I run it, it seems to always return False. It seems to fail when checking if 361 is 361 but I can't work out why:

def comp(array1, array2):
    if array1 is None or array2 is None or len(array1) is 0 or len(array2) is 0 or len(array1) is not len(array2):
        return False

    aListSquared = [x * x for x in sorted(array1)]
    array2.sort()

    print(aListSquared)
    print(array2)

    for x in range(len(aListSquared)):
        print('{0}:{1}'.format(aListSquared[x], type(aListSquared[x])))
        print('{0}:{1}'.format(array2[x], type(array2[x])))

        if int(aListSquared[x]) is not int(array2[x]):
            return False

    return True

a1 = [121, 144, 19, 161, 19, 144, 19, 11]
a2 = [11 * 11, 121 * 121, 144 * 144, 19 * 19, 161 * 161, 19 * 19, 144 * 144, 19 * 19]
print(comp(a1, a2))

Can anyone tell me what i'm doing wrong or why the validation doesn't seem to be working correctly?

Many Thanks

Body:
This syntax

if int(aListSquared[x]) is not int(array2[x]):

is not the same as

if int(aListSquared[x]) != int(array2[x]):

please refer to this Python != operation vs "is not"


问:
Alternative Way to Load Large Json File
I am trying to load a large json file (around 4G) as a pandas dataframe, but the following method does not work for file > around 2G. Is there any alternative method?

data_dir = 'data.json'
 my_data = pd.read_json(data_dir, lines = True)

I tried ijson but have no idea how to covert it to a dataframe.

答:
Loading the Large document in memory may not be best approach in this case. This size of JSON may require you to use a different approach for parsing. Try using Streaming parsers instead. Some options

https://pypi.org/project/json-stream-parser/

https://pypi.org/project/ijson/

The key is to not load the entire document in memory. This is similar to SAX parsing in the XML world.

I am not a python expert, however, there should be a good library that can already do it for you.

Title: Alternative Way to Load Large Json File


问:
Count animation from number A to B
I am updating a numeric value inside an element by doing intervalled ajax requests.

To make the whole thing a bit more alive, I want to count from the current value to the new one, by partially in- or decreasing the value over a time of n sec.

So basically something like this:

```<code><div id="value">100</div>
<script type="text/javascript">
    /** Decrease $value (over a time of 2 seconds) till it reaches 25 */
    $value.increaseAnimation(-75, {duration:2});
</script>
</code>```

Is there a javascript library for doing so?

答:
Current solutions do update more often than needed. Here a frame based approach, which is accurate:

function animateValue(obj, start, end, duration) {
  let startTimestamp = null;
  const step = (timestamp) => {
    if (!startTimestamp) startTimestamp = timestamp;
    const progress = Math.min((timestamp - startTimestamp) / duration, 1);
    obj.innerHTML = Math.floor(progress * (end - start) + start);
    if (progress < 1) {
      window.requestAnimationFrame(step);
    }
  };
  window.requestAnimationFrame(step);
}

const obj = document.getElementById('value');
animateValue(obj, 100, -25, 2000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {font-size: 50px;}</code>```

100
```

Title: Count animation from number A to B

Body:
I am updating a numeric value inside an element by doing intervalled ajax requests.

To make the whole thing a bit more alive, I want to count from the current value to the new one, by partially in- or decreasing the value over a time of n sec.

So basically something like this:

100

Is there a javascript library for doing so?

Body:
Current solutions do update more often than needed. Here a frame based approach, which is accurate:

function animateValue(obj, start, end, duration) {
  let startTimestamp = null;
  const step = (timestamp) => {
    if (!startTimestamp) startTimestamp = timestamp;
    const progress = Math.min((timestamp - startTimestamp) / duration, 1);
    obj.innerHTML = Math.floor(progress * (end - start) + start);
    if (progress < 1) {
      window.requestAnimationFrame(step);
    }
  };
  window.requestAnimationFrame(step);
}

const obj = document.getElementById('value');
animateValue(obj, 100, -25, 2000);

div {font-size: 50px;}

<div id="value">100</div>


问:
Carousel created using vue not rotating as it should
I have a carousel that I found that was created using vanilla javascript and html.  I tried converting it to Vue but am having some issues.  It is supposed to dynamically pull from a SharePoint list.  In the code and pen below, I use an array of objects to simulate a SharePoint list. Instead of it rotating, all the images are listed vertically on top of each other.

new Vue({
  el: '#carouselApp',
  data: function() {
    return {
      images: [{
          src: 'https://images.unsplash.com/photo-1533048324814-79b0a31982f1?ixlib=rb-1.2.1&dpr=1&auto=format&fit=crop&w=416&h=312&q=60',
          text: 'Tech trends',
          num: 0
        },
        {
          src: 'https://thumbs.dreamstime.com/b/rainbow-butterfly-colorful-wings-colored-all-colors-vibgyor-very-attractive-placed-black-white-30774133.jpg',
          text: 'Tech Spot',
          num: 1
        },
        {
          src: 'https://image.shutterstock.com/image-photo/color-butterfly-isolated-on-white-260nw-570560110.jpg',
          text: 'Tech Idea',
          num: 2

        },
        {
          src: 'http://static.nautil.us/16630_c2e2a6521fbf5aab3693d9dd7ca9cb1e.jpg',
          text: 'Yellowy Orange',
          num: 3

        },
        {
          src: 'https://static.independent.co.uk/s3fs-public/thumbnails/image/2020/01/07/13/monarch-butterfly.jpg?width=1368&height=912&fit=bounds&format=pjpg&auto=webp&quality=70',
          text: 'Tech chip',
          num: 4
        }
      ]
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>

<!DOCTYPE html>
<html lang="en" xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882">

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="/SiteAssets/_script/vue.js"></script>
  <style>
    .glyphicon {
      color: #ffffff
    }
  </style>

</head>

<body>
  <!-- https://www.w3schools.com/bootstrap/bootstrap_carousel.asp -->
  <div id="carouselApp" class="container">
    <div class="row">
      <div id="carousel-example-generic" class="carousel slide" data-ride="carousel" style="width:501px;margin-top:5px">
        <!-- Indicators -->
        <ol class="carousel-indicators" v-for="(img, index) in images.length">
          <li data-target="#carousel-example-generic" :data-slide-to="index" class="active"></li>
        </ol>

        <!-- Wrapper for slides -->
        <div class="carousel-inner" role="listbox" v-for="(item, index) in images">
          <div class="item active">
            <img v-bind:src="item.src" alt="..." style=" width:100%;height:303px">
            <div class="carousel-caption">
              {{item.text}}
            </div>
          </div>
        </div>

        <!-- Controls -->

          <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
          <span class="sr-only">Previous</span>

          <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
          <span class="sr-only">Next</span>

      </div>
    </div>

  </div>

</body>

</html></code>```

答:
The way you would handle this in Vue is fundamentally different than how you would handle this in jQuery.

Loosely speaking, Vue would be declarative and jQuery would be imperative. "Thinking in Vue" would have you break this carousel down into components - meaning, you may have a CarouselContainer component which lets you specify height/width/what not.. Then you may have a CarouselSlide component which lives in the container, and holds the actual image.. it would look something like this:

```<code>// Carousel.vue
...
<CarouselContainer /* props, etc.. */>
  <CarouselSlide /* ... */>
    <!-- maybe some children -->
  </CarouselSlide>
</CarouselContainer>
...
</code>```

This article is a great example of how to build out and structure something like a carousel in Vue. You can view the repo here as well..

Now, to elaborate on the code you provided, you could do something rudimentary like this in Vue: (this is just to get an idea across) CodePen mirror can be found here

/*Refactored carousel from this site: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow_autohttps://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow_auto*/
/*Would prefer the images to come from a list. Will work on that later*/
new Vue({
  el: '#carouselApp',
  methods: {
    browse(direction) {
      if (direction === 'forward') {
        if (this.currentIndex + 1 === this.images.length) {
          this.currentIndex = 0;
        } else {
          this.currentIndex++;
        }
      }
      if (direction === 'backward') {
        if (this.currentIndex === 0) {
          this.currentIndex = this.images.length - 1;
        } else {
          this.currentIndex--;
        }
      }
    }
  },
  data: function() {
    return {
      currentIndex: 0,
      images: [{
          src: 'https://images.unsplash.com/photo-1533048324814-79b0a31982f1?ixlib=rb-1.2.1&dpr=1&auto=format&fit=crop&w=416&h=312&q=60',
          text: 'Tech trends',
          num: 0
        },
        {
          src: 'https://thumbs.dreamstime.com/b/rainbow-butterfly-colorful-wings-colored-all-colors-vibgyor-very-attractive-placed-black-white-30774133.jpg',
          text: 'Tech Spot',
          num: 1
        },
        {
          src: 'https://image.shutterstock.com/image-photo/color-butterfly-isolated-on-white-260nw-570560110.jpg',
          text: 'Tech Idea',
          num: 2

        },
        {
          src: 'http://static.nautil.us/16630_c2e2a6521fbf5aab3693d9dd7ca9cb1e.jpg',
          text: 'Yellowy Orange',
          num: 3

        },
        {
          src: 'https://static.independent.co.uk/s3fs-public/thumbnails/image/2020/01/07/13/monarch-butterfly.jpg?width=1368&height=912&fit=bounds&format=pjpg&auto=webp&quality=70',
          text: 'Tech chip',
          num: 4
        }
      ]
    }
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>

<!DOCTYPE html>
<html lang="en" xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882">

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="/SiteAssets/_script/vue.js"></script>
  <style>
    .glyphicon {
      color: #ffffff
    }
  </style>

</head>

<body>
  <!-- https://www.w3schools.com/bootstrap/bootstrap_carousel.asp -->
  <div id="carouselApp" class="container">
    <div class="row">
      <div id="carousel-example-generic" class="carousel slide" data-ride="carousel" style="width:501px;margin-top:5px">
        <!-- Indicators -->
        <ol class="carousel-indicators" v-for="(img, index) in images.length">
          <li data-target="#carousel-example-generic" :data-slide-to="index" class="active"></li>
        </ol>

        <!-- Wrapper for slides -->
        <div class="carousel-inner" role="listbox" v-for="(item, index) in images">
          <div v-if="currentIndex === index" class="item active">
            <img v-bind:src="item.src" alt="..." style=" width:100%;height:303px">
            <div class="carousel-caption">
              {{item.text}}<br/>
              {{currentIndex + 1}} / {{images.length}}
            </div>
          </div>
        </div>

        <!-- Controls -->

          <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
          <span class="sr-only">Previous</span>

          <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
          <span class="sr-only">Next</span>

      </div>
    </div>

  </div>

</body>

</html></code>```

Body:
I have a carousel that I found that was created using vanilla javascript and html.  I tried converting it to Vue but am having some issues.  It is supposed to dynamically pull from a SharePoint list.  In the code and pen below, I use an array of objects to simulate a SharePoint list. Instead of it rotating, all the images are listed vertically on top of each other.

new Vue({
  el: '#carouselApp',
  data: function() {
    return {
      images: [{
          src: 'https://images.unsplash.com/photo-1533048324814-79b0a31982f1?ixlib=rb-1.2.1&dpr=1&auto=format&fit=crop&w=416&h=312&q=60',
          text: 'Tech trends',
          num: 0
        },
        {
          src: 'https://thumbs.dreamstime.com/b/rainbow-butterfly-colorful-wings-colored-all-colors-vibgyor-very-attractive-placed-black-white-30774133.jpg',
          text: 'Tech Spot',
          num: 1
        },
        {
          src: 'https://image.shutterstock.com/image-photo/color-butterfly-isolated-on-white-260nw-570560110.jpg',
          text: 'Tech Idea',
          num: 2

        },
        {
          src: 'http://static.nautil.us/16630_c2e2a6521fbf5aab3693d9dd7ca9cb1e.jpg',
          text: 'Yellowy Orange',
          num: 3

        },
        {
          src: 'https://static.independent.co.uk/s3fs-public/thumbnails/image/2020/01/07/13/monarch-butterfly.jpg?width=1368&height=912&fit=bounds&format=pjpg&auto=webp&quality=70',
          text: 'Tech chip',
          num: 4
        }
      ]
    }
  }
});

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

              {{item.text}}

          Previous

          Next

Body:
The way you would handle this in Vue is fundamentally different than how you would handle this in jQuery.

Loosely speaking, Vue would be declarative and jQuery would be imperative. "Thinking in Vue" would have you break this carousel down into components - meaning, you may have a CarouselContainer component which lets you specify height/width/what not.. Then you may have a CarouselSlide component which lives in the container, and holds the actual image.. it would look something like this:

// Carousel.vue
...
<CarouselContainer /* props, etc.. */>
  <CarouselSlide /* ... */>
    <!-- maybe some children -->
  </CarouselSlide>
</CarouselContainer>
...

This article is a great example of how to build out and structure something like a carousel in Vue. You can view the repo here as well..

Now, to elaborate on the code you provided, you could do something rudimentary like this in Vue: (this is just to get an idea across) CodePen mirror can be found here

/*Refactored carousel from this site: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow_autohttps://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow_auto*/
/*Would prefer the images to come from a list. Will work on that later*/
new Vue({
  el: '#carouselApp',
  methods: {
    browse(direction) {
      if (direction === 'forward') {
        if (this.currentIndex + 1 === this.images.length) {
          this.currentIndex = 0;
        } else {
          this.currentIndex++;
        }
      }
      if (direction === 'backward') {
        if (this.currentIndex === 0) {
          this.currentIndex = this.images.length - 1;
        } else {
          this.currentIndex--;
        }
      }
    }
  },
  data: function() {
    return {
      currentIndex: 0,
      images: [{
          src: 'https://images.unsplash.com/photo-1533048324814-79b0a31982f1?ixlib=rb-1.2.1&dpr=1&auto=format&fit=crop&w=416&h=312&q=60',
          text: 'Tech trends',
          num: 0
        },
        {
          src: 'https://thumbs.dreamstime.com/b/rainbow-butterfly-colorful-wings-colored-all-colors-vibgyor-very-attractive-placed-black-white-30774133.jpg',
          text: 'Tech Spot',
          num: 1
        },
        {
          src: 'https://image.shutterstock.com/image-photo/color-butterfly-isolated-on-white-260nw-570560110.jpg',
          text: 'Tech Idea',
          num: 2

        },
        {
          src: 'http://static.nautil.us/16630_c2e2a6521fbf5aab3693d9dd7ca9cb1e.jpg',
          text: 'Yellowy Orange',
          num: 3

        },
        {
          src: 'https://static.independent.co.uk/s3fs-public/thumbnails/image/2020/01/07/13/monarch-butterfly.jpg?width=1368&height=912&fit=bounds&format=pjpg&auto=webp&quality=70',
          text: 'Tech chip',
          num: 4
        }
      ]
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js"></script>

<!DOCTYPE html>
<html lang="en" xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882">

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="/SiteAssets/_script/vue.js"></script>
  <style>
    .glyphicon {
      color: #ffffff
    }
  </style>

</head>

<body>
  <!-- https://www.w3schools.com/bootstrap/bootstrap_carousel.asp -->
  <div id="carouselApp" class="container">
    <div class="row">
      <div id="carousel-example-generic" class="carousel slide" data-ride="carousel" style="width:501px;margin-top:5px">
        <!-- Indicators -->
        <ol class="carousel-indicators" v-for="(img, index) in images.length">
          <li data-target="#carousel-example-generic" :data-slide-to="index" class="active"></li>
        </ol>

        <!-- Wrapper for slides -->
        <div class="carousel-inner" role="listbox" v-for="(item, index) in images">
          <div v-if="currentIndex === index" class="item active">
            <a href="/News/Pages/Default.aspx"><img v-bind:src="item.src" alt="..." style=" width:100%;height:303px"></a>
            <div class="carousel-caption">
              {{item.text}}<br/>
              {{currentIndex + 1}} / {{images.length}}
            </div>
          </div>
        </div>

        <!-- Controls -->
        <a @click="browse('backward')" class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
          <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
          <span class="sr-only">Previous</span>
        </a>
        <a @click="browse('forward')" class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
          <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
          <span class="sr-only">Next</span>
        </a>
      </div>
    </div>

  </div>

</body>

</html>


问:
Can anyone tell me how to hide the contents of a text box
I have a drop down button named bank.
I have 3 text boxes named t1, t2 and t3
if i am not selecting any of the banks all the three text boxes should be enabled..

am getting it..
but my problem is..

first i have selected any one from the drop down button, and after some time i have changed it to choose bank(i.e; the 0th index).. but even then the data in text boxes are still there itself.. how to hide it..

答:
you cannot hide the data, you can clear the data from the textbox before disabling using following script</p>

```<code>document.getElementById("yourTextBoxID").value = "";
</code>```

Body:
you cannot hide the data, you can clear the data from the textbox before disabling using following script

document.getElementById("yourTextBoxID").value = "";


问:
Where is the Application.DoEvents() in WPF?
I have the following sample code that zooms each time a button is pressed:

XAML:

```<code><Window x:Class="WpfApplication12.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <Canvas x:Name="myCanvas">

        <Canvas.LayoutTransform>
            <ScaleTransform x:Name="myScaleTransform" />
        </Canvas.LayoutTransform>

        <Button Content="Button"
                Name="myButton"
                Canvas.Left="50"
                Canvas.Top="50"
                Click="myButton_Click" />
    </Canvas>
</Window>
</code>```

*.cs

```<code>public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void myButton_Click(object sender, RoutedEventArgs e)
    {
        Console.WriteLine("scale {0}, location: {1}",
            myScaleTransform.ScaleX,
            myCanvas.PointToScreen(GetMyByttonLocation()));

        myScaleTransform.ScaleX =
            myScaleTransform.ScaleY =
            myScaleTransform.ScaleX + 1;

        Console.WriteLine("scale {0}, location: {1}",
            myScaleTransform.ScaleX,
            myCanvas.PointToScreen(GetMyByttonLocation()));
    }

    private Point GetMyByttonLocation()
    {
        return new Point(
            Canvas.GetLeft(myButton),
            Canvas.GetTop(myButton));
    }
}
</code>```

the output is:

```<code>scale 1, location: 296;315
scale 2, location: 296;315

scale 2, location: 346;365
scale 3, location: 346;365

scale 3, location: 396;415
scale 4, location: 396;415
</code>```

as you can see, there is a problem, that I thought solve by using Application.DoEvents(); but... it does not exist a priori in .NET 4.

What to do?

答:
Answering the original question: Where is DoEvents?

I think DoEvents is VBA. And VBA does not seem to have a Sleep function. But VBA has a way to get exactly the same effect as a Sleep or Delay. Seems to me that DoEvents is equivalent to Sleep(0).

In VB and C#, you are dealing in .NET. And the original question is a C# question. In C#, you would use Thread.Sleep(0), where 0 is 0 milliseconds.

You need

```<code>using System.Threading.Task;
</code>```

at the top of the file in order to use

```<code>Sleep(100);
</code>```

in your code.

Body:
I have the following sample code that zooms each time a button is pressed:

XAML:

<Window x:Class="WpfApplication12.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <Canvas x:Name="myCanvas">

        <Canvas.LayoutTransform>
            <ScaleTransform x:Name="myScaleTransform" />
        </Canvas.LayoutTransform>

        <Button Content="Button"
                Name="myButton"
                Canvas.Left="50"
                Canvas.Top="50"
                Click="myButton_Click" />
    </Canvas>
</Window>

*.cs

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void myButton_Click(object sender, RoutedEventArgs e)
    {
        Console.WriteLine("scale {0}, location: {1}",
            myScaleTransform.ScaleX,
            myCanvas.PointToScreen(GetMyByttonLocation()));

        myScaleTransform.ScaleX =
            myScaleTransform.ScaleY =
            myScaleTransform.ScaleX + 1;

        Console.WriteLine("scale {0}, location: {1}",
            myScaleTransform.ScaleX,
            myCanvas.PointToScreen(GetMyByttonLocation()));
    }

    private Point GetMyByttonLocation()
    {
        return new Point(
            Canvas.GetLeft(myButton),
            Canvas.GetTop(myButton));
    }
}

the output is:

scale 1, location: 296;315
scale 2, location: 296;315

scale 2, location: 346;365
scale 3, location: 346;365

scale 3, location: 396;415
scale 4, location: 396;415

as you can see, there is a problem, that I thought solve by using Application.DoEvents(); but... it does not exist a priori in .NET 4.

What to do?

Body:
Answering the original question: Where is DoEvents?

I think DoEvents is VBA. And VBA does not seem to have a Sleep function. But VBA has a way to get exactly the same effect as a Sleep or Delay. Seems to me that DoEvents is equivalent to Sleep(0).

In VB and C#, you are dealing in .NET. And the original question is a C# question. In C#, you would use Thread.Sleep(0), where 0 is 0 milliseconds.

You need

using System.Threading.Task;

at the top of the file in order to use

Sleep(100);

in your code.


问:
Is it possible to reuse a double quoted string with variables?
The application I'm writing generates some HTML server side though it could be applied to just any string.

```<code>$badges = [
    "<span class='badge badge--brand badge--inline'>$target</span>",
    "<span class='badge badge--dark badge--inline'>$target</span>",
    "<span class='badge badge--primary badge--inline'>$target</span>",
    "<span class='badge badge--success badge--inline'>$target</span>",
    "<span class='badge badge--info badge--inline'>$target</span>",
    "<span class='badge badge--warning badge--inline'>$target</span>",
    "<span class='badge badge--danger badge--inline'>$target</span>",
];

$TargetStr = 'one,two,three';

$Targets = explode(',', $TargetStr);
$Badges = '';
foreach ($Targets as $index => $target) {
    $Badges .= $badges[$index % count($badges)];
}
echo $Badges;
</code>```

The desired output would be:

```<code><span class='badge badge--brand badge--inline'>one</span><span class='badge badge--dark badge--inline'>two</span><span class='badge badge--primary badge--inline'>three</span>
</code>```

I realize the $target variables are being evaluated inside the array, before it reaches the loop. With error reporting, this fails and without it, there is nothing in place of $target.

I can certainly just leverage str_replace and achieve desired results but this seemed like an interesting solution if I could get it to work.

Is it possible to achieve this? I haven't tried using eval and I would prefer not to as the $TargetStr is user supplied.

答:
this works better, I think:</p>

```<code><?php
        //Enter your code here, enjoy!
$badges = [
    '<span class="badge badge--brand badge--inline">$target</span>',
    '<span class="badge badge--dark badge--inline">$target</span>',
    '<span class="badge badge--primary badge--inline">$target</span>',
    '<span class="badge badge--success badge--inline">$target</span>',
    '<span class="badge badge--info badge--inline">$target</span>',
    '<span class="badge badge--warning badge--inline">$target</span>',
    '<span class="badge badge--danger badge--inline">$target</span>',
];

$TargetStr = 'one,two,three';

$Targets = explode(',', $TargetStr);
$Badges = '';
foreach ($Targets as $index => $target) {
    $Badges .= eval(" ?>".preg_replace('/(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/', '<?php echo $1; ?>', $badges[$index % count($badges)]). "<?php ");
}
echo $Badges;
</code>```

Body:
The application I'm writing generates some HTML server side though it could be applied to just any string.

$badges = [
    "$target",
    "$target",
    "$target",
    "$target",
    "$target",
    "$target",
    "$target",
];

$TargetStr = 'one,two,three';

$Targets = explode(',', $TargetStr);
$Badges = '';
foreach ($Targets as $index => $target) {
    $Badges .= $badges[$index % count($badges)];
}
echo $Badges;

The desired output would be:

onetwothree

I realize the $target variables are being evaluated inside the array, before it reaches the loop. With error reporting, this fails and without it, there is nothing in place of $target.

I can certainly just leverage str_replace and achieve desired results but this seemed like an interesting solution if I could get it to work.

Is it possible to achieve this? I haven't tried using eval and I would prefer not to as the $TargetStr is user supplied.

Body:
this works better, I think:

<?php
        //Enter your code here, enjoy!
$badges = [
    '<span class="badge badge--brand badge--inline">$target</span>',
    '<span class="badge badge--dark badge--inline">$target</span>',
    '<span class="badge badge--primary badge--inline">$target</span>',
    '<span class="badge badge--success badge--inline">$target</span>',
    '<span class="badge badge--info badge--inline">$target</span>',
    '<span class="badge badge--warning badge--inline">$target</span>',
    '<span class="badge badge--danger badge--inline">$target</span>',
];

$TargetStr = 'one,two,three';

$Targets = explode(',', $TargetStr);
$Badges = '';
foreach ($Targets as $index => $target) {
    $Badges .= eval(" ?>".preg_replace('/(\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/', '<?php echo $1; ?>', $badges[$index % count($badges)]). "<?php ");
}
echo $Badges;


问:
How to set sockaddr_in6::sin6_addr byte order to network byte order?
I developing a network application and using socket APIs.

I want to set sin6_addr byte order of sockaddr_in6 structure.

For 16 bits or 32 bits variables, it is simple: Using htons or htonl:

```<code>// IPv4
sockaddr_in addr;
addr.sin_port = htons(123);
addr.sin_addr.s_addr = htonl(123456);
</code>```

But for 128 bits variables, I dont know how to set byte order to network byte order:

```<code>// IPv6
sockaddr_in6 addr;
addr.sin6_port = htons(123);
addr.sin6_addr.s6_addr = ??? // 16 bytes with network byte order but how to set?
</code>```

Some answers may be using htons for 8 times (2 * 8 = 16 bytes), or using htonl for 4 times (4 * 4 = 16 bytes), but I don't know which way is correct.

Thanks.

答: The usual thing would be to use one of the hostname lookup routines and use the result of that, which is already in network byte order. How come you're dealing with hardcoded numeric IP addresses at all?</p>

Body:
I developing a network application and using socket APIs.

I want to set sin6_addr byte order of sockaddr_in6 structure.

For 16 bits or 32 bits variables, it is simple: Using htons or htonl:

// IPv4
sockaddr_in addr;
addr.sin_port = htons(123);
addr.sin_addr.s_addr = htonl(123456);

But for 128 bits variables, I dont know how to set byte order to network byte order:

// IPv6
sockaddr_in6 addr;
addr.sin6_port = htons(123);
addr.sin6_addr.s6_addr = ??? // 16 bytes with network byte order but how to set?

Some answers may be using htons for 8 times (2 * 8 = 16 bytes), or using htonl for 4 times (4 * 4 = 16 bytes), but I don't know which way is correct.

Thanks.


问:
Extracting a table field with CSV data
I'm looking into ways to extract data from a particular field in a table. The field has CSV data, and I'd like to put them all in a temp table as individual entries. For example,

```<code>Create Table #temp (CsvData Varchar(500))
Insert Into #temp Values ('1,2,3,4'), ('3,6,7,9'), ('a,b,c,d'), ('d,f,g,h')
</code>```

How can I extract the data from this CsvData column into another temp table? Ideally I'd like to get unique values, but at this point I'm willing to clean up the data after I get them all.

答:
Working example:</p>

```<code>    Create Table #temp (CsvData Varchar(500));
    Create Table #temp2 (OneValue Varchar(500));
    Insert Into #temp Values
    ('1,2,3,4'), ('3,6,7,9'), ('a,b,c,d'), ('d,f,g,h');
    DECLARE @s VarChar(Max) = '';
    SELECT @s = @s + Replace('INSERT INTO #temp2
    VALUES('''+CsvData+''')',',','''),(''') FROM #temp;
    PRINT @s;
    EXEC (@s);
    SELECT * FROM #temp2;
    DROP TABLE #temp;
    DROP TABLE #temp2;
</code>```

Title: Extracting a table field with CSV data

Body:
I'm looking into ways to extract data from a particular field in a table. The field has CSV data, and I'd like to put them all in a temp table as individual entries. For example,

Create Table #temp (CsvData Varchar(500))
Insert Into #temp Values ('1,2,3,4'), ('3,6,7,9'), ('a,b,c,d'), ('d,f,g,h')

How can I extract the data from this CsvData column into another temp table? Ideally I'd like to get unique values, but at this point I'm willing to clean up the data after I get them all.

Body:
Working example:

    Create Table #temp (CsvData Varchar(500));
    Create Table #temp2 (OneValue Varchar(500));
    Insert Into #temp Values
    ('1,2,3,4'), ('3,6,7,9'), ('a,b,c,d'), ('d,f,g,h');
    DECLARE @s VarChar(Max) = '';
    SELECT @s = @s + Replace('INSERT INTO #temp2
    VALUES('''+CsvData+''')',',','''),(''') FROM #temp;
    PRINT @s;
    EXEC (@s);
    SELECT * FROM #temp2;
    DROP TABLE #temp;
    DROP TABLE #temp2;


问:
Websphere Application Server Classloader policy
How do I set "Classloader policy" to "Single" from config file or programatically on websphere apllication server , since I don't have access to admin console.</p>

答:
Take a look at the instructions for Modifying WAR class loader policies for applications using wsadmin scripting. If you also want to modify the application classloader policy for a server, take a look at the following wsadmin Jython example that modifies both the application classloader policy and delegation mode for server "server1". Be sure to synchronize configuration modifications to the nodes when using IBM WebSphere Application Server Network Deployment.</p>

```<code>wsadmin> appSrv=AdminConfig.getid("/Server:server1/ApplicationServer:/")
wsadmin> AdminConfig.modify(appSrv, '[[applicationClassLoaderPolicy "SINGLE"] [applicationClassLoadingMode "PARENT_LAST"]]')
wsadmin> AdminConfig.save()
</code>```

Body:
Take a look at the instructions for Modifying WAR class loader policies for applications using wsadmin scripting. If you also want to modify the application classloader policy for a server, take a look at the following wsadmin Jython example that modifies both the application classloader policy and delegation mode for server "server1". Be sure to synchronize configuration modifications to the nodes when using IBM WebSphere Application Server Network Deployment.

wsadmin> appSrv=AdminConfig.getid("/Server:server1/ApplicationServer:/")
wsadmin> AdminConfig.modify(appSrv, '[[applicationClassLoaderPolicy "SINGLE"] [applicationClassLoadingMode "PARENT_LAST"]]')
wsadmin> AdminConfig.save()


问:
Exclude a letter in Regex Pattern
I am trying to create a Regex pattern for <String>-<String>. This is my current pattern:

(\w+\-\w+).

The first String is not allowed to be "W". However, it can still contain "W"s if it's more than one letter long.

For example:
W-80 -> invalid
W42-80 -> valid

How can this be achieved?

答:
So your first string can be either: one character but not W or 2+ characters. Simple pattern to achieve that is:

```<code>([^W]|\w{2,})-\w+
</code>```

But this pattern is not entirely correct, because now it allows any character for first part, but originally only \w characters were expected to be allowed. So correct pattern is:

```<code>([\w&&[^W]]|\w{2,})-\w+
</code>```

Pattern [\w&&[^W]] means any character from \w character class except W character.

Title: Exclude a letter in Regex Pattern

Body:
So your first string can be either: one character but not W or 2+ characters. Simple pattern to achieve that is:

([^W]|\w{2,})-\w+

But this pattern is not entirely correct, because now it allows any character for first part, but originally only \w characters were expected to be allowed. So correct pattern is:

([\w&&[^W]]|\w{2,})-\w+

Pattern [\w&&[^W]] means any character from \w character class except W character.


问:
How to create a finite length generator from an infinite generator
So I have a javascript generator (below) which continues to yield random numbers ad infinitum.

```<code>function* createRandomNumberStream(): IterableIterator<number> {
  while (true) {
    yield Math.random()
  }
}
</code>```

How can I write a generator function with the type (it: Iterable<T>, n: number) => Iterable<T>, where it returns a new iterable which ends after n yields?

Note the createRandomStream() generator isn't really relevant, it's just an example of an unending iterable generator. I'm trying to make a generator which basically slices an iterable.

答:
Is this what you want?</p>

```<code>function* createRandomNumberStream() {
    while (true) {
        yield Math.random()
    }
}

function* take<T>(it: Iterator<T>, count: number) {
    let currentCount = 0
    while (currentCount++ < count) {
        yield it.next().value
    }
}

const stream = take(createRandomNumberStream(), 3)

for (const num of stream) {
    console.log(num)
}
</code>```

Body:
So I have a javascript generator (below) which continues to yield random numbers ad infinitum.

function* createRandomNumberStream(): IterableIterator<number> {
  while (true) {
    yield Math.random()
  }
}

How can I write a generator function with the type (it: Iterable<T>, n: number) => Iterable<T>, where it returns a new iterable which ends after n yields?

Note the createRandomStream() generator isn't really relevant, it's just an example of an unending iterable generator. I'm trying to make a generator which basically slices an iterable.

Body:
Is this what you want?

function* createRandomNumberStream() {
    while (true) {
        yield Math.random()
    }
}

function* take<T>(it: Iterator<T>, count: number) {
    let currentCount = 0
    while (currentCount++ < count) {
        yield it.next().value
    }
}

const stream = take(createRandomNumberStream(), 3)

for (const num of stream) {
    console.log(num)
}


问:
How to use pushdown predicates in Presto connector
I would like to extend Presto's example-http connector to add the relevant predicates to the REST API call made by the connector to  minimize data transfer.

I have been spending now quite a few hours looking through the documentation, online posts and the presto source code but I can't figure out which calls are involved and how to go about this.

It's being mentioned in so many places, but I cannot find any simple code samples or internal descriptions. I'm sure I'm missing something obvious here.

答:
After downloading the source code and running it in a debugger I found it to be rather straight forward on one hand, while restrictive on the other.

The straight forward part is that we simply have to override isPushdownFilterSupported and pushdownFilter when implementing the ConnectorMetadata interface.

The restrictive part is that the query planner now believes that the connector can deal with any type and combination of table filters. In my case, I would only want to take care of those, the remote API I'm calling is supporting and have Presto take care of the rest.

It appears the Presto team is fully aware of that, as a) the methods are labeled @Experimental and b) by the respective comments This interface can be replaced with a connector optimizer rule once the engine supports these (#12546). This would be clearly the right approach for my use case.

```<code>   /**
     * Experimental: if true, the engine will invoke pushdownFilter instead of getTableLayouts.
     *
     * This interface can be replaced with a connector optimizer rule once the engine supports these (#12546).
     */
    @Experimental
    default boolean isPushdownFilterSupported(ConnectorSession session, ConnectorTableHandle tableHandle)
    {
        return false;
    }

    /**
     * Experimental: returns table layout that encapsulates the given filter.
     *
     * This interface can be replaced with a connector optimizer rule once the engine supports these (#12546).
     */
    @Experimental
    default ConnectorPushdownFilterResult pushdownFilter(ConnectorSession session, ConnectorTableHandle tableHandle, RowExpression filter, Optional<ConnectorTableLayoutHandle> currentLayoutHandle)
    {
        throw new UnsupportedOperationException();
    }
</code>```

Body:
After downloading the source code and running it in a debugger I found it to be rather straight forward on one hand, while restrictive on the other.

The straight forward part is that we simply have to override isPushdownFilterSupported and pushdownFilter when implementing the ConnectorMetadata interface.

The restrictive part is that the query planner now believes that the connector can deal with any type and combination of table filters. In my case, I would only want to take care of those, the remote API I'm calling is supporting and have Presto take care of the rest.

It appears the Presto team is fully aware of that, as a) the methods are labeled @Experimental and b) by the respective comments This interface can be replaced with a connector optimizer rule once the engine supports these (#12546). This would be clearly the right approach for my use case.

   /**
     * Experimental: if true, the engine will invoke pushdownFilter instead of getTableLayouts.
     *
     * This interface can be replaced with a connector optimizer rule once the engine supports these (#12546).
     */
    @Experimental
    default boolean isPushdownFilterSupported(ConnectorSession session, ConnectorTableHandle tableHandle)
    {
        return false;
    }

    /**
     * Experimental: returns table layout that encapsulates the given filter.
     *
     * This interface can be replaced with a connector optimizer rule once the engine supports these (#12546).
     */
    @Experimental
    default ConnectorPushdownFilterResult pushdownFilter(ConnectorSession session, ConnectorTableHandle tableHandle, RowExpression filter, Optional<ConnectorTableLayoutHandle> currentLayoutHandle)
    {
        throw new UnsupportedOperationException();
    }


问:
How to subtract two images using python opencv2 to get the foreground object
Is there any way to subtract two images in python opencv2 ?

Image 1 : Any image (eg. a house Image) (static image)

Image 2 : The same Image with an Object (In house, a person is standing...)
(static image + dynamic objects)

Image 3 = Image 2 - Image 1

If we subtract Image2 from Image1 means Image3 should give Object(person) only.

答:
@dvigneshwr's answer does a subtraction where the resulting negative values are rounded up to 0.  @Taha Anwar M-Holmes' answer preserves the negatives but changes the datatype of the resulting array so its no longer a conventional image type.

For those wanting to identify a foreground from a background image based on the absolute difference in values and return an array of the same data type as the inputs (that's how I ended up here), use absdiff.

Assuming the arrays are the same width and height...

import cv2 as cv

image3 = cv.absdiff(image1, image2)
```

Its worth noting that the OP did not provide any details wrt to the images being subtracted here... depending on what the contents of the images are, all of these approaches may answer the OP's question.

Body:
@dvigneshwr's answer does a subtraction where the resulting negative values are rounded up to 0.  @Taha Anwar M-Holmes' answer preserves the negatives but changes the datatype of the resulting array so its no longer a conventional image type.

For those wanting to identify a foreground from a background image based on the absolute difference in values and return an array of the same data type as the inputs (that's how I ended up here), use absdiff.

Assuming the arrays are the same width and height...

import cv2 as cv

image3 = cv.absdiff(image1, image2)

Its worth noting that the OP did not provide any details wrt to the images being subtracted here... depending on what the contents of the images are, all of these approaches may answer the OP's question.


问:
Not able to trim timestamp format in sql loader
I am new to SQL loader and unable to trim the timestamp format while loading data via SQL loader.
my control file looks like this:

```<code>LOAD DATA
APPEND
INTO TABLE MyTable
fields terminated by ','
trailing nullcols
(
column1,
column2,
column3,
column4,
DATE EXPRESSION "current_timestamp(1)"
)
</code>```

The date column loaded in MyTable is in below format:
18-FEB-20 18.10.33.700000000

I want to trim the milliseconds from the output(.700000000). My output should be "18-FEB-20 18.10.33". Is there a way to do it via SQL loader itself?

答:
TO_CHAR(current_timestamp(1), 'DD-MON-YY hh:mi:ss') works in a SELECT statement to format current_timestamp(1) like you are requesting. I'm not sure if the same syntax will work in SQL-Loader, but I'd expect something very similar to work for what you need.

```<code>SELECT
    TO_CHAR(current_timestamp(1), 'DD-MON-YY hh:mi:ss')
FROM DUAL
</code>```

Body:
I am new to SQL loader and unable to trim the timestamp format while loading data via SQL loader.
my control file looks like this:

LOAD DATA
APPEND
INTO TABLE MyTable
fields terminated by ','
trailing nullcols
(
column1,
column2,
column3,
column4,
DATE EXPRESSION "current_timestamp(1)"
)

The date column loaded in MyTable is in below format:
18-FEB-20 18.10.33.700000000

I want to trim the milliseconds from the output(.700000000). My output should be "18-FEB-20 18.10.33". Is there a way to do it via SQL loader itself?

Body:
TO_CHAR(current_timestamp(1), 'DD-MON-YY hh:mi:ss') works in a SELECT statement to format current_timestamp(1) like you are requesting. I'm not sure if the same syntax will work in SQL-Loader, but I'd expect something very similar to work for what you need.

SELECT
    TO_CHAR(current_timestamp(1), 'DD-MON-YY hh:mi:ss')
FROM DUAL