问:
Make Gremlin Server use ALL Processor Cores
I am running Neo4j on Gremlin Server and OrientDB on Gremlin Server and a Java Client Application. There are 8 processor cores on my pc hardware where gremlin server resides (java client app resides on another machine) however, i noticed that Gremlin Server is using only 1 processor core to run my query, even though it is a long running query. My question are as follow please:

Is there a way to make Gremlin Server use ALL the 8 processor cores on my pc hardware to run my query instead of just one?

Is there a way to access and change graph database configuration settings which Gremlin Server controls. i.e. access and change neo4j configuration settings under Gremlin Server?

Is there a way to capture the timestamp of when a query begins to run on gremlin server (i.e. after the client serializes and send the data across network to gremlin server, gremlin server deserializes the data and at the point gremlin server is ready to run the query?). I know of TimeUtil Class but it only gives me the duration in milliseconds that it takes gremlin server to run the query on the side side and not the timestamp.

Thank you so much.

答:
Is there a way to make Gremlin Server use ALL the 8 processor cores on my pc hardware to run my query instead of just one?

Well, a Gremlin query's resource usage is largely going to be bound to the underlying execution of the graph system (in your case neo4j or orientdb). If the underlying graph system can parallelize some aspect of the query then I imagine you'd see more processor usage. If you're looking for massively parallel types of queries over large scale graphs then you might want to look into OLAP traversals with Gremlin over Spark.

Is there a way to access and change graph database configuration settings which Gremlin Server controls. i.e. access and change neo4j configuration settings under Gremlin Server?

If you're asking if there is some API to change neo4j configuration settings through Gremlin Server, then, no, that is not possible. However, all neo4j configurations options can be modified by way of the configuration file you provide to Gremlin Server which instantiates neo4j as described here. Basically, neo4j specific configurations just need to be prefixed with gremlin.neo4j.conf.. For example to set the dbms.index_sampling.background_enabled configuration option you would do:

```<code>gremlin.graph=org.apache.tinkerpop.gremlin.neo4j.structure.Neo4jGraph
gremlin.neo4j.directory=/tmp/neo4j
gremlin.neo4j.conf.dbms.index_sampling.background_enabled=true
</code>```

Is there a way to capture the timestamp of when a query begins to run on gremlin server (i.e. after the client serializes and send the data across network to gremlin server, gremlin server deserializes the data and at the point gremlin server is ready to run the query?). I know of TimeUtil Class but it only gives me the duration in milliseconds that it takes gremlin server to run the query on the side side and not the timestamp.

No, that timestamp is not captured, though it might be a nice piece of metadata that Gremlin Server could return in the future potentially. If you were using scripts (rather than bytecode based traversals) I suppose you could grab a timestamp and fold that into your result:

```<code>start = System.currentTimeMillis()
[start, g.V().has('person','name','marko').toList()]
</code>```

I can't say I'd completely endorse this approach as it binds you to embedded strings for your queries but it does at least allow you to get the timestamp.

Body:
Is there a way to make Gremlin Server use ALL the 8 processor cores on my pc hardware to run my query instead of just one?

Well, a Gremlin query's resource usage is largely going to be bound to the underlying execution of the graph system (in your case neo4j or orientdb). If the underlying graph system can parallelize some aspect of the query then I imagine you'd see more processor usage. If you're looking for massively parallel types of queries over large scale graphs then you might want to look into OLAP traversals with Gremlin over Spark.

Is there a way to access and change graph database configuration settings which Gremlin Server controls. i.e. access and change neo4j configuration settings under Gremlin Server?

If you're asking if there is some API to change neo4j configuration settings through Gremlin Server, then, no, that is not possible. However, all neo4j configurations options can be modified by way of the configuration file you provide to Gremlin Server which instantiates neo4j as described here. Basically, neo4j specific configurations just need to be prefixed with gremlin.neo4j.conf.. For example to set the dbms.index_sampling.background_enabled configuration option you would do:

gremlin.graph=org.apache.tinkerpop.gremlin.neo4j.structure.Neo4jGraph
gremlin.neo4j.directory=/tmp/neo4j
gremlin.neo4j.conf.dbms.index_sampling.background_enabled=true

Is there a way to capture the timestamp of when a query begins to run on gremlin server (i.e. after the client serializes and send the data across network to gremlin server, gremlin server deserializes the data and at the point gremlin server is ready to run the query?). I know of TimeUtil Class but it only gives me the duration in milliseconds that it takes gremlin server to run the query on the side side and not the timestamp.

No, that timestamp is not captured, though it might be a nice piece of metadata that Gremlin Server could return in the future potentially. If you were using scripts (rather than bytecode based traversals) I suppose you could grab a timestamp and fold that into your result:

start = System.currentTimeMillis()
[start, g.V().has('person','name','marko').toList()]

I can't say I'd completely endorse this approach as it binds you to embedded strings for your queries but it does at least allow you to get the timestamp.


来源: stackexchange

问:
What is the best way to declare a property?
We declare properties using the @property keyword and synthesize it in the implementation file. My question is,

What if I declare a property using the @property keyword and also declare a variable in the interface block with the same name? For example, consider the following code,

Interface:

```<code>@interface myClass : NSObject {

    NSString *myClass_name;  // LINE 1
}

@property(nonatomic, retain) NSString *myClass_name;  // LINE 2

@end
</code>```

Implementation:

```<code>@implementation myClass

@synthesize myClass_name  // LINE 3

@end
</code>```

Declaring myClass_name in LINE 1 will make any problem? Like any reference problem or any unnecessary memory consumption problem?

答:
The following is the Object-oriented way:

DeclaringProperties.h

```<code>@interface DeclaringProperties : NSObject
// ivars and {} can be omitted

@property (nonatomic, readwrite, retain) NSString *normal;
@property (nonatomic, readwrite, retain) NSString *alias;
@property (nonatomic, readonly, retain) NSString *readonly;

- (id) initWithNormal:(NSString *)aNormal alias:(NSString *)alias;

@end
</code>```

DeclaringProperties.m

```<code>#import "DeclaringProperties.h"

// private interface
@interface DeclaringProperties ()

@property (nonatomic, readwrite, retain) NSString *readonly; // readwrite for self
@property (nonatomic, readwrite, retain) NSString *private;
@property (nonatomic, readwrite, retain) NSString *retain;

@end

#pragma mark -

@implementation DeclaringProperties

@synthesize normal, alias = _alias, readonly, private, retain;

// You can not use "normal" here;
// But you can still use "alias", and it is highlighted in XCode!
- (id) initWithNormal:(NSString *)aNormal alias:(NSString *)alias {
    self = [super init];
    if (self) {
        self.normal = aNormal;
        self.alias = alias;
        self.readonly = @"readonly";
        self.private = @"private";

        // allocated(copied) variable for retained(copied) property should be released or autoreleased
        NSString *alloc = [[NSString alloc] init];
        self.retain = alloc;
        [alloc release];
        // or
        self.retain = [[NSString alloc] init];
        [self.retain release];
        // or
        self.retain = [[[NSString alloc] init] autorelease];
        // I don't like ;)
        retain = [[NSString alloc] init];
    }
    return self;
}

- (void) dealloc {
    self.normal = nil;
    self.alias = nil;
    self.readonly = nil;
    self.private = nil;
    self.retain = nil;
    [super dealloc];
}

@end
</code>```

ContentLicense: CC BY-SA 2.5

Body:
We declare properties using the @property keyword and synthesize it in the implementation file. My question is,

What if I declare a property using the @property keyword and also declare a variable in the interface block with the same name? For example, consider the following code,

Interface:

@interface myClass : NSObject {

    NSString *myClass_name;  // LINE 1
}

@property(nonatomic, retain) NSString *myClass_name;  // LINE 2

@end

Implementation:

@implementation myClass

@synthesize myClass_name  // LINE 3

@end

Declaring myClass_name in LINE 1 will make any problem? Like any reference problem or any unnecessary memory consumption problem?

Body:
The following is the Object-oriented way:

DeclaringProperties.h

@interface DeclaringProperties : NSObject
// ivars and {} can be omitted

@property (nonatomic, readwrite, retain) NSString *normal;
@property (nonatomic, readwrite, retain) NSString *alias;
@property (nonatomic, readonly, retain) NSString *readonly;

- (id) initWithNormal:(NSString *)aNormal alias:(NSString *)alias;

@end

DeclaringProperties.m

#import "DeclaringProperties.h"

// private interface
@interface DeclaringProperties ()

@property (nonatomic, readwrite, retain) NSString *readonly; // readwrite for self
@property (nonatomic, readwrite, retain) NSString *private;
@property (nonatomic, readwrite, retain) NSString *retain;

@end

#pragma mark -

@implementation DeclaringProperties

@synthesize normal, alias = _alias, readonly, private, retain;

// You can not use "normal" here;
// But you can still use "alias", and it is highlighted in XCode!
- (id) initWithNormal:(NSString *)aNormal alias:(NSString *)alias {
    self = [super init];
    if (self) {
        self.normal = aNormal;
        self.alias = alias;
        self.readonly = @"readonly";
        self.private = @"private";

        // allocated(copied) variable for retained(copied) property should be released or autoreleased
        NSString *alloc = [[NSString alloc] init];
        self.retain = alloc;
        [alloc release];
        // or
        self.retain = [[NSString alloc] init];
        [self.retain release];
        // or
        self.retain = [[[NSString alloc] init] autorelease];
        // I don't like ;)
        retain = [[NSString alloc] init];
    }
    return self;
}

- (void) dealloc {
    self.normal = nil;
    self.alias = nil;
    self.readonly = nil;
    self.private = nil;
    self.retain = nil;
    [super dealloc];
}

@end

ContentLicense: CC BY-SA 3.0


问:
AWS Lambda Layer import for Python function
I need to import the pysftp library for my python3.6 lambda function.

I created the folder structure required, pip installed the library into the correct folder and zipped it. As far as I know, this should work, or did i miss smth.
Btw I created the layer.zip in an aws Linux ec2 and uploaded it from there.

But the lambda function just cant import the library. The Error message is:

```<code>{
  "errorMessage": "Unable to import module 'lambda_function'"
}
</code>```

答:
I found the solution.
After setting everything up fresh I noticed I installed the libraries with pip instead of pip3. Just a minor misstype.</p>

ContentLicense: CC BY-SA 4.0

Body:
I need to import the pysftp library for my python3.6 lambda function.

I created the folder structure required, pip installed the library into the correct folder and zipped it. As far as I know, this should work, or did i miss smth.
Btw I created the layer.zip in an aws Linux ec2 and uploaded it from there.

But the lambda function just cant import the library. The Error message is:

{
  "errorMessage": "Unable to import module 'lambda_function'"
}


问:
Adding element to every 15th position in an Array C#
I am creating an Array using List in C#. List data coming from a web service. I am using this array to create a table in PDF(spire.pdf). I want to add a header every 15th element. I can add the first one. From my method header value replaced an element in the array afterwords.

For example if I have 35 element in the list and I want to add the first row as the header row rankListArray[i] = "No;" + "BRN;" + "Exp.Date;" + "Vehicle No;" + "Policy No;" + "Name of Insured;" + "Additional Covers;" + "Sum Insured;" + "NCB;" + "Amount Due"; to the array.

Then in the 15th position again I need to add this row. Then in the 30th position

```<code>    public class PrintedMotorRenewalCompactData
    {
        public string DUE_DATE { get; set; }
        public string CUST_NAME { get; set; }
        public string POLICY_NO { get; set; }
        public string VEHI_NO { get; set; }
        public double NCB_PERC { get; set; }
        public double SUM_INS { get; set; }
        public double PRM_AMT { get; set; }
        public string COVERS { get; set; }
        public int BRANCH { get; set; }
        public string BRANCH_NAME { get; set; }
        public string POL_STAT { get; set; }
    }

IList<PrintedMotorRenewalCompactData> rankList;

            for (int i = 0; i < rankList.Count; i++)
            {

                if ((i % 15) == 0) {

                    rankListArray[i] = "No;" + "BRN;" + "Exp.Date;" + "Vehicle No;" + "Policy No;" + "Name of Insured;" + "Additional Covers;" + "Sum Insured;" + "NCB;" + "Amount Due";

                    rankListArray[i + 1] =
                        (i + 1) + ";" +
                        rankList[i].BRANCH + ";" +
                        rankList[i].DUE_DATE + ";" +
                        rankList[i].VEHI_NO + ";" +
                        rankList[i].POLICY_NO + ";" +
                        rankList[i].CUST_NAME + ";" +
                        rankList[i].COVERS + ";" +
                        rankList[i].SUM_INS.ToString("N", CultureInfo.InvariantCulture) + ";" +
                        rankList[i].NCB_PERC + ";" +
                        rankList[i].PRM_AMT.ToString("N", CultureInfo.InvariantCulture);

                } else {

                    rankListArray[i + 1] =
                        (i + 1) + ";" +
                        rankList[i].BRANCH + ";" +
                        rankList[i].DUE_DATE + ";" +
                        rankList[i].VEHI_NO + ";" +
                        rankList[i].POLICY_NO + ";" +
                        rankList[i].CUST_NAME + ";" +
                        rankList[i].COVERS + ";" +
                        rankList[i].SUM_INS.ToString("N", CultureInfo.InvariantCulture) + ";" +
                        rankList[i].NCB_PERC + ";" +
                        rankList[i].PRM_AMT.ToString("N", CultureInfo.InvariantCulture);

                }

            }
</code>```

答:
Let's simplify you issue. I will assume that you are to produce a List<string> from your List<customObject>.

We start with a List with all letters of the alphabet. We will insert a header every 3 rows.

```<code>var header = "Hi, I'm Header!";
var headerRepeatsEvery = 3.0;  // .0 to avoid int division.
var inputs = Enumerable.Range((int)'A', 26).Select(x => ((char)x).ToString()).ToList();
</code>```

Writing a part of exected result we have :

Header!

  1;A

  2;B

  3;C

  Header!

  4;D

  5;E

The header are in index : {0,4,8,12,16, .. etc}

That look like : X * 4

Let's try to find how many of those header we will need :

```<code>List Size   |   Header Count
0               0
1               1
2               1
3               1
4               2
</code>```

A simple division won't give use the result 4/3 = 1.3333.

We need to round it to the next int, and that's Math.Ceiling

Now the rest is simple for every Header index, we have to insert the header.

```<code>foreach (var index in headerIndexes)
{
    alpha.Insert(index, headerText);
}
</code>```

Now we have our expected result we just need to make it a array : ToArray().

Online Demo

Your final code may look like this :

```<code>var csvLikeLines = rankList.Select((x, i) => $"{i + 1};{x.property1};{x.property2}"));
var indexes = Enumerable.Range(0,(int)Math.Ceiling(csvLikeLines.Count()/ 15))
                        .Select(x => x * 16);

foreach (var index in indexes)
{
    csvLikeLines.Insert(index, headerTest);
}

rankListArray = csvLikeLines.ToArray();
</code>```

I will recommend using something more rebust for concataining property value with ';' semi colon. Soon enought one of the value will have a \n, \r,  or semi colon and everything will go boom.

As you are using it to create a report the strongest argument for using a mapper like CsvHelper is that you will be able to arrange the column order, delete,  or rename one. Without going through the nightmareof remembering that column 7 is 'propertyFoo'. it will keep the header and the column easly maintanable.

Body:
I am creating an Array using List in C#. List data coming from a web service. I am using this array to create a table in PDF(spire.pdf). I want to add a header every 15th element. I can add the first one. From my method header value replaced an element in the array afterwords.

For example if I have 35 element in the list and I want to add the first row as the header row rankListArray[i] = "No;" + "BRN;" + "Exp.Date;" + "Vehicle No;" + "Policy No;" + "Name of Insured;" + "Additional Covers;" + "Sum Insured;" + "NCB;" + "Amount Due"; to the array.

Then in the 15th position again I need to add this row. Then in the 30th position

    public class PrintedMotorRenewalCompactData
    {
        public string DUE_DATE { get; set; }
        public string CUST_NAME { get; set; }
        public string POLICY_NO { get; set; }
        public string VEHI_NO { get; set; }
        public double NCB_PERC { get; set; }
        public double SUM_INS { get; set; }
        public double PRM_AMT { get; set; }
        public string COVERS { get; set; }
        public int BRANCH { get; set; }
        public string BRANCH_NAME { get; set; }
        public string POL_STAT { get; set; }
    }

IList<PrintedMotorRenewalCompactData> rankList;

            for (int i = 0; i < rankList.Count; i++)
            {

                if ((i % 15) == 0) {

                    rankListArray[i] = "No;" + "BRN;" + "Exp.Date;" + "Vehicle No;" + "Policy No;" + "Name of Insured;" + "Additional Covers;" + "Sum Insured;" + "NCB;" + "Amount Due";

                    rankListArray[i + 1] =
                        (i + 1) + ";" +
                        rankList[i].BRANCH + ";" +
                        rankList[i].DUE_DATE + ";" +
                        rankList[i].VEHI_NO + ";" +
                        rankList[i].POLICY_NO + ";" +
                        rankList[i].CUST_NAME + ";" +
                        rankList[i].COVERS + ";" +
                        rankList[i].SUM_INS.ToString("N", CultureInfo.InvariantCulture) + ";" +
                        rankList[i].NCB_PERC + ";" +
                        rankList[i].PRM_AMT.ToString("N", CultureInfo.InvariantCulture);

                } else {

                    rankListArray[i + 1] =
                        (i + 1) + ";" +
                        rankList[i].BRANCH + ";" +
                        rankList[i].DUE_DATE + ";" +
                        rankList[i].VEHI_NO + ";" +
                        rankList[i].POLICY_NO + ";" +
                        rankList[i].CUST_NAME + ";" +
                        rankList[i].COVERS + ";" +
                        rankList[i].SUM_INS.ToString("N", CultureInfo.InvariantCulture) + ";" +
                        rankList[i].NCB_PERC + ";" +
                        rankList[i].PRM_AMT.ToString("N", CultureInfo.InvariantCulture);

                }

            }

Body:
Let's simplify you issue. I will assume that you are to produce a List<string> from your List<customObject>.

We start with a List with all letters of the alphabet. We will insert a header every 3 rows.

var header = "Hi, I'm Header!";
var headerRepeatsEvery = 3.0;  // .0 to avoid int division.
var inputs = Enumerable.Range((int)'A', 26).Select(x => ((char)x).ToString()).ToList();

Writing a part of exected result we have :

Header!

  1;A

  2;B

  3;C

  Header!

  4;D

  5;E

The header are in index : {0,4,8,12,16, .. etc}

That look like : X * 4

Let's try to find how many of those header we will need :

List Size   |   Header Count
0               0
1               1
2               1
3               1
4               2

A simple division won't give use the result 4/3 = 1.3333.

We need to round it to the next int, and that's Math.Ceiling

Now the rest is simple for every Header index, we have to insert the header.

foreach (var index in headerIndexes)
{
    alpha.Insert(index, headerText);
}

Now we have our expected result we just need to make it a array : ToArray().

Online Demo

Your final code may look like this :

var csvLikeLines = rankList.Select((x, i) => $"{i + 1};{x.property1};{x.property2}"));
var indexes = Enumerable.Range(0,(int)Math.Ceiling(csvLikeLines.Count()/ 15))
                        .Select(x => x * 16);

foreach (var index in indexes)
{
    csvLikeLines.Insert(index, headerTest);
}

rankListArray = csvLikeLines.ToArray();

I will recommend using something more rebust for concataining property value with ';' semi colon. Soon enought one of the value will have a \n, \r,  or semi colon and everything will go boom.

As you are using it to create a report the strongest argument for using a mapper like CsvHelper is that you will be able to arrange the column order, delete,  or rename one. Without going through the nightmareof remembering that column 7 is 'propertyFoo'. it will keep the header and the column easly maintanable.


问:
React-router-dom: Clicking on Link adds the route to the Url Link indefinitely
After several attempts, I have managed to implement basic nested-routing with React-router-dom.

Here's the simple project structure:

Here are the relevant files:

App.js

```<code>import React from "react";
import logo from "./logo.svg";
import "./App.css";
import { BrowserRouter, Switch, Route } from "react-router-dom";

import ParentComponent from "./Components/nestedComponents/ParentComponent";
import NavBar from "./Components/Shared/NavBar";
function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <NavBar />
        <Switch>
          <Route path="/home" name="Home" component={ParentComponent} />
        </Switch>
      </BrowserRouter>
    </div>
  );
}

export default App;
</code>```

NavBar.js

```<code>import React from "react";
import { Link } from "react-router-dom";

export default function NavBar() {
  return (
    <div>
      <Link to={`home/nestedComponentOne`}> Nested Component One </Link>
      <Link to={`home/nestedComponentTwo`}> Nested Component Two </Link>
    </div>
  );
}
</code>```

ParentComponent.js

```<code>import React from "react";
import nestedComponentOne from "./nestedComponentOne";
import nestedComponentTwo from "./nestedComponentTwo";
import { Switch, Route } from "react-router-dom";

export default function ParentComponent() {
  return (
    <div>
      <Switch>
        <Route path="/home/nestedComponentOne" component={nestedComponentOne} />
        <Route path="/home/nestedComponentTwo" component={nestedComponentTwo} />
      </Switch>
    </div>
  );
}
</code>```

nestedComponentOne.js

```<code>import React from "react";

export default function nestedComponentOne() {
  return <div>NESTED COMPONENT 1</div>;
}
</code>```

nestedComponentTwo.js

```<code>import React from "react";

export default function nestedComponentTwo() {
  return <div>NESTED COMPONENT 2</div>;
}
</code>```

So here's the Result:

If I click on nestedComponentOne:

If I click on nestedComponentTwo:

The problem is when I click again on nestedComponentOne (or Two) after the I have clicked it the first time, the route gets added to the url string instead of replacing it:

答:
Why don't you try putting all the route in one file. Something like this:</p>

```<code><Route exact path="/home" name="Home" component={ParentComponent} />
<Route path="/home/nestedComponentOne" component={nestedComponentOne} />
<Route path="/home/nestedComponentTwo" component={nestedComponentTwo} />
</code>```

Body:
After several attempts, I have managed to implement basic nested-routing with React-router-dom.

Here's the simple project structure:

Here are the relevant files:

App.js

import React from "react";
import logo from "./logo.svg";
import "./App.css";
import { BrowserRouter, Switch, Route } from "react-router-dom";

import ParentComponent from "./Components/nestedComponents/ParentComponent";
import NavBar from "./Components/Shared/NavBar";
function App() {
  return (

      <BrowserRouter>
        <NavBar />
        <Switch>
          <Route path="/home" name="Home" component={ParentComponent} />
        </Switch>
      </BrowserRouter>

  );
}

export default App;

NavBar.js

import React from "react";
import { Link } from "react-router-dom";

export default function NavBar() {
  return (

      <Link to={`home/nestedComponentOne`}> Nested Component One </Link>
      <Link to={`home/nestedComponentTwo`}> Nested Component Two </Link>

  );
}

ParentComponent.js

import React from "react";
import nestedComponentOne from "./nestedComponentOne";
import nestedComponentTwo from "./nestedComponentTwo";
import { Switch, Route } from "react-router-dom";

export default function ParentComponent() {
  return (

      <Switch>
        <Route path="/home/nestedComponentOne" component={nestedComponentOne} />
        <Route path="/home/nestedComponentTwo" component={nestedComponentTwo} />
      </Switch>

  );
}

nestedComponentOne.js

import React from "react";

export default function nestedComponentOne() {
  return
NESTED COMPONENT 1
;
}

nestedComponentTwo.js

import React from "react";

export default function nestedComponentTwo() {
  return
NESTED COMPONENT 2
;
}

So here's the Result:

If I click on nestedComponentOne:

If I click on nestedComponentTwo:

The problem is when I click again on nestedComponentOne (or Two) after the I have clicked it the first time, the route gets added to the url string instead of replacing it:

Body:
Why don't you try putting all the route in one file. Something like this:

<Route exact path="/home" name="Home" component={ParentComponent} />
<Route path="/home/nestedComponentOne" component={nestedComponentOne} />
<Route path="/home/nestedComponentTwo" component={nestedComponentTwo} />


问:
Is there a hashing algorithm that is tolerant of minor differences?
I'm doing some web crawling type stuff where I'm looking for certain terms in webpages and finding their location on the page, and then caching it for later use.  I'd like to be able to check the page periodically for any major changes.  Something like md5 can be foiled by simply putting the current date and time on the page.

Are there any hashing algorithms that work for something like this?

答:
http://www.phash.org/ did something like this for images.  The jist: Take an image, blur it, convert it to greyscale, do a discrete cosine transform, and look at just the upper left quadrant of the result (where the important information is).  Then record a 0 for each value less than the average and 1 for each value more than the average.  The result is pretty good for small changes.

Min-Hashing is another possibility.  Find features in your text and record them as a value.  Concatenate all those values to make a hash string.

For both of the above, use a vantage point tree so that you can search for near-hits.


问:
Logging out via a link in Laravel
I have a "Logout" link in my top navigation bar. I'm wondering how I can make it so that while I'm logged in, it'll log me out when I click on it and return me to the homepage.

To be specific, what changes to which files do I make in Laravel? Also, what code do I need to write in the view, which currently contains just HTML, to trigger this?

答:
If you use guard you can logout using this line of code : </p>

```<code>Auth::guard('you-guard')->logout();
</code>```

Title: Logging out via a link in Laravel

Body:
If you use guard you can logout using this line of code :

Auth::guard('you-guard')->logout();


问:
Is it valid to reuse the same React-Redux's useDispatch on multiple components?
I have multiple modals and the conditions for showing and hiding them are stored in a Redux store. To avoid typos I export the actions like this...

```<code>//reduxStuff.js

export const modalNameHide = () => {
  return { type: "MODALNAMEHIDE" };
};

export const modalNameShow = () => {
  return { type: "MODALNAMESHOW" };
};
</code>```

Then when I need the functionality for hiding a modal I do this...

```<code>//HideModalButton.js

import { modalNameHide } from "reduxStuff";
import { useDispatch } from "react-redux";

const HideModalNameButton = () => {
    const dispatch = useDispatch();

    return <button onClick = {() => { dispatch(modalNameHide()) }>Close Modal<button>
}
</code>```

As you can see for every component that needs to update the store, 2 imports must be done, one for useDispatch and one for the needed action (modalNameHide in this example).

So my question boils down to this: Can I import useDispatch in reduxStuff.js and export useDispatch and modalNameHide together?

Something like this...

```<code>//reduxStuff.js

import { useDispatch } from "react-redux";

export const modalNameHide = () => {
  let dispatch = useDispatch();
  dispatch({ type: "MODALNAMEHIDE" });
};

export const modalNameShow = () => {
  let dispatch = useDispatch();
  dispatch({ type: "MODALNAMESHOW" });
};
</code>```

Now when I need to close a modal I would just do one import like this...

```<code>//HideModalButton.js

import { modalNameHide } from "reduxStuff";

const HideModalNameButton = () => {
    return <button onClick = {() => { modalNameHide() }>Close Modal<button>
}
</code>```

答:
As grumd said, I was breaking the rules of hooks by doing what I did. However I just figured out what the solution is. All I had to do was make a custom hook.

```<code>//reduxStuff.js

import { useDispatch } from "react-redux";

export const useModalNameHide = () => {
  const dispatch = useDispatch();
  return () => {
    dispatch({ type: "MODALNAMEHIDE" });
  };
};

export const useModalNameShow = () => {
  const dispatch = useDispatch();
  return () => {
    dispatch({ type: "MODALNAMEHIDE" });
  };
};
</code>```

.

```<code>//HideModalButton.js

import { useModalNameHide } from "reduxStuff";

const HideModalNameButton = () => {
    const modalNameHide = useModalNameHide()
    return <button onClick = {() => { modalNameHide() }>Close Modal<button>
}
</code>```

Body:
I have multiple modals and the conditions for showing and hiding them are stored in a Redux store. To avoid typos I export the actions like this...

//reduxStuff.js

export const modalNameHide = () => {
  return { type: "MODALNAMEHIDE" };
};

export const modalNameShow = () => {
  return { type: "MODALNAMESHOW" };
};

Then when I need the functionality for hiding a modal I do this...

//HideModalButton.js

import { modalNameHide } from "reduxStuff";
import { useDispatch } from "react-redux";

const HideModalNameButton = () => {
    const dispatch = useDispatch();

    return <button onClick = {() => { dispatch(modalNameHide()) }>Close Modal<button>
}

As you can see for every component that needs to update the store, 2 imports must be done, one for useDispatch and one for the needed action (modalNameHide in this example).

So my question boils down to this: Can I import useDispatch in reduxStuff.js and export useDispatch and modalNameHide together?

Something like this...

//reduxStuff.js

import { useDispatch } from "react-redux";

export const modalNameHide = () => {
  let dispatch = useDispatch();
  dispatch({ type: "MODALNAMEHIDE" });
};

export const modalNameShow = () => {
  let dispatch = useDispatch();
  dispatch({ type: "MODALNAMESHOW" });
};

Now when I need to close a modal I would just do one import like this...

//HideModalButton.js

import { modalNameHide } from "reduxStuff";

const HideModalNameButton = () => {
    return <button onClick = {() => { modalNameHide() }>Close Modal<button>
}

Body:
As grumd said, I was breaking the rules of hooks by doing what I did. However I just figured out what the solution is. All I had to do was make a custom hook.

//reduxStuff.js

import { useDispatch } from "react-redux";

export const useModalNameHide = () => {
  const dispatch = useDispatch();
  return () => {
    dispatch({ type: "MODALNAMEHIDE" });
  };
};

export const useModalNameShow = () => {
  const dispatch = useDispatch();
  return () => {
    dispatch({ type: "MODALNAMEHIDE" });
  };
};

.

//HideModalButton.js

import { useModalNameHide } from "reduxStuff";

const HideModalNameButton = () => {
    const modalNameHide = useModalNameHide()
    return <button onClick = {() => { modalNameHide() }>Close Modal<button>
}


问:
Django: Integrity error UNIQUE constraint failed: user_profile.user_id
When I am trying to edit a profile to add info to a UserProfile model, I am getting this strange error:

```<code>IntegrityError at /profiles/edit/
UNIQUE constraint failed: user_profile.user_id
</code>```

What is wrong here,

model:

```<code>class UserProfile(models.Model):

    user = models.OneToOneField(User)
    bio = models.TextField(blank=True)
    phone= models.CharField(max_length=10, blank=True)
    address = models.CharField(max_length=1024)
    age = models.PositiveIntegerField(blank=True,null=True)
    gender = models.IntegerField(choices=GENDER_CHOICES, default=1)
</code>```

form:

```<code>class UserProfileForm(forms.ModelForm):

    class Meta:
        model = UserProfile
        fields = ('phone','age','gender','address','bio')
</code>```

view:

```<code>def edit_profile(request):

    if request.method == 'POST':
        form = UserProfileForm(request.POST)
        print request.POST
        if form.is_valid():

            new_profile = UserProfile(
                            user = request.user,
                            bio = request.POST['bio'],
                            address = request.POST['address'],
                            age = request.POST['age']
                            )

            new_profile.save()

            return HttpResponseRedirect(reverse('user_public_profile', args=(request.user.username,)))
        return render(request,'users/edit_profile.html', {'form': form})

    else:
        form = UserProfileForm()
        return render(request,'users/edit_profile.html',
                          {'form': form})
</code>```

答:
I was getting the same error multiple times and I was really disheartened but finally came over the solution.

Convert:

user = models.OneToOneField(User)
```
<p>to</p>
<pre class="lang-py prettyprint-override"><code>user = models.ForeignKey(User)
</code>```

This should solve the issue.

Body:
When I am trying to edit a profile to add info to a UserProfile model, I am getting this strange error:

IntegrityError at /profiles/edit/
UNIQUE constraint failed: user_profile.user_id

What is wrong here,

model:

class UserProfile(models.Model):

    user = models.OneToOneField(User)
    bio = models.TextField(blank=True)
    phone= models.CharField(max_length=10, blank=True)
    address = models.CharField(max_length=1024)
    age = models.PositiveIntegerField(blank=True,null=True)
    gender = models.IntegerField(choices=GENDER_CHOICES, default=1)

form:

class UserProfileForm(forms.ModelForm):

    class Meta:
        model = UserProfile
        fields = ('phone','age','gender','address','bio')

view:

def edit_profile(request):

    if request.method == 'POST':
        form = UserProfileForm(request.POST)
        print request.POST
        if form.is_valid():

            new_profile = UserProfile(
                            user = request.user,
                            bio = request.POST['bio'],
                            address = request.POST['address'],
                            age = request.POST['age']
                            )

            new_profile.save()

            return HttpResponseRedirect(reverse('user_public_profile', args=(request.user.username,)))
        return render(request,'users/edit_profile.html', {'form': form})

    else:
        form = UserProfileForm()
        return render(request,'users/edit_profile.html',
                          {'form': form})

Body:
I was getting the same error multiple times and I was really disheartened but finally came over the solution.

Convert:

user = models.OneToOneField(User)

to

user = models.ForeignKey(User)

This should solve the issue.


问:
how can something be bigger than (unsigned long long) > LONG_MAX?
I found this code in an algorithm I need to update:

```<code> if (value > (unsigned long long) LONG_MAX)
</code>```

EDIT: value is the result of a division of two uint64_t numbers.

I understand that (unsigned long long) LONG_MAX is a VERY big number:

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

   int main() {
     unsigned long long ull = (unsigned long long) LONG_MAX;
     printf("%lu",ull);
     return 0;
   }
</code>```

prints 9223372036854775807

So what I am comparing here? In what case this if statement will evaluate to true?

答:
A float or double can be larger than that.  Appendix Ep5 of the C standard states that either type must be able to hold a value at least as large as 1E37 which is a larger value than LONG_MAX which must be at least 2147483647:

The values given in the following list shall be replaced by
  implementation-defined constant expressions with values that are
  greater than or equal to those shown:

```<code>#define DBL_MAX 1E+37
#define FLT_MAX 1E+37
#define LDBL_MAX 1E+37
</code>```

So if value is either of those types, it could evaluate to true.

EDIT:

Since value is a uint64_t, whose max value is 18446744073709551615, this can also be larger than LONG_MAX.

Body:
I found this code in an algorithm I need to update:

 if (value > (unsigned long long) LONG_MAX)

EDIT: value is the result of a division of two uint64_t numbers.

I understand that (unsigned long long) LONG_MAX is a VERY big number:

   #include "stdio.h"
   #include "limits.h"

   int main() {
     unsigned long long ull = (unsigned long long) LONG_MAX;
     printf("%lu",ull);
     return 0;
   }

prints 9223372036854775807

So what I am comparing here? In what case this if statement will evaluate to true?

Body:
A float or double can be larger than that.  Appendix Ep5 of the C standard states that either type must be able to hold a value at least as large as 1E37 which is a larger value than LONG_MAX which must be at least 2147483647:

The values given in the following list shall be replaced by
  implementation-defined constant expressions with values that are
  greater than or equal to those shown:

#define DBL_MAX 1E+37
#define FLT_MAX 1E+37
#define LDBL_MAX 1E+37

So if value is either of those types, it could evaluate to true.

EDIT:

Since value is a uint64_t, whose max value is 18446744073709551615, this can also be larger than LONG_MAX.


问:
Leetcode : Submitted Function producing Unexpected output
When I am submitting the following solution

```<code>class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
    li = []
    i = 0
    for ch in t:
        if ch == s[i]:
            i+=1
            #debug
            li.append(ch)
    if s == ''.join(li):
        return "true"
    else:
        return "false"
</code>```

in leetcode, solution is failing because it it shows ouput being true as can be seen here. But output for this testcase on my mahcine is false which is correct and expected ouput. I have tried finding solution for this on various forums and already tried all the recommened solution provided by this post by leetcode but it is also not working.

The test case for which solution is failing:

"axc"
"ahbgdc"

Question can be found here on leetcode

答:
False != 'false', and every non-empty string (including 'false') evaluates to True.

Just return True and False (bool values, like type hints suggest), not strings.

```<code>def isSubsequence(self, s: str, t: str) -> bool:
    li = []
    i = 0
    for ch in t:
        if ch == s[i]:
            i+=1
            #debug
            li.append(ch)
    if s == ''.join(li):
        return True
    else:
        return False
</code>```

Body:
When I am submitting the following solution

class Solution:
def isSubsequence(self, s: str, t: str) -> bool:
    li = []
    i = 0
    for ch in t:
        if ch == s[i]:
            i+=1
            #debug
            li.append(ch)
    if s == ''.join(li):
        return "true"
    else:
        return "false"

in leetcode, solution is failing because it it shows ouput being true as can be seen here. But output for this testcase on my mahcine is false which is correct and expected ouput. I have tried finding solution for this on various forums and already tried all the recommened solution provided by this post by leetcode but it is also not working.

The test case for which solution is failing:

"axc"
"ahbgdc"

Question can be found here on leetcode

Body:
False != 'false', and every non-empty string (including 'false') evaluates to True.

Just return True and False (bool values, like type hints suggest), not strings.

def isSubsequence(self, s: str, t: str) -> bool:
    li = []
    i = 0
    for ch in t:
        if ch == s[i]:
            i+=1
            #debug
            li.append(ch)
    if s == ''.join(li):
        return True
    else:
        return False


问:
what is the best practice using async method in lock
In .Net Core,many I/O methods have async version,and Microsoft suggests us to use them for better performance.

But as we know,async methods can't work right in normal lock,because normal lock is relative to thread.

For example，Using ReadWriteLocker in MemoryCache.when MemoryCache is missing，I need read data from database.
I have known 2 ways to solve this problem now:

convert async database query method to sync,such as "Wait" or ".Result".

using special lock, such as redis lock or some unofficial AsyncReaderWriteLocker.(I have found one,but I haven't read its code yet,so I don't know the detail,the cost or new bug about it)

So back to title,when I have to use async method in lock,what is the best way?I need some suggestions.
Thanks a lot for reading my poor English.

答:
lock is just syntactic sugar for a semaphore.  You can do what you need with SemaphoreSlim, like this.  First declare a semaphore in a field or a property that is accessible from wherever you need the thread protection:

```<code>public readonly SemaphoreSlim _mySemaphoreSlim = new SemaphoreSlim(1, 1);
</code>```

Then use it like this:

```<code>await _mySemaphoreSlim.WaitAsync(cancellationToken);
// Do whatever other sync or async operations you need.
_initializationSemaphoreSlim.Release();
</code>```

Body:
lock is just syntactic sugar for a semaphore.  You can do what you need with SemaphoreSlim, like this.  First declare a semaphore in a field or a property that is accessible from wherever you need the thread protection:

public readonly SemaphoreSlim _mySemaphoreSlim = new SemaphoreSlim(1, 1);

Then use it like this:

await _mySemaphoreSlim.WaitAsync(cancellationToken);
// Do whatever other sync or async operations you need.
_initializationSemaphoreSlim.Release();


问:
Assembly code inlining in java and how to distinguish 32bit and 64bit os in java
I need to write some assembly injection in java code for tasks at my university.
I have a class with native function

```<code>import java.io.File;

public class AsmOR {
    static {
        String path = System.getProperty("user.dir");

        System.load(path+File.separator+"mydll.dll");
    }

    public static native int or(int num1, int num2);
}
</code>```

Then I compiled the class using command javac -h AsmOR.java and I got header.

```<code>/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class org_user_AsmFun_AsmOR */

#ifndef _Included_org_user_AsmFun_AsmOR
#define _Included_org_user_AsmFun_AsmOR
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     org_user_AsmFun_AsmOR
 * Method:    or
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_org_user_AsmFun_AsmOR_or
  (JNIEnv *, jclass, jint, jint);

#ifdef __cplusplus
}
#endif
#endif
</code>```

I used assembly this assembly code, but I don't understand why are r8 and r9 parameters of the function. I tried to read javadoc, but it's useless.

```<code>global Java_org_user_AsmFun_AsmOR_or

Java_org_user_AsmFun_AsmOR_or:
    mov rax,r8
    or rax,r9
    ret 32
end
</code>```

Also, I wanted to use the coprocessor for double sum, but it doesn't work.

```<code>    fld dword [r8]
    fld dword [r9]
    fadd st0,st1
    fistp dword [rax]
    ret 32
</code>```

How to do this and how to distinguish between 32bit and 64bit version of the systems and load the dll library depending on the version?

答:
Judging by the "mydll.dll" in your code, you are on Windows.
That means the Microsoft x64 calling convention applies:

The first four arguments are placed onto the registers. That means RCX, RDX, R8, R9 for integer, struct or pointer arguments (in that order), and XMM0, XMM1, XMM2, XMM3 for floating point arguments. Additional arguments are pushed onto the stack (right to left). Integer return values (similar to x86) are returned in RAX if 64 bits or less. Floating point return values are returned in XMM0. Parameters less than 64 bits long are not zero extended; the high bits are not zeroed.

So RCX and RDX are the JNIEnv pointer and a pointer to your jclass, respectively.

As for your second question: fld dword [r8] will treat the contents of r8 as a float* and dereference that to get the actual float value. I think you have to use fild dword r8 if you want to load directly from a register.

The third question is already answered here.

Body:
I need to write some assembly injection in java code for tasks at my university.
I have a class with native function

import java.io.File;

public class AsmOR {
    static {
        String path = System.getProperty("user.dir");

        System.load(path+File.separator+"mydll.dll");
    }

    public static native int or(int num1, int num2);
}

Then I compiled the class using command javac -h AsmOR.java and I got header.

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class org_user_AsmFun_AsmOR */

#ifndef _Included_org_user_AsmFun_AsmOR
#define _Included_org_user_AsmFun_AsmOR
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     org_user_AsmFun_AsmOR
 * Method:    or
 * Signature: (II)I
 */
JNIEXPORT jint JNICALL Java_org_user_AsmFun_AsmOR_or
  (JNIEnv *, jclass, jint, jint);

#ifdef __cplusplus
}
#endif
#endif

I used assembly this assembly code, but I don't understand why are r8 and r9 parameters of the function. I tried to read javadoc, but it's useless.

global Java_org_user_AsmFun_AsmOR_or

Java_org_user_AsmFun_AsmOR_or:
    mov rax,r8
    or rax,r9
    ret 32
end

Also, I wanted to use the coprocessor for double sum, but it doesn't work.

    fld dword [r8]
    fld dword [r9]
    fadd st0,st1
    fistp dword [rax]
    ret 32

How to do this and how to distinguish between 32bit and 64bit version of the systems and load the dll library depending on the version?


问:
Gitlab webhook system
I have one question:

My application uses port 1337 (I used in sails.js framework) and I must write a webhook system from gitlab. I didn't find many tutorials on "how to write webhook system", but I have the following code:

```<code>const secret = "your_secret_here";
const repo = "~/your_repo_path_here/";

const http = require('http');
const crypto = require('crypto');
const exec = require('child_process').exec;

http.createServer(function (req, res) {
    req.on('data', function(chunk) {
        let sig = "sha1=" + crypto.createHmac('sha1', secret).update(chunk.toString()).digest('hex');

    if (req.headers['x-hub-signature'] == sig) {
        exec('cd ' + repo + ' && git pull');
    }
});

    res.end();
}).listen(8080);
</code>```

This code use port 8080,
And my question: how to use this code but not on port 8080 but on my application port 1337?, How to edit this code to be the correct version for sails?

Thanks for all answers

答:
You are creating a new service using Node's http library. It won't work on port 1337, as that port is taken by sails.

You need to make a custom route in sails, more info on how to do that here, here and here. And that needs to be connected to an action which will contain the actual code which handles the webhook.

Title: Gitlab webhook system

Body:
I have one question:

My application uses port 1337 (I used in sails.js framework) and I must write a webhook system from gitlab. I didn't find many tutorials on "how to write webhook system", but I have the following code:

const secret = "your_secret_here";
const repo = "~/your_repo_path_here/";

const http = require('http');
const crypto = require('crypto');
const exec = require('child_process').exec;

http.createServer(function (req, res) {
    req.on('data', function(chunk) {
        let sig = "sha1=" + crypto.createHmac('sha1', secret).update(chunk.toString()).digest('hex');

    if (req.headers['x-hub-signature'] == sig) {
        exec('cd ' + repo + ' && git pull');
    }
});

    res.end();
}).listen(8080);

This code use port 8080,
And my question: how to use this code but not on port 8080 but on my application port 1337?, How to edit this code to be the correct version for sails?

Thanks for all answers


问:
ASP.NET MVC3 URL and hiding Id's
I have a heap of entities that are keyed by ID. In one screen I load a "Subject" based on the ID like so: "/Results/Subject/53" On that same screen I have a combo box that maintains a list of all subjects. The user can change the selection in this combo to another subject and I load the results for that subject using ajax. When I do this the URL in the browser is stale as I might be now be looking at /Results/Subject/45 If a user reloads I reload the original document and not the new one.

I would either like to update the URL (which sounds hacky as) or I would like to base my navigation on something else besides the Id as part of the URL. How can I do this? How can I load controllers for specific items without specifying the Id as part of the URL.

答:
Easiest way would be to ditch the ajax when that drop-down changes, and just navigate to a new url (/Results/Subject/NewID).

If you want to keep the ajax, you could just put the key at the end of the url with a # like "/Results/Subject#53", then load it via Ajax (the #53 will not be passed over to the server). That way, when the user changes the drop-down, you can navigate to "/Results/Subject#NewID" without it reloading the page.

Title: ASP.NET MVC3 URL and hiding Id's


问:
Creating/appending Numpy Array
I have two numpy arrays that are shaped (8760,1) that I want to combine into a single array that is (8760,2) and then from that, filter out any values of zero that might be in first index column, or gauge in the "data" so that I can do statistical manipulation with the temp array.  I have tried np.stack and then attempted to filter out any zero values that way, but ended up with my temp array being 3D rather than still 2D.

```<code>data=np.stack((mb, gauge), axis=-1)
dta = data[:,data!=0]
idx = np.where(data[:,1]>0)
temp = data[idx,:]
</code>```

I know I could filter out the zeros from gauge first, but I want to preserve the index values that go along with the mb array

答:
np.stack joins along a newly created axis. Thus your arrays become 3D.

To join along an existing axis, you could use np.concatenate:

```<code>a1 = np.empty((100, 1))
a2 = np.empty((100, 1))
a3 = np.concatenate((a1, a2), axis=1) # will give a (100, 2) array

</code>```

Title: Creating/appending Numpy Array

Body:
I have two numpy arrays that are shaped (8760,1) that I want to combine into a single array that is (8760,2) and then from that, filter out any values of zero that might be in first index column, or gauge in the "data" so that I can do statistical manipulation with the temp array.  I have tried np.stack and then attempted to filter out any zero values that way, but ended up with my temp array being 3D rather than still 2D.

data=np.stack((mb, gauge), axis=-1)
dta = data[:,data!=0]
idx = np.where(data[:,1]>0)
temp = data[idx,:]

I know I could filter out the zeros from gauge first, but I want to preserve the index values that go along with the mb array

Body:
np.stack joins along a newly created axis. Thus your arrays become 3D.

To join along an existing axis, you could use np.concatenate:

a1 = np.empty((100, 1))
a2 = np.empty((100, 1))
a3 = np.concatenate((a1, a2), axis=1) # will give a (100, 2) array


问:
Flutter : Change accent color on runtime
How to change accent color on runtime in flutter?

```<code>Color scolor = Colors.green;
...
...
new MaterialApp(

      theme: new ThemeData(
        brightness: Brightness.light,
        accentColor:  scolor,
        ),
 home: new SetAccentColor());

class SetAccentColor extends StatefulWidget {
  @override
  _SetAccentColor createState() => _SetAccentColor();
}

class _SetAccentColor extends State<SetAccentColor > {
...
...
@override
  Widget build(BuildContext context) {
 return Scaffold(
        body: Builder(
            builder: (context) => Container(
                  child: FutureBuilder<List<ColorDBModel>>(
                          future: ColorDBProvider.db.getAllColorModels(),
                          builder: (BuildContext context, AsyncSnapshot<List<ColorDBModel>> snapshot) {

 if (snapshot.data[0].ColorName == "red")
scolor = Colors.red;
else
scolor = Colors.blue;
...
...
...
}
}
}
</code>```

These are the important parts of the code. But accentColor isnt changing according to the changes in scolor.

答:
Use the setState to rebuild the widget with the new color. This will work with a StatefulWidget.

```<code>onPressed: () {
  setState(() {
    scolor = Colors.red;
  });
}
</code>```

Body:
How to change accent color on runtime in flutter?

Color scolor = Colors.green;
...
...
new MaterialApp(

      theme: new ThemeData(
        brightness: Brightness.light,
        accentColor:  scolor,
        ),
 home: new SetAccentColor());

class SetAccentColor extends StatefulWidget {
  @override
  _SetAccentColor createState() => _SetAccentColor();
}

class _SetAccentColor extends State<SetAccentColor > {
...
...
@override
  Widget build(BuildContext context) {
 return Scaffold(
        body: Builder(
            builder: (context) => Container(
                  child: FutureBuilder<List<ColorDBModel>>(
                          future: ColorDBProvider.db.getAllColorModels(),
                          builder: (BuildContext context, AsyncSnapshot<List<ColorDBModel>> snapshot) {

 if (snapshot.data[0].ColorName == "red")
scolor = Colors.red;
else
scolor = Colors.blue;
...
...
...
}
}
}

These are the important parts of the code. But accentColor isnt changing according to the changes in scolor.

Body:
Use the setState to rebuild the widget with the new color. This will work with a StatefulWidget.

onPressed: () {
  setState(() {
    scolor = Colors.red;
  });
}


问:
How to perform a def function using dash html core component button
I have a simple code like the below:

```<code>import pyodbc
import pandas as pd
import os
import sqlalchemy as db
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Date, Float
import datetime as dt
import numpy as np
import dash
import dash_html_components as html
import dash_core_components as dcc

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

def my_DB_func():

    .............

    """Connection to sql-server Part"""
    # connect db
    engine = create_engine('mssql+pyodbc://bbbbb-aaaaa\zzzzzzzxxx/toolDB?driver=SQL+Server+Native+Client+11.0')
    connection = engine.connect()

    ................

    # Close the connection
    connection.close()
app.layout = html.Div([
    html.Button('Submit', id='button'),
])

if __name__ == '__main__':
    app.run_server(debug=True)
</code>```

So all I need When Click this button kust do the my_DB_func()

About this function it's just a code contains about more than 800 lines that's create a database and export some excel files using to_csv and to_sql functions

So how to perform the @Callback function to do a def funtion

答:
I tried to use thise simple @Call-Back and it works:</p>

```<code>@app.callback(
    Output(component_id='body-div', component_property='children'),
    [Input(component_id='button', component_property='n_clicks')]
)

def update_output(n_clicks):
    if n_clicks is None:
        raise PreventUpdate
    else:
        return my_DB_func()
</code>```

Body:
I have a simple code like the below:

import pyodbc
import pandas as pd
import os
import sqlalchemy as db
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Date, Float
import datetime as dt
import numpy as np
import dash
import dash_html_components as html
import dash_core_components as dcc

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

def my_DB_func():

    .............

    """Connection to sql-server Part"""
    # connect db
    engine = create_engine('mssql+pyodbc://bbbbb-aaaaa\zzzzzzzxxx/toolDB?driver=SQL+Server+Native+Client+11.0')
    connection = engine.connect()

    ................

    # Close the connection
    connection.close()
app.layout = html.Div([
    html.Button('Submit', id='button'),
])

if __name__ == '__main__':
    app.run_server(debug=True)

So all I need When Click this button kust do the my_DB_func()

About this function it's just a code contains about more than 800 lines that's create a database and export some excel files using to_csv and to_sql functions

So how to perform the @Callback function to do a def funtion

Body:
I tried to use thise simple @Call-Back and it works:

@app.callback(
    Output(component_id='body-div', component_property='children'),
    [Input(component_id='button', component_property='n_clicks')]
)

def update_output(n_clicks):
    if n_clicks is None:
        raise PreventUpdate
    else:
        return my_DB_func()


问:
Excel VBA PasteSpecial xlPasteValues Syntax error
I'm trying to copy data from one .xlsx file to my .xlsm file, but without the formatting. When I try to use the following code line an unspecified Syntax error appears.

TargetSheet.Range("A" & TargetLastRow).PasteSpecial xlPasteValues (or various other forms)

```<code>Sub Import_Click()

'Set the target workbook for import.'
Dim TargetWorkbook As Workbook
Set TargetWorkbook = Application.ActiveWorkbook

'Prompt window for user to select and import file.'
Dim UserFilename As String
UserFilename = Application.GetOpenFilename

Dim UserWorkbook As Workbook
Set UserWorkbook = Application.Workbooks.Open(UserFilename)

'Copy data from source to target sheet.'
Dim SourceSheet As Worksheet
Set SourceSheet = UserWorkbook.Worksheets(1)

Dim TargetSheet As Worksheet
Set TargetSheet = TargetWorkbook.Worksheets(1)

Dim SourceLastRow As Long
SourceLastRow = SourceSheet.Cells(SourceSheet.Rows.Count, "A").End(xlUp).Row

Dim TargetLastRow As Long
TargetLastRow = TargetSheet.Cells(TargetSheet.Rows.Count, "A").End(xlUp).Offset(1).Row

SourceSheet.Range("A2:S" & SourceLastRow).Copy _
TargetSheet.Range("A" & TargetLastRow)

'Close import workbook.'
UserWorkbook.Close

End Sub
</code>```

答:
Either you copy in onle line by giving the destination as first parameter of .Copy

```<code>SourceSheet.Range("A2:S" & SourceLastRow).Copy Destination:=TargetSheet.Range("A" & TargetLastRow)
</code>```

Or if you want to use SpecialPaste you need to do it in 2 seperate statements:

```<code>SourceSheet.Range("A2:S" & SourceLastRow).Copy 'no destination given here
'separate statement for pasting:
TargetSheet.Range("A" & TargetLastRow).PasteSpecial xlPasteValues
</code>```

note that there must be no  _ as line concatenater at the end of the .Copy line then!

Body:
I'm trying to copy data from one .xlsx file to my .xlsm file, but without the formatting. When I try to use the following code line an unspecified Syntax error appears.

TargetSheet.Range("A" & TargetLastRow).PasteSpecial xlPasteValues (or various other forms)

Sub Import_Click()

'Set the target workbook for import.'
Dim TargetWorkbook As Workbook
Set TargetWorkbook = Application.ActiveWorkbook

'Prompt window for user to select and import file.'
Dim UserFilename As String
UserFilename = Application.GetOpenFilename

Dim UserWorkbook As Workbook
Set UserWorkbook = Application.Workbooks.Open(UserFilename)

'Copy data from source to target sheet.'
Dim SourceSheet As Worksheet
Set SourceSheet = UserWorkbook.Worksheets(1)

Dim TargetSheet As Worksheet
Set TargetSheet = TargetWorkbook.Worksheets(1)

Dim SourceLastRow As Long
SourceLastRow = SourceSheet.Cells(SourceSheet.Rows.Count, "A").End(xlUp).Row

Dim TargetLastRow As Long
TargetLastRow = TargetSheet.Cells(TargetSheet.Rows.Count, "A").End(xlUp).Offset(1).Row

SourceSheet.Range("A2:S" & SourceLastRow).Copy _
TargetSheet.Range("A" & TargetLastRow)

'Close import workbook.'
UserWorkbook.Close

End Sub

Body:
Either you copy in onle line by giving the destination as first parameter of .Copy

SourceSheet.Range("A2:S" & SourceLastRow).Copy Destination:=TargetSheet.Range("A" & TargetLastRow)

Or if you want to use SpecialPaste you need to do it in 2 seperate statements:

SourceSheet.Range("A2:S" & SourceLastRow).Copy 'no destination given here
'separate statement for pasting:
TargetSheet.Range("A" & TargetLastRow).PasteSpecial xlPasteValues

note that there must be no  _ as line concatenater at the end of the .Copy line then!


问:
Powershell query results list
The Powershell script provides results table below. We need to find out if VM is reachable or not, so I would like to check if "Time" column is not empty.

The question:

How to check if "Time(ms)" has value? how to query any column or row in such a cases in general?

```<code>$result = Test-ConnectionAsync "MyVm"

C:\$result

Source        Destination     IPV4Address      IPV6Address                              Bytes    Time(ms)
------        -----------     -----------      -----------                              -----    --------
SourceVM        MyVM          10.20.20.10                                                32       207
SourceVM        MyVM          10.20.20.10                                                32       207
SourceVM        MyVM          10.20.20.10                                                32       207
SourceVM        MyVM          10.20.20.10                                                32       207
</code>```

thank you!

答:
You can use the Where-Object functionality that checks the value of any column of the given row. If you want to find out what column names are supposed to be, use Get-Member to get all the properties or methods of that object.

```<code># Get all the properties of $result[0]
$result[0] | Get-Member

# Among other things, you will ResponseTime as one of the properties you can use.

# Check if Time(ms) has any value. Following will give you only those rows that match the condition

#Original where statement
#$result | Where-Object { $_.ResponseTime -ne $null }

#Updated where statement
$result | Where-Object { $null -ne $_.ResponseTime }
</code>```

Title: Powershell query results list

Body:
The Powershell script provides results table below. We need to find out if VM is reachable or not, so I would like to check if "Time" column is not empty.

The question:

How to check if "Time(ms)" has value? how to query any column or row in such a cases in general?

$result = Test-ConnectionAsync "MyVm"

C:\$result

Source        Destination     IPV4Address      IPV6Address                              Bytes    Time(ms)
------        -----------     -----------      -----------                              -----    --------
SourceVM        MyVM          10.20.20.10                                                32       207
SourceVM        MyVM          10.20.20.10                                                32       207
SourceVM        MyVM          10.20.20.10                                                32       207
SourceVM        MyVM          10.20.20.10                                                32       207

thank you!

Body:
You can use the Where-Object functionality that checks the value of any column of the given row. If you want to find out what column names are supposed to be, use Get-Member to get all the properties or methods of that object.

# Get all the properties of $result[0]
$result[0] | Get-Member

# Among other things, you will ResponseTime as one of the properties you can use.

# Check if Time(ms) has any value. Following will give you only those rows that match the condition

#Original where statement
#$result | Where-Object { $_.ResponseTime -ne $null }

#Updated where statement
$result | Where-Object { $null -ne $_.ResponseTime }


问:
Simulated annealing in optaplanner
Good afternoon.

I need to solve the problem with time windows using the road graph, where the client’s and depot’s working hours are limited in time. I load the initial data on the problem from my file.

How to set correctly in the configuration the Algorithm for simulating annealing and hard rules in drops by capacities and time windows? I need an example of a working configuration.

```<code>    //my loader problem from json file
    Loader loader = new Loader();
    loader.load(AppConfig.CURRENT_DIR + "\\" + "problem_cvrptw.json");
    InputBuffer buf = loader.getBuf();

    //set problem
    TimeWindowedVehicleRoutingSolution problem = new TimeWindowedVehicleRoutingSolution();
    problem.setCustomerList(buf.getCustomers());
    problem.setDepotList(buf.getDepots());
    problem.setVehicleList(buf.getVehicles());
    problem.setLocationList(buf.getLocations());
    problem.setDistanceType(DistanceType.ROAD_DISTANCE);
    problem.setDistanceUnitOfMeasurement(null); //not "sec"

    //build solver
    SolverConfig solverConfig = SolverConfig.createFromXmlResource("vehicleRoutingSolverConfig.xml");
    SolverFactory<TimeWindowedVehicleRoutingSolution> solverFactory = SolverFactory.create(solverConfig);
    Solver<TimeWindowedVehicleRoutingSolution> solver =  solverFactory.buildSolver();

    //solve
    TimeWindowedVehicleRoutingSolution solution = solver.solve(problem);
</code>```

How to create a configuration to solve the problem with the annealing algorithm using SolverConfig solverConfig = new SolverConfig ()?

答:
In XML, just follow this docs section. It will look like this:

```<code><localSearch>
    ...
    <acceptor>
      <simulatedAnnealingStartingTemperature>2hard/100soft</simulatedAnnealingStartingTemperature>
    </acceptor>
</localSearch>
</code>```

If you want to avoid using XML, you can do something like this:

```<code>solverConfig = new SolverConfig(...).withPhases(
       new ConstructionHeuristicPhaseConfig(),
       new LocalSearchPhaseConfig.withLocalSearchType(LATE_ACCEPTANCE));
</code>```

Now, instead of LATE_ACCEPTANCE you could use SIMMULATED_ANNEALING, but that can't work without a startingTemperate, so you 'll have to do something like withAcceptor().with....

Title: Simulated annealing in optaplanner

Body:
Good afternoon.

I need to solve the problem with time windows using the road graph, where the client’s and depot’s working hours are limited in time. I load the initial data on the problem from my file.

How to set correctly in the configuration the Algorithm for simulating annealing and hard rules in drops by capacities and time windows? I need an example of a working configuration.

    //my loader problem from json file
    Loader loader = new Loader();
    loader.load(AppConfig.CURRENT_DIR + "\\" + "problem_cvrptw.json");
    InputBuffer buf = loader.getBuf();

    //set problem
    TimeWindowedVehicleRoutingSolution problem = new TimeWindowedVehicleRoutingSolution();
    problem.setCustomerList(buf.getCustomers());
    problem.setDepotList(buf.getDepots());
    problem.setVehicleList(buf.getVehicles());
    problem.setLocationList(buf.getLocations());
    problem.setDistanceType(DistanceType.ROAD_DISTANCE);
    problem.setDistanceUnitOfMeasurement(null); //not "sec"

    //build solver
    SolverConfig solverConfig = SolverConfig.createFromXmlResource("vehicleRoutingSolverConfig.xml");
    SolverFactory<TimeWindowedVehicleRoutingSolution> solverFactory = SolverFactory.create(solverConfig);
    Solver<TimeWindowedVehicleRoutingSolution> solver =  solverFactory.buildSolver();

    //solve
    TimeWindowedVehicleRoutingSolution solution = solver.solve(problem);

How to create a configuration to solve the problem with the annealing algorithm using SolverConfig solverConfig = new SolverConfig ()?

Body:
In XML, just follow this docs section. It will look like this:

<localSearch>
    ...
    <acceptor>
      <simulatedAnnealingStartingTemperature>2hard/100soft</simulatedAnnealingStartingTemperature>
    </acceptor>
</localSearch>

If you want to avoid using XML, you can do something like this:

solverConfig = new SolverConfig(...).withPhases(
       new ConstructionHeuristicPhaseConfig(),
       new LocalSearchPhaseConfig.withLocalSearchType(LATE_ACCEPTANCE));

Now, instead of LATE_ACCEPTANCE you could use SIMMULATED_ANNEALING, but that can't work without a startingTemperate, so you 'll have to do something like withAcceptor().with....


问:
MIME type error while using ES6 export/import
How to get rid of "forbidden MIME type („text/html”)" error while using ES6 export/import?
My html:

app.js:

```<code>import {about} from "./templates/about"
let contentContainer = document.getElementById('contentContainer');
const routes = {
    "/" : about,
}

window.onpopstate = () =>{
    contentContainer.innerHTML = routes[window.location.pathname];
}
console.log("script")
</code>```

about.js:

```<code>export const about =`
<section class="about-us">
            <div class="about-us-img">
                <div class="img-shader">
                    <h1 class="about-title">ABOUT US</h1>
                    <article class="about-description">
                        <p>Our company specializes in high quality wooden products.</p>
                        <p>We care about natural environment so we plant two trees for each one we cut down to make the product.</p>
                    </article>
                    <button id="shop-link">shop now</button>
                </div>
            </div>
        </section>
`
</code>```

Also i am using Firefox 73, liveserver extension to VSCode and this is client-side application.
I've tried adding text/javascript type to script tag but this didn't help.

答:
You need to provide the URL to the script.

"./templates/about" is pointing to an HTML document.

Probably you need "./templates/about.js".

Note that browsers cannot implement Node.js' module name resolution system which can figure out file extensions automatically. Browsers use URLs which don't have file extensions (through they might have a full stop character followed by a few letters in a format that looks like a file extension).

Body:
How to get rid of "forbidden MIME type („text/html”)" error while using ES6 export/import?
My html:

app.js:

import {about} from "./templates/about"
let contentContainer = document.getElementById('contentContainer');
const routes = {
    "/" : about,
}

window.onpopstate = () =>{
    contentContainer.innerHTML = routes[window.location.pathname];
}
console.log("script")

about.js:

export const about =`

ABOUT US

Our company specializes in high quality wooden products.

We care about natural environment so we plant two trees for each one we cut down to make the product.

                    <button id="shop-link">shop now</button>

`

Also i am using Firefox 73, liveserver extension to VSCode and this is client-side application.
I've tried adding text/javascript type to script tag but this didn't help.


问:
Routing exception after upgrading to TYPO3 v9.5.14
After upgrading to TYPO3 v9.5.14 our detail pages for news crash with the exception

Symfony\Component\Routing\Exception\InvalidParameterException

Parameter "p88bd715a41119d0e8087a5d19cb049" for route "tx_news_pi1_1" must match "[^/]++" ("" given) to generate a corresponding URL.

What's going on?

The site used this configuration:

```<code>  NewsTagPlugin:
    type: Extbase
    limitToPages: [14]
    extension: News
    plugin: Pi1
    routes:
      - routePath: '/{tag-name}'
        _controller: 'News::list'
        _arguments:
          tag-name: 'overwriteDemand/tags'
      - routePath: '/{tag-name}/page/{page}'
        _controller: 'News::list'
        _arguments:
          tag-name: 'overwriteDemand/tags'
          page: '@widget_0/currentPage'
          requirements:
            page: '\d+'
    defaultController: 'News::list'
    defaults:
      page: ''
    aspects:
      page:
        type: IntegerMapper
        start: 1
        end: 5000
      tag-name:
        type: PersistedAliasMapper
        tableName: tx_news_domain_model_tag
        routeFieldName: slug
</code>```

答:
First off, consider https://docs.typo3.org/c/typo3/cms-core/master/en-us/Changelog/9.5.x/Important-86895-RouteAspectsTakePrecedenceOverRequirements.html

The culprit is the default configuration for the page aspect.
It was once introduced to make sure that the URL for the first tag page is always "/tag-name" and only subsequent pages have "/tag-name/page/2" and so on.

This default value now needs to be removed in order to have the requirements applied as desired.

Body:
After upgrading to TYPO3 v9.5.14 our detail pages for news crash with the exception

Symfony\Component\Routing\Exception\InvalidParameterException

Parameter "p88bd715a41119d0e8087a5d19cb049" for route "tx_news_pi1_1" must match "[^/]++" ("" given) to generate a corresponding URL.

What's going on?

The site used this configuration:

  NewsTagPlugin:
    type: Extbase
    limitToPages: [14]
    extension: News
    plugin: Pi1
    routes:
      - routePath: '/{tag-name}'
        _controller: 'News::list'
        _arguments:
          tag-name: 'overwriteDemand/tags'
      - routePath: '/{tag-name}/page/{page}'
        _controller: 'News::list'
        _arguments:
          tag-name: 'overwriteDemand/tags'
          page: '@widget_0/currentPage'
          requirements:
            page: '\d+'
    defaultController: 'News::list'
    defaults:
      page: ''
    aspects:
      page:
        type: IntegerMapper
        start: 1
        end: 5000
      tag-name:
        type: PersistedAliasMapper
        tableName: tx_news_domain_model_tag
        routeFieldName: slug


问:
Align ImageView to top right corner
I have a RelativeLayout with images next to each other. The number of images will be variable.

```<code>    <RelativeLayout
        android:id="@id/multipleImages"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@drawable/border">

        <ImageView
            android:id="@+id/multi_image1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag1"/>
        <ImageView
            android:id="@+id/multi_image2"
            android:layout_toRightOf="@+id/imag1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag2"/>
        <ImageView
            android:id="@+id/multi_image3"
            android:layout_toRightOf="@+id/multi_image2"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag3"/>

        <ImageView
            android:id="@+id/multi_image4"
            android:layout_toRightOf="@+id/multi_image3"
            android:layout_marginTop="2dp"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag4"/>

    </RelativeLayout>
</code>```

I want to add another image (the red rectangle) to the top-right corner slightly above the last image .
I tried layout_alignParentEnd but the layout goes full width.
Setting negative layout_marginTop the image goes up but is disappears outside the RelativeLayout.

答:
Use this xml :</p>

```<code>    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="@dimen/dimension_40">

    <LinearLayout
        android:id="@+id/multipleImages"
        android:layout_width="wrap_content"
        android:gravity="center"
        android:layout_gravity="bottom"
        android:layout_height="wrap_content"
        android:padding="@dimen/dimension_10"
        android:background="@drawable/grey_border"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/multi_image1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/ic_check_icon_blue" />

        <ImageView
            android:id="@+id/multi_image2"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_toRightOf="@+id/multi_image1"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/ic_check_icon_blue" />

        <ImageView
            android:id="@+id/multi_image3"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_toRightOf="@+id/multi_image2"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/ic_check_icon_blue" />

        <ImageView
            android:id="@+id/multi_image4"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_marginTop="2dp"
            android:layout_toRightOf="@+id/multi_image3"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/ic_check_icon_blue" />

    </LinearLayout>

    <ImageView
        android:id="@+id/multi_image5"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_gravity="end|center_vertical"
        android:layout_marginStart="@dimen/dimension_15"
        android:layout_marginBottom="@dimen/dimension_10"
        android:background="@drawable/notification_background"
        />
</FrameLayout>
</code>```

Title: Align ImageView to top right corner

Body:
I have a RelativeLayout with images next to each other. The number of images will be variable.

    <RelativeLayout
        android:id="@id/multipleImages"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="@drawable/border">

        <ImageView
            android:id="@+id/multi_image1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag1"/>
        <ImageView
            android:id="@+id/multi_image2"
            android:layout_toRightOf="@+id/imag1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag2"/>
        <ImageView
            android:id="@+id/multi_image3"
            android:layout_toRightOf="@+id/multi_image2"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag3"/>

        <ImageView
            android:id="@+id/multi_image4"
            android:layout_toRightOf="@+id/multi_image3"
            android:layout_marginTop="2dp"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/imag4"/>

    </RelativeLayout>

I want to add another image (the red rectangle) to the top-right corner slightly above the last image .
I tried layout_alignParentEnd but the layout goes full width.
Setting negative layout_marginTop the image goes up but is disappears outside the RelativeLayout.

Body:
Use this xml :

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="@dimen/dimension_40">

    <LinearLayout
        android:id="@+id/multipleImages"
        android:layout_width="wrap_content"
        android:gravity="center"
        android:layout_gravity="bottom"
        android:layout_height="wrap_content"
        android:padding="@dimen/dimension_10"
        android:background="@drawable/grey_border"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/multi_image1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/ic_check_icon_blue" />

        <ImageView
            android:id="@+id/multi_image2"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_toRightOf="@+id/multi_image1"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/ic_check_icon_blue" />

        <ImageView
            android:id="@+id/multi_image3"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_toRightOf="@+id/multi_image2"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/ic_check_icon_blue" />

        <ImageView
            android:id="@+id/multi_image4"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_marginTop="2dp"
            android:layout_toRightOf="@+id/multi_image3"
            android:scaleType="fitXY"
            app:srcCompat="@drawable/ic_check_icon_blue" />

    </LinearLayout>

    <ImageView
        android:id="@+id/multi_image5"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_gravity="end|center_vertical"
        android:layout_marginStart="@dimen/dimension_15"
        android:layout_marginBottom="@dimen/dimension_10"
        android:background="@drawable/notification_background"
        />
</FrameLayout>


问:
How to create a color box in front of a radiobutton in html?
I want to create a radiobutton with a small color box in front of it.
This is the current code that I have written:

```<code><label class="container"  style="color: #0B9BCD">
   <div class="foo"></div>
   <input type="radio" name="radiobutton" id="highlight1" value="highlight1"/>
   <span class="checkmark"></span>
</label>
</code>```

where the class foo has the following style:

```<code>.foo {
     float: left;
     width: 20px;
     height: 20px;
     margin: 5px;
     border: 1px solid black;
     background: #13b4ff;
  }
</code>```

And the output I am getting is something like this:

How can I move the color box to the right of the radiobutton?

答:
By moving the div with className "foo" below the radio input and giving the container a display: flex property we can achieve the desired solution.
follow this link to know more about the flexbox.
https://yoksel.github.io/flex-cheatsheet/

```<code><label class="container">
  <input type="radio" name="radiobutton" id="highlight1" value="highlight1" />
  <div class="foo"></div>
</label>

.foo {
  width: 20px;
  height: 20px;
  border: 1px solid black;
  background: #13b4ff;
}

.container{
  display: flex;
}

</code>```

Body:
I want to create a radiobutton with a small color box in front of it.
This is the current code that I have written:

   <input type="radio" name="radiobutton" id="highlight1" value="highlight1"/>

where the class foo has the following style:

.foo {
     float: left;
     width: 20px;
     height: 20px;
     margin: 5px;
     border: 1px solid black;
     background: #13b4ff;
  }

And the output I am getting is something like this:

How can I move the color box to the right of the radiobutton?

Body:
By moving the div with className "foo" below the radio input and giving the container a display: flex property we can achieve the desired solution.
follow this link to know more about the flexbox.
https://yoksel.github.io/flex-cheatsheet/

<label class="container">
  <input type="radio" name="radiobutton" id="highlight1" value="highlight1" />
  <div class="foo"></div>
</label>

.foo {
  width: 20px;
  height: 20px;
  border: 1px solid black;
  background: #13b4ff;
}

.container{
  display: flex;
}


问:
How can I find gameobject with tag that are childs of a specific parent?
```<code>public void UpdateOrAddShaderPrefabToDoors()
    {
        GameObject[] doorsLeft = GameObject.FindGameObjectsWithTag(c_doorLeft);
        GameObject[] doorsRight = GameObject.FindGameObjectsWithTag(c_doorRight);

        List<GameObject> allDoors = doorsLeft.Union(doorsRight).ToList();

        HashSet<GameObject> prefabParentsOfDoorsNeedRemove = new HashSet<GameObject>();
        allDoors.ForEach(doorGameObject =>
        {
            List<GameObject> shadersChildren = new List<GameObject>();
            for (int i=0; i<doorGameObject.transform.childCount ;i++)
            {
                if (doorGameObject.transform.GetChild(i).name.StartsWith(c_doorShieldFxLocked))
                {
                    shadersChildren.Add(doorGameObject.transform.GetChild(i).gameObject);
                }
            }
            foreach (GameObject shader in shadersChildren)
            {
                GameObject outermostPrefabInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(shader);
                prefabParentsOfDoorsNeedRemove.Add(outermostPrefabInstanceRoot);
            }
        });

        foreach (GameObject parent in prefabParentsOfDoorsNeedRemove)
        {
            Modify(parent, RemoveFunc);
        }

        HashSet<GameObject> prefabParentsOfDoors = new HashSet<GameObject>();
        allDoors.ForEach(doorGameObject =>
        {
            GameObject outermostPrefabInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(doorGameObject);
            prefabParentsOfDoors.Add(outermostPrefabInstanceRoot);
        });

        foreach (GameObject parent in prefabParentsOfDoors)
        {
            AddShaderToPrefab(parent);
        }
    }
</code>```

When doing :

```<code>GameObject[] doorsLeft = GameObject.FindGameObjectsWithTag(c_doorLeft);
GameObject[] doorsRight = GameObject.FindGameObjectsWithTag(c_doorRight);
</code>```

It will find all "Door_Left" and "Door_Right" but some of them are childs of other gameobjects and I want to find the door left and door right only that are childs of : Wall_Door_Long_01

答:
You could check all child of that object.</p>

```<code>List<GameObject> doorsLeft = new List<GameObject>();
foreach (Transform child in transform){
    if (child.tag == tag){
        doorsLeft.add(child.gameObject);
    }
}
</code>```

Body:
public void UpdateOrAddShaderPrefabToDoors()
    {
        GameObject[] doorsLeft = GameObject.FindGameObjectsWithTag(c_doorLeft);
        GameObject[] doorsRight = GameObject.FindGameObjectsWithTag(c_doorRight);

        List<GameObject> allDoors = doorsLeft.Union(doorsRight).ToList();

        HashSet<GameObject> prefabParentsOfDoorsNeedRemove = new HashSet<GameObject>();
        allDoors.ForEach(doorGameObject =>
        {
            List<GameObject> shadersChildren = new List<GameObject>();
            for (int i=0; i<doorGameObject.transform.childCount ;i++)
            {
                if (doorGameObject.transform.GetChild(i).name.StartsWith(c_doorShieldFxLocked))
                {
                    shadersChildren.Add(doorGameObject.transform.GetChild(i).gameObject);
                }
            }
            foreach (GameObject shader in shadersChildren)
            {
                GameObject outermostPrefabInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(shader);
                prefabParentsOfDoorsNeedRemove.Add(outermostPrefabInstanceRoot);
            }
        });

        foreach (GameObject parent in prefabParentsOfDoorsNeedRemove)
        {
            Modify(parent, RemoveFunc);
        }

        HashSet<GameObject> prefabParentsOfDoors = new HashSet<GameObject>();
        allDoors.ForEach(doorGameObject =>
        {
            GameObject outermostPrefabInstanceRoot = PrefabUtility.GetOutermostPrefabInstanceRoot(doorGameObject);
            prefabParentsOfDoors.Add(outermostPrefabInstanceRoot);
        });

        foreach (GameObject parent in prefabParentsOfDoors)
        {
            AddShaderToPrefab(parent);
        }
    }

When doing :

GameObject[] doorsLeft = GameObject.FindGameObjectsWithTag(c_doorLeft);
GameObject[] doorsRight = GameObject.FindGameObjectsWithTag(c_doorRight);

It will find all "Door_Left" and "Door_Right" but some of them are childs of other gameobjects and I want to find the door left and door right only that are childs of : Wall_Door_Long_01

Body:
You could check all child of that object.

List<GameObject> doorsLeft = new List<GameObject>();
foreach (Transform child in transform){
    if (child.tag == tag){
        doorsLeft.add(child.gameObject);
    }
}


问:
validate two fields with jQuery Validate
I'm using jQuery Validate Plugin:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Simple demo:

```<code>  <input type="text" name="email" class="required email" />
  <input type="text" name="email_confirm" class="required email" />
</code>```

How to check if the value in the two inputs are the same with jQuery or with jQuery Validate Plugin.

I just tried equalto and it works:

```
rules: {
  email: 'required',
  email2: {equalTo: '.email'}
```

答:
By looking at the demo page at  http://jquery.bassistance.de/validate/demo/ you can validate 2 fields that should be equal by using "equalTo":

```<code>    $("#signupForm").validate({
    rules: {
                    ...snip...
        password: {
            required: true,
            minlength: 5
        },
        confirm_password: {
            required: true,
            minlength: 5,
            equalTo: "#password"
        },
                   ...snip...
    },
    messages: {
        ...snip...
        password: {
            required: "Please provide a password",
            minlength: "Your password must be at least 5 characters long"
        },
        confirm_password: {
            required: "Please provide a password",
            minlength: "Your password must be at least 5 characters long",
            equalTo: "Please enter the same password as above"
        },
        ...snip...
    }
});
</code>```

To do it using the class method, you just need to find the syntax.  I couldn't find it for the equalTo attribute, but it is probably something like:

```<code>class="required email equalTo['email']"
</code>```

Body:
I'm using jQuery Validate Plugin:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Simple demo:

  <input type="text" name="email" class="required email" />
  <input type="text" name="email_confirm" class="required email" />

How to check if the value in the two inputs are the same with jQuery or with jQuery Validate Plugin.

I just tried equalto and it works:

rules: {
  email: 'required',
  email2: {equalTo: '.email'}

Body:
By looking at the demo page at  http://jquery.bassistance.de/validate/demo/ you can validate 2 fields that should be equal by using "equalTo":

    $("#signupForm").validate({
    rules: {
                    ...snip...
        password: {
            required: true,
            minlength: 5
        },
        confirm_password: {
            required: true,
            minlength: 5,
            equalTo: "#password"
        },
                   ...snip...
    },
    messages: {
        ...snip...
        password: {
            required: "Please provide a password",
            minlength: "Your password must be at least 5 characters long"
        },
        confirm_password: {
            required: "Please provide a password",
            minlength: "Your password must be at least 5 characters long",
            equalTo: "Please enter the same password as above"
        },
        ...snip...
    }
});

To do it using the class method, you just need to find the syntax.  I couldn't find it for the equalTo attribute, but it is probably something like:

class="required email equalTo['email']"


问:
Android TalkBack: Hint overwrites contentDescription
I have an EditText like below

```<code><EditText
    android:id="@+id/extUsername"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:contentDescription="Username field"
    android:hint="Username" />
</code>```

I want TalkBack to say "Username field" but it says "Username". It ignores contentDescription.

Do not tell me to remove hint or contentDescription. I need to use both.

Any advices will be appreciated.

答:
Unfortunately, android:hint will always override android:contentDescription. You can create TextView which you will use only to set android:labelFor but from my experience TalkBack will then read both hint and labelFor.

The right way to add TextView which is only for labeling EditText for TalkBack :

```<code>    <TextView
         android:layout_width="0dp"
         android:layout_height="0dp"
         android:text="@string/yourDescription"
         android:labelFor="@+id/editText" />

    <EditText android:id="@+id/editText"/>
</code>```

So one of the solutions is that you can check to see if TalkBack is on and change hint programmatically. You can check if TalkBack is on with:

```<code>  if(context.isScreenReaderOn){
    ...
}
</code>```

And you create an inline function in Kotlin like :

```<code>fun Context.isScreenReaderOn():Boolean{
    val am = getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager
    if (am != null && am.isEnabled) {
        val serviceInfoList =
            am.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_SPOKEN)
        if (!serviceInfoList.isEmpty())
            return true
    }
    return false}
</code>```

Body:
I have an EditText like below

<EditText
    android:id="@+id/extUsername"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:contentDescription="Username field"
    android:hint="Username" />

I want TalkBack to say "Username field" but it says "Username". It ignores contentDescription.

Do not tell me to remove hint or contentDescription. I need to use both.

Any advices will be appreciated.

Body:
Unfortunately, android:hint will always override android:contentDescription. You can create TextView which you will use only to set android:labelFor but from my experience TalkBack will then read both hint and labelFor.

The right way to add TextView which is only for labeling EditText for TalkBack :

    <TextView
         android:layout_width="0dp"
         android:layout_height="0dp"
         android:text="@string/yourDescription"
         android:labelFor="@+id/editText" />

    <EditText android:id="@+id/editText"/>

So one of the solutions is that you can check to see if TalkBack is on and change hint programmatically. You can check if TalkBack is on with:

  if(context.isScreenReaderOn){
    ...
}

And you create an inline function in Kotlin like :

fun Context.isScreenReaderOn():Boolean{
    val am = getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager
    if (am != null && am.isEnabled) {
        val serviceInfoList =
            am.getEnabledAccessibilityServiceList(AccessibilityServiceInfo.FEEDBACK_SPOKEN)
        if (!serviceInfoList.isEmpty())
            return true
    }
    return false}


问:
Is it possible to Change Ant designs theme as dynamic
Is there any way available to change Ant design theme during runtime in react 16.7 CRA.
Config-overides.js file looks like this

const { override, fixBabelImports } = require('customize-cra');

 module.exports = override(
   fixBabelImports('import', {
     libraryName: 'antd',
     libraryDirectory: 'es',
     style: 'css',
   }),
addLessLoader({
   javascriptEnabled: true,
   modifyVars: { '@primary-color': '#1DA57A' },
 })
 );```

This code changes the color as static but How can I make it as dynamic

答:
Yes, it is now possible with antd-theme-webpack-plugin. You can see in the source code of the live demo how it works (by calling window.less.modifyVars(vars)).

As stated in the repository, the webpack plugin injects a javascript file that allows you so your application can act like it dynamically modifies less variables. Also note that, as stated in the repo, if your webpack does not generate the HTML you need to manually modify it to include the library and proper script files.

Body:
Is there any way available to change Ant design theme during runtime in react 16.7 CRA.
Config-overides.js file looks like this

const { override, fixBabelImports } = require('customize-cra');

 module.exports = override(
   fixBabelImports('import', {
     libraryName: 'antd',
     libraryDirectory: 'es',
     style: 'css',
   }),
addLessLoader({
   javascriptEnabled: true,
   modifyVars: { '@primary-color': '#1DA57A' },
 })
 );

This code changes the color as static but How can I make it as dynamic