问:
Build a k-ary tree with no repeated values
Suppose I have two values: x1 and x2.

Given a single root, how to build all the combinations of x1 and x2 using an k-ary tree?

Example:

```<code>#0    root
      /   \
#1  x1     x2
     |
#2  x2
</code>```

At level #1 I have the initial elements, x1 and x2.

At level #2 I  have x2, making the combination x1x2, but don't have x1 because it would be a repeated combination (x2x1, we don't care about the elements order here).

If I had more than two elements, the tree would keep going on, until the level is equal to the number of elements minus 1.

I have already built the initial #1 level. but how do I keep generating the tree without repeating combinations? In other words, how to verify if I should or not put a given element on the tree, in the most performatic way. There is some well-known algorithm for this?

Additional info: PHP

答:
Edit: some modifications on building the tree

My idea is having a n-ary tree for n elements (x1, x2,... ,xn). let root be x0, then for any node xi (0 <= i <= n), you should have all children xj where (i < j <= n). In this way you can have all non-repeating combinations. E.g. for n=3 the 3-ary tree would be something like this:

```<code>root ---> x1 ---> x2 ---> x3
          |  ---> x3
root ---> x2 ---> x3
root ---> x3
</code>```

Body:
Suppose I have two values: x1 and x2.

Given a single root, how to build all the combinations of x1 and x2 using an k-ary tree?

Example:

#0    root
      /   \
#1  x1     x2
     |
#2  x2

At level #1 I have the initial elements, x1 and x2.

At level #2 I  have x2, making the combination x1x2, but don't have x1 because it would be a repeated combination (x2x1, we don't care about the elements order here).

If I had more than two elements, the tree would keep going on, until the level is equal to the number of elements minus 1.

I have already built the initial #1 level. but how do I keep generating the tree without repeating combinations? In other words, how to verify if I should or not put a given element on the tree, in the most performatic way. There is some well-known algorithm for this?

Additional info: PHP

Body:
Edit: some modifications on building the tree

My idea is having a n-ary tree for n elements (x1, x2,... ,xn). let root be x0, then for any node xi (0 <= i <= n), you should have all children xj where (i < j <= n). In this way you can have all non-repeating combinations. E.g. for n=3 the 3-ary tree would be something like this:

root ---> x1 ---> x2 ---> x3
          |  ---> x3
root ---> x2 ---> x3
root ---> x3


来源: stackexchange

问:
How to render components on the same page in react
In my design on the top of the page, you can see pictures as links.
When you click on different pictures, the different component is called.
For example, onClick method show component which is set to true:

```<code>    state = {
        showPage1: true,
        showPage2: false,
        showPage3: false,
        showPage4: false
      };
      onClick1 = e =>
      this.setState({ showPage1 : true, showPage2: false, showPage3: false, showPage4: false
      });
      //continue with another onClick methods
</code>```

And in the final render method is:

```<code>render (){
    const src = '/images/image.jpg'
    return(
      <div>
      <Image.Group size='tiny'>
      <Image src={src} onClick={this.onClick1}/>
      </Image.Group>
      { this.renderPage() }
      </div>
    )
  }
</code>```

And based on that, the different components are shown on the same page.

```<code> renderPage() {
    const showPage1 = this.state.showPage1;
    if (showPage1) {
      return (
          <Page1 submit={this.submit}/>
      );}
</code>```

Now, each component is a form for me, where a user submits details.
When details are submitted, I do not know how to redirect to another component.
For example, if it was Page1, then I want automatically redirect to Page2 and so on.
This is what I have now, but this, of course, does not work.
I am not sure how to call one component after another component if this component does not have link, because it is displayed on the same page.

```<code>submit = data =>
     this.props.saveComponent(data).then(() => this.props.history.push('/text'));
</code>```

Thank you in advance!

答:
While it's true that routing is a more sustainable solution for this problem, without installing React Router it seems to me you just need to update your state, don't you? You could include a currentPage and nextPage property in data to indicate which page to transition to. For example:

```<code>submit = data =>
  this.props.saveComponent(data).then(
    () => this.setState({
      [data.currentPage]: false,
      [data.nextPage]: true
    })
</code>```

This is the kind of task routers are pretty good for though, so rather than doing conditional renders I'd definitely suggest learning more about routes.

ContentLicense: CC BY-SA 3.0

Body:
In my design on the top of the page, you can see pictures as links.
When you click on different pictures, the different component is called.
For example, onClick method show component which is set to true:

    state = {
        showPage1: true,
        showPage2: false,
        showPage3: false,
        showPage4: false
      };
      onClick1 = e =>
      this.setState({ showPage1 : true, showPage2: false, showPage3: false, showPage4: false
      });
      //continue with another onClick methods

And in the final render method is:

render (){
    const src = '/images/image.jpg'
    return(

      <Image.Group size='tiny'>
      <Image src={src} onClick={this.onClick1}/>
      </Image.Group>
      { this.renderPage() }

    )
  }

And based on that, the different components are shown on the same page.

 renderPage() {
    const showPage1 = this.state.showPage1;
    if (showPage1) {
      return (
          <Page1 submit={this.submit}/>
      );}

Now, each component is a form for me, where a user submits details.
When details are submitted, I do not know how to redirect to another component.
For example, if it was Page1, then I want automatically redirect to Page2 and so on.
This is what I have now, but this, of course, does not work.
I am not sure how to call one component after another component if this component does not have link, because it is displayed on the same page.

submit = data =>
     this.props.saveComponent(data).then(() => this.props.history.push('/text'));

Thank you in advance!

Body:
While it's true that routing is a more sustainable solution for this problem, without installing React Router it seems to me you just need to update your state, don't you? You could include a currentPage and nextPage property in data to indicate which page to transition to. For example:

submit = data =>
  this.props.saveComponent(data).then(
    () => this.setState({
      [data.currentPage]: false,
      [data.nextPage]: true
    })

This is the kind of task routers are pretty good for though, so rather than doing conditional renders I'd definitely suggest learning more about routes.


问:
Get permission to do PTRACE_ATTACH
I'm trying to write a program to do ptrace(PTRACE_ATTACH, pid, nullptr, nullptr) but it returns -1 and errno is 3 (No such process). The tracee are running and kicked off by me so I guess the tracer should have permission. What should I do then?

Also ptrace seems to be on per-thread basis. Is there easy way to get all the thread ids given a process id? Only way is to check /proc/{pid}/task/{tid}? How to catch thread creation?

答:
You can catch thread creation using ptrace(PTRACE_SETOPTIONS, pid, nullptr, PTRACE_O_TRACECLONE). I'd suggest carefully reading man 2 ptrace.

PTRACE_ATTACH might fail for numerous reasons. Try running your process as root with sudo.

Title: Get permission to do PTRACE_ATTACH


问:
How to wait a result from the EDT?
For test things, I want to launch a process on the swing edt, and wait for a result.

Usualy, I do that with a invokeAndWait. But perhaps is it possible to use a FutureTask, and launch this task on the EDT ??

Is it possible, and have you an exemple of (my) idea ?

Thanks.

答:
EventQueue.invokeAndWait behaves much the same as a lock. A lock with an awful lot inside, which is against the usual advice to keep short. It therefore is prone to cause deadlocks, and I'd recommend avoiding it.

Run a task on the EDT with EventQueue.invokeLater. Have that task run a task on your thread using a task queue. (Only avoid statics, and I suggest using a non-static wrapper around invokeLater so that you can test and monitor).

ContentLicense: CC BY-SA 2.5

Title: How to wait a result from the EDT?


问:
How to wait for all promises being added to array in forEach loop?
I would like my function to return array of promises. The code inside the function is asynchronous. I need to check each element for its type and do some processing. I do not know how the function can return all promises - once it has done the asynchronous processing. JSFiddle</p>

```<code>function addFeatures (input) {

  var result = [];
  input.forEach(function (el) {

    if (Number.isInteger(el)) {
      // placeholder asynchronous
      setTimeout(function () {
        result.push(
          new Promise(function (resolve, reject) {
            resolve(el.toString() + 'string')
          })
        )
      }, 2000);
    }
    else {
      // placeholder synchronous
      result.push(
        new Promise(function (resolve, reject) {
          resolve(el + 'string')
        }));
    }
  })
  return result;
};

var arr = [1, 'text']
var final = addFeatures(arr)
// should log 2 promises but logs only 1 - the synchronous
console.log(final)
</code>```

答:
Based on the excellent answer from Bergi, this is my contribution:

1- Function addFeatures with array.map:

```<code>function addFeatures (input) {
    return input.map(function(el) {
        return new Promise(function (resolve, reject) {
            if (Number.isInteger(el)) {
                setTimeout(resolve, 2000, el.toString() + 'string');
                /* setTimeout(reject, 2000, el.toString() + 'string'); //for reject */
            }
            else {
                resolve(el + 'string');
                /* reject(el + 'string'); //for reject */
            }
        })
    });
};
</code>```

2- A function to test the result from addFeatures.

If you don't manage correctly the answer from code above, sometimes the resolve from the asynchronous placeholder promise becomes pending and returns undefined. That's why you need Promise.all:

```<code>function foo(){
    return Promise.all(addFeatures([1, 'text'])).then(values => {
        return values;
    }, function() {
        throw 'Promise Rejected';
    });
}
</code>```

3- Calling your function above

```<code>foo().then(function(result) {
    console.log("result => " + result);
}).catch(function(error) {
    console.log("error => " + error);
});
</code>```

Fiddle

Body:
I would like my function to return array of promises. The code inside the function is asynchronous. I need to check each element for its type and do some processing. I do not know how the function can return all promises - once it has done the asynchronous processing. JSFiddle

function addFeatures (input) {

  var result = [];
  input.forEach(function (el) {

    if (Number.isInteger(el)) {
      // placeholder asynchronous
      setTimeout(function () {
        result.push(
          new Promise(function (resolve, reject) {
            resolve(el.toString() + 'string')
          })
        )
      }, 2000);
    }
    else {
      // placeholder synchronous
      result.push(
        new Promise(function (resolve, reject) {
          resolve(el + 'string')
        }));
    }
  })
  return result;
};

var arr = [1, 'text']
var final = addFeatures(arr)
// should log 2 promises but logs only 1 - the synchronous
console.log(final)

Body:
Based on the excellent answer from Bergi, this is my contribution:

1- Function addFeatures with array.map:

function addFeatures (input) {
    return input.map(function(el) {
        return new Promise(function (resolve, reject) {
            if (Number.isInteger(el)) {
                setTimeout(resolve, 2000, el.toString() + 'string');
                /* setTimeout(reject, 2000, el.toString() + 'string'); //for reject */
            }
            else {
                resolve(el + 'string');
                /* reject(el + 'string'); //for reject */
            }
        })
    });
};

2- A function to test the result from addFeatures.

If you don't manage correctly the answer from code above, sometimes the resolve from the asynchronous placeholder promise becomes pending and returns undefined. That's why you need Promise.all:

function foo(){
    return Promise.all(addFeatures([1, 'text'])).then(values => {
        return values;
    }, function() {
        throw 'Promise Rejected';
    });
}

3- Calling your function above

foo().then(function(result) {
    console.log("result => " + result);
}).catch(function(error) {
    console.log("error => " + error);
});

Fiddle


问:
Pass Rails model params to javascript onchange call?
Say I have the following rails code in a view:

```<code>    <%= form.select(:language_id,
        options_from_collection_for_select(Language.all, :id, :name),
        {},
        { :onchange => "setThemeAndMode('theme', 'mode')", class: "form-control" })
    %>
</code>```

Is it possible to send, say language.theme and language.mode to the setThemeAndMode call in the onchange event? Or even the specific language model element as some flat json?

答:
I'm having a hard time following what you want, but here's a shot at what I think you're asking.

You can interpolate the onchange string if you know the values at render time.

```<code><%= form.select(:language_id,
    options_from_collection_for_select(Language.all, :id, :name),
    {},
    { :onchange => "setThemeAndMode('#{Mything}', '#{other thing}')", class: "form-control" })
%>
</code>```

If you're trying to get the value of the select element's newly changed value, you'll need to get the select element's values in the javascript.

```<code>function setThemeAndModel() {
  var value = document.querySelector('input[name="language_id"').value
}
</code>```

Body:
Say I have the following rails code in a view:

    <%= form.select(:language_id,
        options_from_collection_for_select(Language.all, :id, :name),
        {},
        { :onchange => "setThemeAndMode('theme', 'mode')", class: "form-control" })
    %>

Is it possible to send, say language.theme and language.mode to the setThemeAndMode call in the onchange event? Or even the specific language model element as some flat json?

Body:
I'm having a hard time following what you want, but here's a shot at what I think you're asking.

You can interpolate the onchange string if you know the values at render time.

<%= form.select(:language_id,
    options_from_collection_for_select(Language.all, :id, :name),
    {},
    { :onchange => "setThemeAndMode('#{Mything}', '#{other thing}')", class: "form-control" })
%>

If you're trying to get the value of the select element's newly changed value, you'll need to get the select element's values in the javascript.

function setThemeAndModel() {
  var value = document.querySelector('input[name="language_id"').value
}


问:
Kubernetes POD arguments are not passing to service, however Docker arguments are passing correctly

Problem Statement:

I have a created a Docker image successfully from docker.io/joethecoder2/spring-boot-web. It has been tested with command line arguments, and those work correctly locally with Docker.

I am trying to pass java arguments that are passed to Docker to a Kubernetes POD that is defined with a single image docker.io/joethecoder2/spring-boot-web

The purpose of passing the arguments is to let the POD know what the IP address and port number are for the database service.

Problem Definition:

I have defined a Kubernetes POD here, however I believe the arguments are not passed correctly from singlePod.yaml when the POD is running the service.

Expected Result:

I expect that the Kubernetes POD be compatible with the Docker image defined here.

I expect that the Kubernetes POD accept arguments just like Docker does here:

docker run -it -p 8080:8080 joethecoder2/spring-boot-web
  -Dcassandra_ip=127.0.0.1 -Dcassandra_port=9042

```<code>curl -X POST --header 'Content-Type: application/json' --header 'Accept: text/plain' 'http://localhost:8080/restaurant/arguments'
</code>```

Correct result is returned-> 127.0.0.1:9042

Wrong Result:

I know that the actual arguments are not passed to the POD, because when I run the following service, I receive no arguments returned.

```<code>curl -X POST --header 'Content-Type: application/json' --header 'Accept: text/plain' 'http://192.168.64.3:32308/restaurant/arguments'
</code>```

Wrong result is returned->   :

Expected result -> 127.0.0.1:9042, as defined in the singlePod.yaml file

Why are the arguments missing, even though the POD definition file knows that the arguments have been defined staticly?

答:
If you want to inject environment variable into the container.It's better to use ConfigMap so it provides flexibility as well as separation of concern.

```<code>apiVersion: v1
kind: Pod
metadata:
  name: spring-boot-web-demo
  labels:
    purpose: demonstrate-spring-boot-web
spec:
  containers:
  - name: spring-boot-web
    image: docker.io/joethecoder2/spring-boot-web
    command: ["java","-jar", "spring-boot-web-0.0.1-SNAPSHOT.jar"]
  env:
  - name: DCASSANDRA_IP
    valueFrom:
        configMapKeyRef:
            key: Dcassandra_ip
            name: env-values
  - name: DCASSANDRA_PORT
    valueFrom:
        configMapKeyRef:
            key: Dcassandra_port
            name: env-values
  restartPolicy: OnFailure

---
apiVersion: v1
kind: ConfigMap
metadata:
  name: env-values
data:
  Dcassandra_port=9042
  Dcassandra_ip=127.0.0.1
</code>```

Now You need to write a Service Manifest file to expose this container in order to access it.
I have attached links for further research.

ConfigMap

Service

Body:
Problem Statement:

I have a created a Docker image successfully from docker.io/joethecoder2/spring-boot-web. It has been tested with command line arguments, and those work correctly locally with Docker.

I am trying to pass java arguments that are passed to Docker to a Kubernetes POD that is defined with a single image docker.io/joethecoder2/spring-boot-web

The purpose of passing the arguments is to let the POD know what the IP address and port number are for the database service.

Problem Definition:

I have defined a Kubernetes POD here, however I believe the arguments are not passed correctly from singlePod.yaml when the POD is running the service.

Expected Result:

I expect that the Kubernetes POD be compatible with the Docker image defined here.

I expect that the Kubernetes POD accept arguments just like Docker does here:

docker run -it -p 8080:8080 joethecoder2/spring-boot-web
  -Dcassandra_ip=127.0.0.1 -Dcassandra_port=9042

curl -X POST --header 'Content-Type: application/json' --header 'Accept: text/plain' 'http://localhost:8080/restaurant/arguments'

Correct result is returned-> 127.0.0.1:9042

Wrong Result:

I know that the actual arguments are not passed to the POD, because when I run the following service, I receive no arguments returned.

curl -X POST --header 'Content-Type: application/json' --header 'Accept: text/plain' 'http://192.168.64.3:32308/restaurant/arguments'

Wrong result is returned->   :

Expected result -> 127.0.0.1:9042, as defined in the singlePod.yaml file

Why are the arguments missing, even though the POD definition file knows that the arguments have been defined staticly?

Body:
If you want to inject environment variable into the container.It's better to use ConfigMap so it provides flexibility as well as separation of concern.

apiVersion: v1
kind: Pod
metadata:
  name: spring-boot-web-demo
  labels:
    purpose: demonstrate-spring-boot-web
spec:
  containers:
  - name: spring-boot-web
    image: docker.io/joethecoder2/spring-boot-web
    command: ["java","-jar", "spring-boot-web-0.0.1-SNAPSHOT.jar"]
  env:
  - name: DCASSANDRA_IP
    valueFrom:
        configMapKeyRef:
            key: Dcassandra_ip
            name: env-values
  - name: DCASSANDRA_PORT
    valueFrom:
        configMapKeyRef:
            key: Dcassandra_port
            name: env-values
  restartPolicy: OnFailure

---
apiVersion: v1
kind: ConfigMap
metadata:
  name: env-values
data:
  Dcassandra_port=9042
  Dcassandra_ip=127.0.0.1

Now You need to write a Service Manifest file to expose this container in order to access it.
I have attached links for further research.

ConfigMap

Service


问:
How do i write an R scripts that will create an object "l" below:
This is the output I want it to give. I have tried several options but it doesn't work.</p>

```<code>> l
 $item1
[1] 1 2 3
$item2
[1] "a"
$item3
[1] TRUE FALSE TRUE
$item4
[1] 2.5 4.2
</code>```

答:
```<code>l = list(item1 = c(1,2,3), item2 = 'a', item3 = c(TRUE,FALSE,TRUE), item4 = c(2.5,4.2))
</code>```

Be aware that all the items are of different datatypes.

Body:
This is the output I want it to give. I have tried several options but it doesn't work.

> l
 $item1
[1] 1 2 3
$item2
[1] "a"
$item3
[1] TRUE FALSE TRUE
$item4
[1] 2.5 4.2

Body:
l = list(item1 = c(1,2,3), item2 = 'a', item3 = c(TRUE,FALSE,TRUE), item4 = c(2.5,4.2))

Be aware that all the items are of different datatypes.


问:
Elixir Enum.max returns last instead of first element

If multiple elements are considered maximal, the first one that was found is returned.
  https://hexdocs.pm/elixir/Enum.html#max/2

```<code>iex> [4, 0, 4] |> Enum.with_index |> Enum.max
{4, 2}
</code>```

I would have expected that this returns {4, 0}, obviously I'm missing something?

Thanks for any help to clear up my confusion :)

答:
That's because after |> Enum.with_index, your list is [{4, 0}, {0, 1}, {4, 2}] and {4, 2} is greater than {4, 0} as when comparing tuples, when the first element is equal, the second (and then third and so on) elements are compared.

A correct way to test what you were trying to test would be to use Enum.max_by/2 instead like this:

```<code>iex(1)> [4, 0, 4] |> Enum.with_index |> Enum.max_by(fn {x, i} -> x end)
{4, 0}
</code>```

Body:
If multiple elements are considered maximal, the first one that was found is returned.
  https://hexdocs.pm/elixir/Enum.html#max/2

iex> [4, 0, 4] |> Enum.with_index |> Enum.max
{4, 2}

I would have expected that this returns {4, 0}, obviously I'm missing something?

Thanks for any help to clear up my confusion :)

Body:
That's because after |> Enum.with_index, your list is [{4, 0}, {0, 1}, {4, 2}] and {4, 2} is greater than {4, 0} as when comparing tuples, when the first element is equal, the second (and then third and so on) elements are compared.

A correct way to test what you were trying to test would be to use Enum.max_by/2 instead like this:

iex(1)> [4, 0, 4] |> Enum.with_index |> Enum.max_by(fn {x, i} -> x end)
{4, 0}


问:
Help with MySQL incorrect number of arguments function error
I am getting an error in MySQL that is driving me crazy and I just can't figure out what's wrong. I makes the following call:

```<code>CALL ProfileUpdateProgress(107)
</code>```

MySQL returns the error: "Incorrect number of arguments for FUNCTION ccms.fnGetProfileAlbumsPhotoCount; expected 2, got 1"

Now, as you can see in the code below, the call being made to that function is: fnGetProfileAlbumsPhotoCount(_profileId, profileUserId)

That's two arguments isn't it?? Why is it erroring??
I'm going mad!!

Database procs:

```<code>DELIMITER $$

DROP PROCEDURE IF EXISTS `ProfileUpdateProgress` $$
CREATE DEFINER=`root`@`%` PROCEDURE `ProfileUpdateProgress`(
        IN _profileId integer
    )
BEGIN

    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

    CALL ProfileUpdateProfileProgress(_profileId);

END $$

DELIMITER ;
</code>```

which in turn calls:

```<code>DELIMITER $$

DROP PROCEDURE IF EXISTS `ProfileUpdateProfileProgress` $$
CREATE DEFINER=`root`@`%` PROCEDURE `ProfileUpdateProfileProgress`(IN _profileId int)
BEGIN

    -- Declarations here

    SELECT profileEyes, profileSex, profileHair, profileBustBand, profileBustCup, profileBirthCountry, profileProfession , profileAbout,
            profileBiography, fnGetProfilePhoto(_profileId, null) AS profilePhoto, fnGetProfileAlbumsPhotoCount(_profileId, profileUserId) AS albumPhotoCount,
            userAllowMultipleProfiles, profileIsPrimary, fnUserGetChildrenProfileCount(userId) AS ownerProfileCount
    INTO  _profileEyes, _profileSex, _profileHair, _profileBustBand, _profileBustCup, _profileBirthCountry, _profileProfession,
           _profileAbout, _profileBiography, _profilePhoto, _albumPhotoCount, _userAllowMultipleProfiles, _profileIsPrimary,
           _ownerProfileCount
    FROM profile
    INNER JOIN user
      ON profileUserId = userId
    WHERE profileId = _profileId;

    -- Other irrelevant code here

END $$

DELIMITER ;
</code>```

and the function being called that errors looks like:

```<code>DELIMITER $$

DROP FUNCTION IF EXISTS `fnGetProfileAlbumsPhotoCount` $$
CREATE DEFINER=`root`@`%` FUNCTION `fnGetProfileAlbumsPhotoCount`(
  _profileId int,
  _userId int
) RETURNS int(11)
BEGIN

  DECLARE outProfileAlbumsPhotoCount int DEFAULT 0;

  -- Irrelvant Code

  RETURN outProfileAlbumsPhotoCount;

END $$

DELIMITER ;
</code>```

答: Ah finally solved it. Another function called fnUserGetChildrenProfileCount in the select columns was the culprit as it too had a call to the fnGetProfileAlbumsPhotoCount() function and THAT call only had one argument, i.e. missing the second one.</p>

Body:
I am getting an error in MySQL that is driving me crazy and I just can't figure out what's wrong. I makes the following call:

CALL ProfileUpdateProgress(107)

MySQL returns the error: "Incorrect number of arguments for FUNCTION ccms.fnGetProfileAlbumsPhotoCount; expected 2, got 1"

Now, as you can see in the code below, the call being made to that function is: fnGetProfileAlbumsPhotoCount(_profileId, profileUserId)

That's two arguments isn't it?? Why is it erroring??
I'm going mad!!

Database procs:

DELIMITER $$

DROP PROCEDURE IF EXISTS `ProfileUpdateProgress` $$
CREATE DEFINER=`root`@`%` PROCEDURE `ProfileUpdateProgress`(
        IN _profileId integer
    )
BEGIN

    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;

    CALL ProfileUpdateProfileProgress(_profileId);

END $$

DELIMITER ;

which in turn calls:

DELIMITER $$

DROP PROCEDURE IF EXISTS `ProfileUpdateProfileProgress` $$
CREATE DEFINER=`root`@`%` PROCEDURE `ProfileUpdateProfileProgress`(IN _profileId int)
BEGIN

    -- Declarations here

    SELECT profileEyes, profileSex, profileHair, profileBustBand, profileBustCup, profileBirthCountry, profileProfession , profileAbout,
            profileBiography, fnGetProfilePhoto(_profileId, null) AS profilePhoto, fnGetProfileAlbumsPhotoCount(_profileId, profileUserId) AS albumPhotoCount,
            userAllowMultipleProfiles, profileIsPrimary, fnUserGetChildrenProfileCount(userId) AS ownerProfileCount
    INTO  _profileEyes, _profileSex, _profileHair, _profileBustBand, _profileBustCup, _profileBirthCountry, _profileProfession,
           _profileAbout, _profileBiography, _profilePhoto, _albumPhotoCount, _userAllowMultipleProfiles, _profileIsPrimary,
           _ownerProfileCount
    FROM profile
    INNER JOIN user
      ON profileUserId = userId
    WHERE profileId = _profileId;

    -- Other irrelevant code here

END $$

DELIMITER ;

and the function being called that errors looks like:

DELIMITER $$

DROP FUNCTION IF EXISTS `fnGetProfileAlbumsPhotoCount` $$
CREATE DEFINER=`root`@`%` FUNCTION `fnGetProfileAlbumsPhotoCount`(
  _profileId int,
  _userId int
) RETURNS int(11)
BEGIN

  DECLARE outProfileAlbumsPhotoCount int DEFAULT 0;

  -- Irrelvant Code

  RETURN outProfileAlbumsPhotoCount;

END $$

DELIMITER ;


问:
Prevent a Retrofit request when a proxy is being used
Im using retrofit 2 + OkHttp in my android app.

There are some apps like BBVA that when a proxy is being used it doesnt makes any request and closes the user session, I can see my retrofit requests uisng a proxy like Charles.

The behavior I want to do is: if a proxy is being used. block / cancel any Retrofit 2 requests. is this possible with Retrofit?

thanks.

答:
You have to take several actions to protect your app:
   - Validate root, Certificate pinning (https) and Obfuscate code</p>


问:
Unused argument error with offset in column() for Shiny
Following is my server.R script:

```<code>shinyServer(function(input, output, session) {
})
</code>```

Following is my ui.R script:

```<code>library(shiny)
library(shinythemes)

shinyUI(navbarPage("My Electronic CV", theme = shinytheme('readable'), inverse = TRUE,
        tabPanel("Overview Section",
            fluidRow(
                column(width = 4,
                    "4"
                ),
                column(width = 3, offset = 2,
                    "3 offset 2"
                )
            ) #closing bracket for fluidRow
        ) #closing bracket for tabPanel
    ) #closing bracket for navbarPage
) #closing bracket for shinyUI
</code>```

With the above scripts, I keep getting the error:

```<code>Error in column(width = 4, "4") : unused argument (width = 4)
</code>```

But I am really confused why this is so - I have spent the last couple of hours trying to find out why I face this.
Could anybody please point me in the right direction?

答:
shiny and googlecharts both have the column() function. So, in order to solve this issue simply determine the package before the function name. For example:

```<code>shiny::column(width = 3, offset = 1, ...)
</code>```

this should solve the issue.

Body:
Following is my server.R script:

shinyServer(function(input, output, session) {
})

Following is my ui.R script:

library(shiny)
library(shinythemes)

shinyUI(navbarPage("My Electronic CV", theme = shinytheme('readable'), inverse = TRUE,
        tabPanel("Overview Section",
            fluidRow(
                column(width = 4,
                    "4"
                ),
                column(width = 3, offset = 2,
                    "3 offset 2"
                )
            ) #closing bracket for fluidRow
        ) #closing bracket for tabPanel
    ) #closing bracket for navbarPage
) #closing bracket for shinyUI

With the above scripts, I keep getting the error:

Error in column(width = 4, "4") : unused argument (width = 4)

But I am really confused why this is so - I have spent the last couple of hours trying to find out why I face this.
Could anybody please point me in the right direction?

Body:
shiny and googlecharts both have the column() function. So, in order to solve this issue simply determine the package before the function name. For example:

shiny::column(width = 3, offset = 1, ...)

this should solve the issue.


问:
VBA Loop to Conditionally Format showing Type Mismatch bug
I have an excel sheet with 4 columns, and I want to loop through the column and if (Column D/Column C) <> (Column B/Column A), highlight all 4 cells. I'm getting a Type Mismatch running the following and not sure why?</p>

```<code>Sub Check()

Dim ValA as Variant
Dim ValB as Variant
Dim ValC as Variant
Dim ValD as Variant
Dim ColA as Long
Dim ColB as Long
Dim ColC as Long
Dim ColD as Long

Set ValA = ActiveSheet.Rows(1).Find("A", lookat:=xlWhole)
ColA = ValA.Column

 Set ValB = ActiveSheet.Rows(1).Find("B", lookat:=xlWhole)
ColB = ValB.Column

 Set ValC = ActiveSheet.Rows(1).Find("C", lookat:=xlWhole)
ColC = ValC.Column

 Set ValD = ActiveSheet.Rows(1).Find("D", lookat:=xlWhole)
ColD = ValD.Column

LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

'Loop

For i = 2 to LastRow
    If ActiveSheet.Cells(i,ColD).Value/ActiveSheet.Cells(i,ColC).Value <> ActiveSheet.Cells(i, ColB).Value/ActiveSheet(i, ColA).Value Then
        ActiveSheet.Cells(i, ColA).Interior.ColorIndex = 3
        ActiveSheet.Cells(i, ColB).Interior.ColorIndex = 3
        ActiveSheet.Cells(i, ColC).Interior.ColorIndex = 3
        ActiveSheet.Cells(i, ColD).Interior.ColorIndex = 3
    End If
Next i
End Sub
</code>```

答:
Ok, I am new to StackOverflow and VBA, but I got your code to work by changing it a little... I tested it, and it works.

```<code>    Option Explicit

Private Sub test()

Dim Tbl1, ValA, ValB, ValC, ValD As Range
Dim ColA, ColB, ColC, ColD, i, LastRow As Long
Worksheets(1).Activate
Cells.Find("").Select
ActiveCell.Offset(0, -1).Select
Set Tbl1 = ActiveCell.CurrentRegion

Set ValA = Tbl1.Find("A")
Set ValA = Worksheets(1).Range(ValA, ValA.End(xlDown))
Set ValB = Tbl1.Find("B")
Set ValB = Worksheets(1).Range(ValB, ValB.End(xlDown))
Set ValC = Tbl1.Find("C")
Set ValC = Worksheets(1).Range(ValC, ValC.End(xlDown))
Set ValD = Tbl1.Find("D")
Set ValD = Worksheets(1).Range(ValD, ValD.End(xlDown))

LastRow = Tbl1.SpecialCells(xlCellTypeLastCell).Row

ColA = ValA.Cells.Count
ColB = ValB.Cells.Count
ColC = ValC.Cells.Count
ColD = ValC.Cells.Count

'Loop

If ColA > 0 And ColB > 0 And ColC > 0 And ColD > 0 Then

    For i = 2 To LastRow

        If ValD.Cells(i).Value / ValC.Cells(i).Value <>
ValB.Cells(i).Value / ValA.Cells(i).Value Then

            ValA.Cells(i).Interior.ColorIndex = 3
            ValB.Cells(i).Interior.ColorIndex = 3
            ValC.Cells(i).Interior.ColorIndex = 3
            ValD.Cells(i).Interior.ColorIndex = 3

        End If

    Next i

 Else

     MsgBox "Matches weren't found for A,B,C and D in row 1."

End If

End Sub
</code>```

Tada! Also got me thinking of how to automatically choose any number of columns... A-F for example. But the above code will fix what you are asking help on, best of luck!
-.Reverus.

Body:
I have an excel sheet with 4 columns, and I want to loop through the column and if (Column D/Column C) <> (Column B/Column A), highlight all 4 cells. I'm getting a Type Mismatch running the following and not sure why?

Sub Check()

Dim ValA as Variant
Dim ValB as Variant
Dim ValC as Variant
Dim ValD as Variant
Dim ColA as Long
Dim ColB as Long
Dim ColC as Long
Dim ColD as Long

Set ValA = ActiveSheet.Rows(1).Find("A", lookat:=xlWhole)
ColA = ValA.Column

 Set ValB = ActiveSheet.Rows(1).Find("B", lookat:=xlWhole)
ColB = ValB.Column

 Set ValC = ActiveSheet.Rows(1).Find("C", lookat:=xlWhole)
ColC = ValC.Column

 Set ValD = ActiveSheet.Rows(1).Find("D", lookat:=xlWhole)
ColD = ValD.Column

LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

'Loop

For i = 2 to LastRow
    If ActiveSheet.Cells(i,ColD).Value/ActiveSheet.Cells(i,ColC).Value <> ActiveSheet.Cells(i, ColB).Value/ActiveSheet(i, ColA).Value Then
        ActiveSheet.Cells(i, ColA).Interior.ColorIndex = 3
        ActiveSheet.Cells(i, ColB).Interior.ColorIndex = 3
        ActiveSheet.Cells(i, ColC).Interior.ColorIndex = 3
        ActiveSheet.Cells(i, ColD).Interior.ColorIndex = 3
    End If
Next i
End Sub

Body:
Ok, I am new to StackOverflow and VBA, but I got your code to work by changing it a little... I tested it, and it works.

    Option Explicit

Private Sub test()

Dim Tbl1, ValA, ValB, ValC, ValD As Range
Dim ColA, ColB, ColC, ColD, i, LastRow As Long
Worksheets(1).Activate
Cells.Find("").Select
ActiveCell.Offset(0, -1).Select
Set Tbl1 = ActiveCell.CurrentRegion

Set ValA = Tbl1.Find("A")
Set ValA = Worksheets(1).Range(ValA, ValA.End(xlDown))
Set ValB = Tbl1.Find("B")
Set ValB = Worksheets(1).Range(ValB, ValB.End(xlDown))
Set ValC = Tbl1.Find("C")
Set ValC = Worksheets(1).Range(ValC, ValC.End(xlDown))
Set ValD = Tbl1.Find("D")
Set ValD = Worksheets(1).Range(ValD, ValD.End(xlDown))

LastRow = Tbl1.SpecialCells(xlCellTypeLastCell).Row

ColA = ValA.Cells.Count
ColB = ValB.Cells.Count
ColC = ValC.Cells.Count
ColD = ValC.Cells.Count

'Loop

If ColA > 0 And ColB > 0 And ColC > 0 And ColD > 0 Then

    For i = 2 To LastRow

        If ValD.Cells(i).Value / ValC.Cells(i).Value <>
ValB.Cells(i).Value / ValA.Cells(i).Value Then

            ValA.Cells(i).Interior.ColorIndex = 3
            ValB.Cells(i).Interior.ColorIndex = 3
            ValC.Cells(i).Interior.ColorIndex = 3
            ValD.Cells(i).Interior.ColorIndex = 3

        End If

    Next i

 Else

     MsgBox "Matches weren't found for A,B,C and D in row 1."

End If

End Sub

Tada! Also got me thinking of how to automatically choose any number of columns... A-F for example. But the above code will fix what you are asking help on, best of luck!
-.Reverus.


问:
Dax Rolling Average with multiple records per day
Take a simple table

```<code>SalesTime
Product
UnitsSold
</code>```

There is one row per sale. So there are multiple rows per day. I need a chart that will show the average units sold per sale over 7 days and average units sold per day over 7 days.

The examples that I found all used DATESBETWEEN or DATESINPERIOD and those throw an error if the table has multiple records per date.

答:
I will name this table Sales and assume that Sales[SalesTime] is a date type rather than a datetime type. If not, create a new calculated column

```<code>Sales[SalesDate] = Sales[SalesTime].[Date]
</code>```

and work with that instead.

Your rolling average units per sale can be calculated something like this:

```<code>AvgUnitsPerSale =
VAR CurrDay = MIN(Sales[SalesTime])
RETURN CALCULATE(
            AVERAGE(Sales[UnitsSold]),
            DATESBETWEEN(Sales[SalesTime], CurrDay-7, CurrDay))
</code>```

You can get an average count of sales per day by using COUNT instead of AVERAGE. To get the average units sold per day, multiply the average count of sales and the average units per sale.

Body:
Take a simple table

SalesTime
Product
UnitsSold

There is one row per sale. So there are multiple rows per day. I need a chart that will show the average units sold per sale over 7 days and average units sold per day over 7 days.

The examples that I found all used DATESBETWEEN or DATESINPERIOD and those throw an error if the table has multiple records per date.

Body:
I will name this table Sales and assume that Sales[SalesTime] is a date type rather than a datetime type. If not, create a new calculated column

Sales[SalesDate] = Sales[SalesTime].[Date]

and work with that instead.

Your rolling average units per sale can be calculated something like this:

AvgUnitsPerSale =
VAR CurrDay = MIN(Sales[SalesTime])
RETURN CALCULATE(
            AVERAGE(Sales[UnitsSold]),
            DATESBETWEEN(Sales[SalesTime], CurrDay-7, CurrDay))

You can get an average count of sales per day by using COUNT instead of AVERAGE. To get the average units sold per day, multiply the average count of sales and the average units per sale.


问:
Semantic UI React Popup(s) Not Appearing
See title.

Code is literally

```<code><Popup
trigger={<li id="close"><a>Close</a></li>}
content="Click to close"
basic
/>
</code>```

And yeah when the item in question is hovered, or clicked, the popup doesn't appear. When I set open={true} it does, not attached to the component (as expected). Has anyone encountered this issue and could they advise possible solutions?

答:
CSS code applied to HTML was making it position: relative which affect where Popups appeared - they were appearing, just at the wrong position. Unfortunately removing this code completely ruins our sticky footer.

Hopefully anyone else who experiences the same problem will see this and realise their mistake.

Body:
See title.

Code is literally

<Popup
trigger={
Close
}
content="Click to close"
basic
/>

And yeah when the item in question is hovered, or clicked, the popup doesn't appear. When I set open={true} it does, not attached to the component (as expected). Has anyone encountered this issue and could they advise possible solutions?

ContentLicense: CC BY-SA 4.0


问:
Python - Why is the dictionary shortened when mapping two lists?
I have two large lists, equal lengths 0f 2574 items a piece. I want to map the items into a dictionary, because when mapped, I want to know which values are different from their keys. One value per key. When I map them however, I get a much shorter dictionary with length 76.

Here's a test:

```<code>Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> list1 = [1, 1, 3, 4, 5, 6, 7, 8, 8, 8, 8, 8, 8, 10]
>>> list2 = [1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 8, 8, 9, 10]
>>>
>>> listdict = dict(zip(list1, list2))
>>> print len(list1)
14
>>> print len(list2)
14
>>> print len(listdict)
8
>>> print listdict
{1: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 9, 10: 10}
</code>```

So why does using dict(zip()) remove the 1's that would map to one another and the 8's that would map to one another but keeps everything else? Basically, the two lists I ahve are equal length, and for each index I need to know if the item is different. Positions in each list for comparisons must match. So list1[0] to list2[0], and nowhere else. when I got the dictionary I figured something like this would work:

```<code>for k,v in listdict:
if k != v:
print k, '\t', v
</code>```

but they're not matching up...

答:
In order to preserve the length and order of elements as in the lists, use </p>

```<code>OrderedDict(zip(list1,list2))
</code>```

Body:
I have two large lists, equal lengths 0f 2574 items a piece. I want to map the items into a dictionary, because when mapped, I want to know which values are different from their keys. One value per key. When I map them however, I get a much shorter dictionary with length 76.

Here's a test:

Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> list1 = [1, 1, 3, 4, 5, 6, 7, 8, 8, 8, 8, 8, 8, 10]
>>> list2 = [1, 2, 3, 4, 5, 6, 7, 8, 8, 8, 8, 8, 9, 10]
>>>
>>> listdict = dict(zip(list1, list2))
>>> print len(list1)
14
>>> print len(list2)
14
>>> print len(listdict)
8
>>> print listdict
{1: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 9, 10: 10}

So why does using dict(zip()) remove the 1's that would map to one another and the 8's that would map to one another but keeps everything else? Basically, the two lists I ahve are equal length, and for each index I need to know if the item is different. Positions in each list for comparisons must match. So list1[0] to list2[0], and nowhere else. when I got the dictionary I figured something like this would work:

for k,v in listdict:
if k != v:
print k, '\t', v

but they're not matching up...

Body:
In order to preserve the length and order of elements as in the lists, use

OrderedDict(zip(list1,list2))


问:
MySQL, RoR issues on Snow Leopard
I feel I've gone through every post on this subject, and I'm still banging my head against the wall.

I am running...

Mac OS 10.6.6

MySQL 5.1.4.4 (on MAMP) or (MySQL 5.5.8 in my /usr/ directory) both can be running and work fine

Ruby 1.8.7 (2010-12-23 patchlevel 330) [i686-darwin10.6.0] (using RVM)

Rails 2.2.2

Gem 1.4.2

MySQL gem 2.8.1 (it says it's installed)

When I fire up the RoR app I've been developing, the mongrel appears to load fine. When I try to bring up the app in my browser I get the following error...

/!\ FAILSAFE /!\  Thu Jan 20 19:46:07 -0500 2011

  Status: 500 Internal Server Error

  uninitialized constant MysqlCompat::MysqlRes

then what follows are a bunch of lines like...

```<code>/Users/PJ/.rvm/gems/ruby-1.8.7-p330/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:442:in `load_missing_constant'
</code>```

I feel I have tired every variation of the ARCHFLAGS solutions that have been previously suggested on other posts. None have worked.

I am using MAMP and RVM as I have done other uninstalls and re-installs of MySQL, Ruby, Rails and various gems in attempts from other suggested solutions.

The app worked fine prior to my update to Snow Leopard. I am not a very sophisticated developer type, so I apologize in advance for being, well, not the brightest.

答:
I coudn't ever seem to get the 2.8.1 mysql gem to work.
I downgraded it to the 2.7 version which led to a series of new errors (a DYLD_LIBRARY_PATH error), but it was eventually figured out and I am up and running again.</p>

Title: MySQL, RoR issues on Snow Leopard

Body:
I feel I've gone through every post on this subject, and I'm still banging my head against the wall.

I am running...

Mac OS 10.6.6

MySQL 5.1.4.4 (on MAMP) or (MySQL 5.5.8 in my /usr/ directory) both can be running and work fine

Ruby 1.8.7 (2010-12-23 patchlevel 330) [i686-darwin10.6.0] (using RVM)

Rails 2.2.2

Gem 1.4.2

MySQL gem 2.8.1 (it says it's installed)

When I fire up the RoR app I've been developing, the mongrel appears to load fine. When I try to bring up the app in my browser I get the following error...

/!\ FAILSAFE /!\  Thu Jan 20 19:46:07 -0500 2011

  Status: 500 Internal Server Error

  uninitialized constant MysqlCompat::MysqlRes

then what follows are a bunch of lines like...

/Users/PJ/.rvm/gems/ruby-1.8.7-p330/gems/activesupport-2.2.2/lib/active_support/dependencies.rb:442:in `load_missing_constant'

I feel I have tired every variation of the ARCHFLAGS solutions that have been previously suggested on other posts. None have worked.

I am using MAMP and RVM as I have done other uninstalls and re-installs of MySQL, Ruby, Rails and various gems in attempts from other suggested solutions.

The app worked fine prior to my update to Snow Leopard. I am not a very sophisticated developer type, so I apologize in advance for being, well, not the brightest.


问:
What is the difference between git diff HEAD vs. git diff --staged?
What is the difference between git diff HEAD and git diff --staged? I tried both but both give the same output.

答:
git diff View difference between Stage and Working Directory

git diff --staged View difference between HEAD and Stage

git diff HEAD View difference between HEAD and Working Directory

img src

HEAD is a reference to the last commit in the currently checked-out branch.

Staging area, stage and index all mean the same thing

Unstaged changes exist in our Working Directory, but Git hasn’t recorded them into its version history yet.

Staged changes are a lot like unstaged changes, except that they’ve been marked to be committed the next time you run git commit


问:
How to generate a histogram in Django view (from Pandas DF) and pass to template?
I have a script that gets executed when the following view function is called in Django:

```<code>def CalScriptResultsView(request):
    all_activities = models.CalEvents.objects.filter(user=request.user)

    activities = ['Undefined',]
    for activity in all_activities:
        activities.append(activity.activity_code)

    script_result = gCalScriptMain.main(activities)

    return render(request, 'gCalData/gCalData_result.html', {'script_result': script_result})
</code>```

The script gCalScriptMain.main() reads events in a Google calendar and builds a Pandas data frame. The headers (columns) of the data frame are the activities defined by the user and the index (rows) is made of date type dates (e.g. 2017-10-02). The actual data consists in number of hours spent on each activity for each day (in a three month period).

I want to be able to plot a histogram that looks something like this:

And I have to somehow return the histogram to the view so that then it gets passed to the corresponding template and can be displayed on the webpage.

What I have tried is the following:

```<code>import matplotlib.pyplot as plt

df.hist()
plt.savefig('path/to/hist.png')
</code>```

But it just generates a blank file.

However, I'm also doubting if this is a good approach or if there is something better. Any ideas?

答:
I've found pygal to be a good tool for what I want to accomplish. I'm creating an .svg file and calling it from the template.

```<code>line_chart = pygal.Line()
line_chart.title = 'Hours spent in each activity during the specified
period ({} to {})'.format(input_start,input_end)
line_chart.x_labels = map(lambda d: d.strftime('%Y-%m-%d'),
list(df.index.values))
for activity in act_hours:
    line_chart.add(activity, df[activity])

static_path = 'images/charts/line_chart_{}.svg'.format(user.id)
line_chart.render_to_file('static/' + static_path)

activities['static_path'] = static_path
</code>```

In the template:

```<code>  <div class="container">
    {% with chart_path=script_result.static_path %}
    <object type="image/svg+xml" data="{% static chart_path %}">
      Error: Your browser doesn't support SVG files
    </object>
    {% endwith %}
  </div>
</code>```

Body:
I have a script that gets executed when the following view function is called in Django:

def CalScriptResultsView(request):
    all_activities = models.CalEvents.objects.filter(user=request.user)

    activities = ['Undefined',]
    for activity in all_activities:
        activities.append(activity.activity_code)

    script_result = gCalScriptMain.main(activities)

    return render(request, 'gCalData/gCalData_result.html', {'script_result': script_result})

The script gCalScriptMain.main() reads events in a Google calendar and builds a Pandas data frame. The headers (columns) of the data frame are the activities defined by the user and the index (rows) is made of date type dates (e.g. 2017-10-02). The actual data consists in number of hours spent on each activity for each day (in a three month period).

I want to be able to plot a histogram that looks something like this:

And I have to somehow return the histogram to the view so that then it gets passed to the corresponding template and can be displayed on the webpage.

What I have tried is the following:

import matplotlib.pyplot as plt

df.hist()
plt.savefig('path/to/hist.png')

But it just generates a blank file.

However, I'm also doubting if this is a good approach or if there is something better. Any ideas?

Body:
I've found pygal to be a good tool for what I want to accomplish. I'm creating an .svg file and calling it from the template.

line_chart = pygal.Line()
line_chart.title = 'Hours spent in each activity during the specified
period ({} to {})'.format(input_start,input_end)
line_chart.x_labels = map(lambda d: d.strftime('%Y-%m-%d'),
list(df.index.values))
for activity in act_hours:
    line_chart.add(activity, df[activity])

static_path = 'images/charts/line_chart_{}.svg'.format(user.id)
line_chart.render_to_file('static/' + static_path)

activities['static_path'] = static_path

In the template:

  <div class="container">
    {% with chart_path=script_result.static_path %}
    <object type="image/svg+xml" data="{% static chart_path %}">
      Error: Your browser doesn't support SVG files
    </object>
    {% endwith %}
  </div>


问:
How to modify URL for Wordpress in config files, not through the Admin Console
My Wordpress site has an incorrect URL so when I access the domain "phoenixadultsoccerleague.com" it doesn't work.  You'll see "Home" and "About" links.  When you hover over those links you'll see a different URL.

How can I go into the configuration files and update the URL so the Wordpress site will come up?  It should be pointing to "phoenixadultsoccerleague.com"  Is it in the DB files or the PHP files in the file structure?

Thank you in advance.

答:
You have to edit the wp_configuration table in your DB. The site domain is written there.

After that, you would have a working wordpress, but I suggest you to run also the domain edit by your control panel: it will do a bunch of stuff that is very tedius if done "by hand"


问:
How to populate a form with array of data in Angular2?
The SO question below helped me setup a formbuilder, proper validation, and a dynamic set of input fields from a formBuilder Array.

How to assign and validate arrays to forms in Angular2

Note this solution code http://plnkr.co/edit/YoqdBEo0MihaxdhHH1FV?p=preview

Everything works great on a new form, but I get stuck when trying to populate said form from the database.

I'm using the following code and initialValue has multiple emails saved from this form in a previous transaction. All my other form fields work perfectly. I'm just not sure how to operate on an array.

```<code>ngOnChanges(changes: SimpleChanges): void {
  if(this.form && changes['initialValue']){
    this.emails = changes['initialValue'].currentValue.emails;
    this.form.patchValue(changes['initialValue'].currentValue);
    //console.log('emails are now', this.emails);
    //this.emailCtrl = this.fb.array([], Validators.minLength(1));
    //this.emails.forEach((email: any) => this.addEmail(email));
  }
}
</code>```

If I keep the lines commented only the first email in the array shows properly in the form.

If i uncomment the lines and try to refresh the emailsCtrl w/ the new list of emails. I get the following error.

```<code>ERROR Error: Cannot find control with path: 'emails -> 1 -> email'
at _throwError (forms.js:2385)
at setUpControl (forms.js:2255)
at FormGroupDirective.addControl (forms.js:6606)
at FormControlName._setUpControl (forms.js:7256)
at FormControlName.ngOnChanges (forms.js:7169)
at checkAndUpdateDirectiveInline (core.js:12092)
at checkAndUpdateNodeInline (core.js:13598)
at checkAndUpdateNode (core.js:13541)
at debugCheckAndUpdateNode (core.js:14413)
at debugCheckDirectivesFn (core.js:14354)
</code>```

答:
```<code>this.emailCtrl = this.fb.array([], Validators.minLength(1));
this.emails.forEach((email: any) => this.addEmail(email));
</code>```

The FormArray should be this.emailsCtrl other than this.emailCtrl
   The formArrayName is emails and the formControlName is email

You can access it based on the name:

```<code>  this.emailsCtrl = this.form.get('emails') as FormArray;
  this.emails.forEach(email => this.addEmail(email));
</code>```

Body:
The SO question below helped me setup a formbuilder, proper validation, and a dynamic set of input fields from a formBuilder Array.

How to assign and validate arrays to forms in Angular2

Note this solution code http://plnkr.co/edit/YoqdBEo0MihaxdhHH1FV?p=preview

Everything works great on a new form, but I get stuck when trying to populate said form from the database.

I'm using the following code and initialValue has multiple emails saved from this form in a previous transaction. All my other form fields work perfectly. I'm just not sure how to operate on an array.

ngOnChanges(changes: SimpleChanges): void {
  if(this.form && changes['initialValue']){
    this.emails = changes['initialValue'].currentValue.emails;
    this.form.patchValue(changes['initialValue'].currentValue);
    //console.log('emails are now', this.emails);
    //this.emailCtrl = this.fb.array([], Validators.minLength(1));
    //this.emails.forEach((email: any) => this.addEmail(email));
  }
}

If I keep the lines commented only the first email in the array shows properly in the form.

If i uncomment the lines and try to refresh the emailsCtrl w/ the new list of emails. I get the following error.

ERROR Error: Cannot find control with path: 'emails -> 1 -> email'
at _throwError (forms.js:2385)
at setUpControl (forms.js:2255)
at FormGroupDirective.addControl (forms.js:6606)
at FormControlName._setUpControl (forms.js:7256)
at FormControlName.ngOnChanges (forms.js:7169)
at checkAndUpdateDirectiveInline (core.js:12092)
at checkAndUpdateNodeInline (core.js:13598)
at checkAndUpdateNode (core.js:13541)
at debugCheckAndUpdateNode (core.js:14413)
at debugCheckDirectivesFn (core.js:14354)

Body:
this.emailCtrl = this.fb.array([], Validators.minLength(1));
this.emails.forEach((email: any) => this.addEmail(email));

The FormArray should be this.emailsCtrl other than this.emailCtrl
   The formArrayName is emails and the formControlName is email

You can access it based on the name:

  this.emailsCtrl = this.form.get('emails') as FormArray;
  this.emails.forEach(email => this.addEmail(email));


答:
I believe I understand your problem and below is a solution.

Explanation: I sorted the data rows into start and end points sets like in gap and islands problems and then joined a start id with end id for same material mode and truck.

```<code>; with separationSet as
(
    select
        *,
        dense_rank()
            over(
                partition by materialmode,truckid
                order by locationid asc
                ) as r
    from T
)
, scoredSet as
(
    select
        *,
        row_number()
            over(
                partition by materialmode,truckid,r
                order by id
                ) as r2
    from separationSet
)
, startToEndPairs as
(
    select
        S.id as StartId,
        E.id  as EndId
    from scoredSet S
        join scoredSet E
             on S.r=1 and E.r=2
             and S.r2=E.r2
             and S.TruckId=E.TruckId
             and S.materialmode=E.materialmode
)

select
    *
from starttoEndPairs
order by StartId asc
</code>```

See working demo

Title: SQL Server Obtain Pairs of records

Body:
I am trying to obtain "pairs" of records and I just cant figure out.

Here is what I have:

Id  TruckId LocationId  MaterialMode
145223  1198    19  43
145224  1199    19  43
145225  1200    19  43
145226  1198    20  43
145227  1199    20  43
145228  1200    20  43
145229  1199    21  46
145230  1198    21  46
145231  1200    21  46
145232  1198    22  46
145233  1199    22  46
145234  1200    22  46
145235  1198    19  43
145236  1199    19  43
145237  1200    19  43
145238  1198    20  43
145239  1199    20  43
145240  1200    20  43
145241  1199    21  46
145242  1198    21  46
145243  1200    21  46
145244  1198    22  46
145245  1199    22  46
145246  1200    22  46

I need to get the following:

Id A    Id B
145223  145226
145224  145227
145225  145228
145229  145233
145230  145232
145231  145234
145235  145238
145236  145239
145237  145240
145241  145245
145242  145244
145243  145246

Basically matching a TruckId between 2 locations under the same material mode

I have tried:

SELECT
 Id AS IdA,
 Lead(Id, 1, NULL) OVER(PARTITION BY TruckId, MaterialMode ORDER BY Date) AS IdB
FROM T

This produces:

Id A    Id B
145223  145226
145224  145227
145225  145228
*145226 145235
*145227 145236
*145228 145237
145229  145233
145230  145232
145231  145234
*145232 145242
*145233 145241
*145234 145243
145235  145238
145236  145239
145237  145240
145241  145245
145242  145244
145243  145246

Records with the * I don't want them. If a pair is matched then that record should not be part of "another match"

Body:
I believe I understand your problem and below is a solution.

Explanation: I sorted the data rows into start and end points sets like in gap and islands problems and then joined a start id with end id for same material mode and truck.

; with separationSet as
(
    select
        *,
        dense_rank()
            over(
                partition by materialmode,truckid
                order by locationid asc
                ) as r
    from T
)
, scoredSet as
(
    select
        *,
        row_number()
            over(
                partition by materialmode,truckid,r
                order by id
                ) as r2
    from separationSet
)
, startToEndPairs as
(
    select
        S.id as StartId,
        E.id  as EndId
    from scoredSet S
        join scoredSet E
             on S.r=1 and E.r=2
             and S.r2=E.r2
             and S.TruckId=E.TruckId
             and S.materialmode=E.materialmode
)

select
    *
from starttoEndPairs
order by StartId asc

See working demo


问:
ArangoDB memory overflow - is there no solution?
When I perform AQL queries, I run into this error:

Query: AQL: query would use more memory than allowed (while executing)

My dataset: 9 billion vertices, 19 billion edges

My cluster has three nodes, running Centos 7 with 32 GB RAM

I only hope that the query can be executed and will not be reported wrong. What configuration files can be modified to achieve the purpose? I am new to ArangoDB.

答:
Some back-of-the-envelope calculations suggest you will need to use the RocksDB engine:

```<code>(100 * 28 * 10^9) / (3 * (32 * 10^9)) => 29.17
</code>```

See https://www.arangodb.com/why-arangodb/comparing-rocksdb-mmfiles-storage-engines/

Body:
Some back-of-the-envelope calculations suggest you will need to use the RocksDB engine:

(100 * 28 * 10^9) / (3 * (32 * 10^9)) => 29.17

See https://www.arangodb.com/why-arangodb/comparing-rocksdb-mmfiles-storage-engines/


问:
Can't style an element in a td
I've been trying to style the h3 and p tags, but I couldn't. I tried class, id, divs, and spans, yet to no avail. I'm also kind of new to coding, so I'm sorry for the poor indentation.

h3, p {
 color:#2c6ffe;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><tr>
        <td colspan="2">
            <u><h3>Introduction:</h3></u>
            <p><i>To Kill A Mockingbird</i> is a coming of age novel that was
            written by Harper Lee. The story To Kill A Mockingbird is not based on
            a true story but references in Harper Lee’s daily life. The book was
            written in at the time of the Great Depression and the Jim Crow laws,
            taking place in the early 1930s. The story takes place in Maycomb,
            Alabama, and is narrated by the main character, a little girl named
            Jean Louise “Scout” Finch. Scout’s father, Atticus Finch, is a lawyer
            with high moral standards.The book is an accurate representation of
            racism and discrimination towards black people in early 1900s. Scout,
            who happens to be the protagonist of the story, is also the narrator
            as the story is seen through her eyes and explained through her
            thoughts.</p>
         </td></code>```

答:
Have you tried wrapping the entire

 with

?
Are you getting any error messages in the console when you press F12 (for DevTools)?

Try copy pasting your html into Codepen.io and seeing if it works there
You can also try being more specific with your query selector for example

```<code>table > h3{ color: black;}
</code>```

Or if all else fails, Inline-styles

```<code><h3 style="color: black;">Mockingbird</h3>
</code>```

Also this is not great practice but applying the !important tag in CSS may solve some cascading issue.

```<code>h3{ color: pink !important}
</code>```

Title: Can't style an element in a td

Body:
I've been trying to style the h3 and p tags, but I couldn't. I tried class, id, divs, and spans, yet to no avail. I'm also kind of new to coding, so I'm sorry for the poor indentation.

h3, p {
 color:#2c6ffe;
}

Introduction:

To Kill A Mockingbird is a coming of age novel that was
            written by Harper Lee. The story To Kill A Mockingbird is not based on
            a true story but references in Harper Lee’s daily life. The book was
            written in at the time of the Great Depression and the Jim Crow laws,
            taking place in the early 1930s. The story takes place in Maycomb,
            Alabama, and is narrated by the main character, a little girl named
            Jean Louise “Scout” Finch. Scout’s father, Atticus Finch, is a lawyer
            with high moral standards.The book is an accurate representation of
            racism and discrimination towards black people in early 1900s. Scout,
            who happens to be the protagonist of the story, is also the narrator
            as the story is seen through her eyes and explained through her
            thoughts.

Body:
Have you tried wrapping the entire <tr></tr> with <table></table>?
Are you getting any error messages in the console when you press F12 (for DevTools)?

Try copy pasting your html into Codepen.io and seeing if it works there
You can also try being more specific with your query selector for example

table > h3{ color: black;}

Or if all else fails, Inline-styles

<h3 style="color: black;">Mockingbird</h3>

Also this is not great practice but applying the !important tag in CSS may solve some cascading issue.

h3{ color: pink !important}


问:
Unity/C# Adding two areas presented by vector2
I have two areas, which are both given in there bounds.size. Now the z-axis does not matter for me, since i am working in 2D. I want to add these vectors so i have a vector, which represents the jointed area. Simply adding these vectors does not work.</p>

答:
If you just need the combined area of two rectangles (x1, y1) and (x2, y2), then take

```<code>float totalArea = (x1 * y1) + (x2 * y2)
</code>```

which is literally just summing the areas of the two rectangles. If you need a rectangle with that area and don't care what shape the rectangle is, just choose

```<code>Vector2 rect = new Vector2(Mathf.sqrt(totalArea), Mathf.sqrt(totalArea))
</code>```

Which is a square whose area is equal to the sum of the areas of the two rectangles. (I don't know what you plan on doing with this vector. It is completely arbitrary and is not a particularly meaningful value, since there are an infinite number of possible rectangles with any given totalArea. If you just want the sum of the areas, you'd be better off storing it as a float.)

Body:
If you just need the combined area of two rectangles (x1, y1) and (x2, y2), then take

float totalArea = (x1 * y1) + (x2 * y2)

which is literally just summing the areas of the two rectangles. If you need a rectangle with that area and don't care what shape the rectangle is, just choose

Vector2 rect = new Vector2(Mathf.sqrt(totalArea), Mathf.sqrt(totalArea))

Which is a square whose area is equal to the sum of the areas of the two rectangles. (I don't know what you plan on doing with this vector. It is completely arbitrary and is not a particularly meaningful value, since there are an infinite number of possible rectangles with any given totalArea. If you just want the sum of the areas, you'd be better off storing it as a float.)


问:
Merge two columns in Select into one column based on a condition
I have a SELECT with two columns I'd like to merge based on the condition that if the left one is null it should choose the right column but when the left column is not null it should always choose the left.

scenario

What I have on the left is what I currently Have and I'd like to get the table on the right

AlphabetTable

```<code>+-------+------+    +---------+
| A     | B    |    | Desired |
+-------+------+    |---------+
| null  | 1    |    | 1       |
| null  | 1    |    | 1       |
|  2    | null |    | 2       |
|  2    | 3    |    | 2       |
|  2    | 5    |    |  2      |
|  null | null |    | null    |
+-------+------+    +---------+
</code>```

SQL for left table above

```<code>SELECT
    CAST((select sum(Total) from LettersTable LT
                                WHERE LT.ID = ID
                                AND LT.Count > 5)
                                AS INT) as A
    CAST((select sum(Total) from LettersTable LT
                                WHERE LT.ID = ID
                                AND LT.Count > 5)
                                AS INT) as B
From IDTable
</code>```

Heres what I have so far

```<code>SELECT
        CASE WHEN
            CAST((select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT) IS NULL
            THEN
                (select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT)
            ELSE
                (select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT)
 FROM AlphabetTable AT
</code>```

答:
Assuming that you have the columns A and B available, one of the below should work:

```<code>SELECT
CASE WHEN A IS NULL THEN B ELSE A END AS DESIRED_COL
FROM
YOUR_TABLE;
</code>```

Or as @NetMage suggested:

```<code>SELECT
CASE WHEN (A IS NOT NULL OR B IS NOT NULL) THEN COALESCE(A,B) ELSE NULL END AS DESIRED_COL
FROM YOUR_TABLE;
</code>```

Since COALESCE will throw an error if both columns are NULL, you would still require a case when to deal with that condition.

Body:
I have a SELECT with two columns I'd like to merge based on the condition that if the left one is null it should choose the right column but when the left column is not null it should always choose the left.

scenario

What I have on the left is what I currently Have and I'd like to get the table on the right

AlphabetTable

+-------+------+    +---------+
| A     | B    |    | Desired |
+-------+------+    |---------+
| null  | 1    |    | 1       |
| null  | 1    |    | 1       |
|  2    | null |    | 2       |
|  2    | 3    |    | 2       |
|  2    | 5    |    |  2      |
|  null | null |    | null    |
+-------+------+    +---------+

SQL for left table above

SELECT
    CAST((select sum(Total) from LettersTable LT
                                WHERE LT.ID = ID
                                AND LT.Count > 5)
                                AS INT) as A
    CAST((select sum(Total) from LettersTable LT
                                WHERE LT.ID = ID
                                AND LT.Count > 5)
                                AS INT) as B
From IDTable

Heres what I have so far

SELECT
        CASE WHEN
            CAST((select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT) IS NULL
            THEN
                (select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT)
            ELSE
                (select sum(Total) from LettersTable LT
                        WHERE LT.ID = AT.ID
                        AND LT.Count > 5)
                        AS INT)
 FROM AlphabetTable AT

Body:
Assuming that you have the columns A and B available, one of the below should work:

SELECT
CASE WHEN A IS NULL THEN B ELSE A END AS DESIRED_COL
FROM
YOUR_TABLE;

Or as @NetMage suggested:

SELECT
CASE WHEN (A IS NOT NULL OR B IS NOT NULL) THEN COALESCE(A,B) ELSE NULL END AS DESIRED_COL
FROM YOUR_TABLE;

Since COALESCE will throw an error if both columns are NULL, you would still require a case when to deal with that condition.


问:
C++ - Recursive counter
I am trying to create a counter. It counts each operation such as multiplication, addition, subtraction, division. Every time I try to cout the counter, it stays as zero.

Can anyone shed any light on what I am doing wrong?

A bulk of my code is missing so I can protect it from other classmates, however I have listed how many operations is in that section where the code would be.

```<code>long karatsuba(int num1, int num2, int &counter)
{
 if (num1 < 10 || num2 < 10)
 {
    counter++ // 1 operation
    return num1 * num2;
 }
 /* calculates the size of the number */
 ... 4 operations

 /* split the digit sequences about the middle */
 ... 4 operations

 /* 3 calls made to numbers approximately half the size */
 int z0 = karatsuba(..., ..., counter);
 int z1 = karatsuba(..., ..., counter);
 int z2 = karatsuba(..., ..., counter);

 return ... // 9 operations
}
-------------------------------------------------------------
int main()
{
 int counter = 0;
 cout << karatsuba(123, 456, counter) << " " << counter << endl;

 cout << endl;
 system("Pause");
 return 0;
}
</code>```

答:
The problem is this line:

cout << karatsuba(123, 456, counter) << " " << counter << endl;

Try instead

cout << karatsuba(123, 456, counter);
cout << " " << counter << endl;

the problem is cout, count is still 0 when it prints.

Title: C++ - Recursive counter

Body:
I am trying to create a counter. It counts each operation such as multiplication, addition, subtraction, division. Every time I try to cout the counter, it stays as zero.

Can anyone shed any light on what I am doing wrong?

A bulk of my code is missing so I can protect it from other classmates, however I have listed how many operations is in that section where the code would be.

long karatsuba(int num1, int num2, int &counter)
{
 if (num1 < 10 || num2 < 10)
 {
    counter++ // 1 operation
    return num1 * num2;
 }
 /* calculates the size of the number */
 ... 4 operations

 /* split the digit sequences about the middle */
 ... 4 operations

 /* 3 calls made to numbers approximately half the size */
 int z0 = karatsuba(..., ..., counter);
 int z1 = karatsuba(..., ..., counter);
 int z2 = karatsuba(..., ..., counter);

 return ... // 9 operations
}
-------------------------------------------------------------
int main()
{
 int counter = 0;
 cout << karatsuba(123, 456, counter) << " " << counter << endl;

 cout << endl;
 system("Pause");
 return 0;
}


问:
Rerendering a Pylons form with a querystring parameter after FormEncode validation fails
My question may be the same as this, but the suggested answer didn't seem to help (or I didn't understand it correctly): Pylons FormEncode @validate decorator pass parameters into re-render action

I have a simple form that takes a required querystring (id) value, uses that as a hidden form field value, and validates the posted data. The controller looks like this:

```<code>class NewNodeForm(formencode.Schema):
  parent_id = formencode.validators.Int(not_empty = True)
  child_name = formencode.validators.String(not_empty = True)

def newnode(self, id):
  c.parent_id = id
  return render('newnode.html')

@validate(schema=NewNodeForm(), form='newnode')
def createnode(self):
  parentId = self.form_result.get('parent_id')
  childName = self.form_result.get('child_name')
  nodeId = save_the_data(parentId, childName)
  return redirect_to(controller = 'node', action = 'view', id = nodeId)
</code>```

and the form is very basic:

```<code><form method="post" action="/node/createnode">
  <input type="text" name="child_name">
  <input type="hidden" value="${c.parent_id}" name="parent_id">
  <input name="submit" type="submit" value="Submit">
</form>
</code>```

Everything works fine if the validation passes, but if it fails, newnode can't be called because id isn't passed back. It throws TypeError: newnode() takes exactly 2 arguments (1 given). Simply defining as newnode(self, id = None) gets around this problem, but I can't do that as the id is required by the logic.

This seems so simple, but what am I missing?

答:
If you are using an id arg in your newnode my preference would be to use the same arg in it's related createnode function. Adapt your post url to use an id, and you wont need to hidden the parent_id because it is now part of the url.</p>

```<code><form method="post" action="/node/createnode/${request.urlvars['id']}">
  <input type="text" name="child_name">
  <input name="submit" type="submit" value="Submit">
</form>
</code>```

Body:
My question may be the same as this, but the suggested answer didn't seem to help (or I didn't understand it correctly): Pylons FormEncode @validate decorator pass parameters into re-render action

I have a simple form that takes a required querystring (id) value, uses that as a hidden form field value, and validates the posted data. The controller looks like this:

class NewNodeForm(formencode.Schema):
  parent_id = formencode.validators.Int(not_empty = True)
  child_name = formencode.validators.String(not_empty = True)

def newnode(self, id):
  c.parent_id = id
  return render('newnode.html')

@validate(schema=NewNodeForm(), form='newnode')
def createnode(self):
  parentId = self.form_result.get('parent_id')
  childName = self.form_result.get('child_name')
  nodeId = save_the_data(parentId, childName)
  return redirect_to(controller = 'node', action = 'view', id = nodeId)

and the form is very basic:

<form method="post" action="/node/createnode">
  <input type="text" name="child_name">
  <input type="hidden" value="${c.parent_id}" name="parent_id">
  <input name="submit" type="submit" value="Submit">
</form>

Everything works fine if the validation passes, but if it fails, newnode can't be called because id isn't passed back. It throws TypeError: newnode() takes exactly 2 arguments (1 given). Simply defining as newnode(self, id = None) gets around this problem, but I can't do that as the id is required by the logic.

This seems so simple, but what am I missing?

Body:
If you are using an id arg in your newnode my preference would be to use the same arg in it's related createnode function. Adapt your post url to use an id, and you wont need to hidden the parent_id because it is now part of the url.

<form method="post" action="/node/createnode/${request.urlvars['id']}">
  <input type="text" name="child_name">
  <input name="submit" type="submit" value="Submit">
</form>


问:
Converting a text file with math problems to a text file with the answers to those problems
I am currently trying to work on a code that takes input from a user asking them to open a file with math problems within it, and then outputs a file with the answers to those problems. I have looked all over for some kind of solution to this, but these are the closest I have gotten:

text file contents:

2 + 2

3 * 3

4.5 - 2.3

-8.8 + 1.2

2 ^ 4

8.9 / 2.3

5 % 3

-2 * -2

Attempt 1:

```<code>input_file_name = input("What file would you like to open? ")
output_file_name = input("What file would you like to write to? ")

with open(input_file_name,"r") as input_file:
    contents = input_file.readlines()
    num = "".join(contents)
    contents_length = len(num)

with open(output_file_name, "w") as output_file:
    while contents_length >= 0:
        num = num.replace("^","**") # change the ^ to ** so python can properly do the function
        contents_value = exec(num)

        contents_length = contents_length - 1

    output_file.write(str(contents_value))
</code>```

The text file I received would return "None"

Attempt 2:

```<code>input_file_name = input("What file would you like to open? ")
output_file_name = input("What file would you like to write to? ")

infile = open(input_file_name, "r")
outfile = open(output_file_name, "w")

lines = infile.readlines()

i = len(lines) - 1

while i >= 0:
    ans = eval(lines[i])
    outfile.write(str(ans))
    i = i - 1

infile.close()
outfile.close()
</code>```

And the text document had 423.86956521739130476-7.60000000000000052.294 in the file.

So, I'm not really sure what else to do. Any help will be greatly appreciated.

答:
For the sake of argument I want to demonstrate that you don't have to use eval at all for your problem! As PM 2Ring has warned, using eval or exec is a security hazard in case there's any chance that the string you're evaluating can be tampered with by malicious third parties. Many people dismiss this security risk, but if you read my favourite answer in the subject you can see a strikingly simple example to executing arbitrary programs outside python with a call to eval. So one should never use eval/exec on sources that are not 100% trusted and under control.

Coming back to your problem, your examples make it seem that the pattern is always val1 OP val2, i.e. two numbers (possibly negative, possibly floats) with an infix mathematical operator. This structure is so simple that you can (and I believe should) write your own parser for it. This serves as a demonstration that by explicitly handling inputs we expect in a safe way we can guarantee that our program breaks on invalid and malicious input.

Here's a function that returns the result for one line (one expression) of your input:

```<code>import operator

def evaluate(expr):
    '''Evaluate expressions of the form `val1 OP val2`; OP is in [+,-,/,*,%,^]'''
    ops = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.truediv,
        '%': operator.mod,
        '^': operator.pow,
        }
    # gather operators and put minus last so we can handle negative numbers right
    opskeys = list(ops)
    ind = opskeys.index('-')
    implemented_ops = opskeys[ind+1:] + opskeys[:ind+1]

    for opnow in implemented_ops:
        if opnow in expr:
            val1,op,val2 = expr.rpartition(opnow)
            # convert the numbers to floats, or ints in case they are integral
            val1,val2 = (int(val) if val.is_integer() else val
                         for val in map(float,[val1,val2]))
            break
    else:
        raise ValueError('Invalid input line "{}"!'.format(expr))

    return ops[op](val1,val2) # or round(...,digits) see PM 2Ring's answer
</code>```

The function takes a single line of input, finds the appropriate mathematical operator, splits the line using that character, then evaluates the result. It uses a dispatch dict to choose actual mathematical operators based on the characters; one upside is that we don't even have to convert the power operator. We convert integer inputs to integers, and leave the rest as floats.

The function handles subtraction last, this ensures that negative numbers don't mess up calculations with every other operator. This isn't entirely foolproof: in case there's an invalid line with something unexpected and negative numbers, we're probably going to get a ValueError from the first conversion of val1/val2 to float. It might also break when subtracting a number from a negative number, or similar corner cases. Further safeguards (such as catching exceptions coming from float()) could be added to the code; my point is to prove that you can very easily use a safe and controlled approach instead of eval.

An example run with your data (hat tip again to PM 2Ring) plus an intentionally invalid input line:

```<code>data = '''\
2 + 2
3 * 3
4.5 - 2.3
-8.8 + 1.2
2 ^ 4
8.9 / 2.3
5 % 3
-2 * -2
3 @ 4
'''.splitlines()

for line in data:
    print(evaluate(line))
</code>```

The corresponding output in an interactive shell:

4
9
2.2
-7.6000000000000005
16
3.8695652173913047
2
4
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "foo.py", line 26, in evaluate
    raise ValueError('Invalid input line "{}"!'.format(expr))
ValueError: Invalid input line "3 @ 4"!
```

Body:
I am currently trying to work on a code that takes input from a user asking them to open a file with math problems within it, and then outputs a file with the answers to those problems. I have looked all over for some kind of solution to this, but these are the closest I have gotten:

text file contents:

2 + 2

3 * 3

4.5 - 2.3

-8.8 + 1.2

2 ^ 4

8.9 / 2.3

5 % 3

-2 * -2

Attempt 1:

input_file_name = input("What file would you like to open? ")
output_file_name = input("What file would you like to write to? ")

with open(input_file_name,"r") as input_file:
    contents = input_file.readlines()
    num = "".join(contents)
    contents_length = len(num)

with open(output_file_name, "w") as output_file:
    while contents_length >= 0:
        num = num.replace("^","**") # change the ^ to ** so python can properly do the function
        contents_value = exec(num)

        contents_length = contents_length - 1

    output_file.write(str(contents_value))

The text file I received would return "None"

Attempt 2:

input_file_name = input("What file would you like to open? ")
output_file_name = input("What file would you like to write to? ")

infile = open(input_file_name, "r")
outfile = open(output_file_name, "w")

lines = infile.readlines()

i = len(lines) - 1

while i >= 0:
    ans = eval(lines[i])
    outfile.write(str(ans))
    i = i - 1

infile.close()
outfile.close()

And the text document had 423.86956521739130476-7.60000000000000052.294 in the file.

So, I'm not really sure what else to do. Any help will be greatly appreciated.

Body:
For the sake of argument I want to demonstrate that you don't have to use eval at all for your problem! As PM 2Ring has warned, using eval or exec is a security hazard in case there's any chance that the string you're evaluating can be tampered with by malicious third parties. Many people dismiss this security risk, but if you read my favourite answer in the subject you can see a strikingly simple example to executing arbitrary programs outside python with a call to eval. So one should never use eval/exec on sources that are not 100% trusted and under control.

Coming back to your problem, your examples make it seem that the pattern is always val1 OP val2, i.e. two numbers (possibly negative, possibly floats) with an infix mathematical operator. This structure is so simple that you can (and I believe should) write your own parser for it. This serves as a demonstration that by explicitly handling inputs we expect in a safe way we can guarantee that our program breaks on invalid and malicious input.

Here's a function that returns the result for one line (one expression) of your input:

import operator

def evaluate(expr):
    '''Evaluate expressions of the form `val1 OP val2`; OP is in [+,-,/,*,%,^]'''
    ops = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.truediv,
        '%': operator.mod,
        '^': operator.pow,
        }
    # gather operators and put minus last so we can handle negative numbers right
    opskeys = list(ops)
    ind = opskeys.index('-')
    implemented_ops = opskeys[ind+1:] + opskeys[:ind+1]

    for opnow in implemented_ops:
        if opnow in expr:
            val1,op,val2 = expr.rpartition(opnow)
            # convert the numbers to floats, or ints in case they are integral
            val1,val2 = (int(val) if val.is_integer() else val
                         for val in map(float,[val1,val2]))
            break
    else:
        raise ValueError('Invalid input line "{}"!'.format(expr))

    return ops[op](val1,val2) # or round(...,digits) see PM 2Ring's answer

The function takes a single line of input, finds the appropriate mathematical operator, splits the line using that character, then evaluates the result. It uses a dispatch dict to choose actual mathematical operators based on the characters; one upside is that we don't even have to convert the power operator. We convert integer inputs to integers, and leave the rest as floats.

The function handles subtraction last, this ensures that negative numbers don't mess up calculations with every other operator. This isn't entirely foolproof: in case there's an invalid line with something unexpected and negative numbers, we're probably going to get a ValueError from the first conversion of val1/val2 to float. It might also break when subtracting a number from a negative number, or similar corner cases. Further safeguards (such as catching exceptions coming from float()) could be added to the code; my point is to prove that you can very easily use a safe and controlled approach instead of eval.

An example run with your data (hat tip again to PM 2Ring) plus an intentionally invalid input line:

data = '''\
2 + 2
3 * 3
4.5 - 2.3
-8.8 + 1.2
2 ^ 4
8.9 / 2.3
5 % 3
-2 * -2
3 @ 4
'''.splitlines()

for line in data:
    print(evaluate(line))

The corresponding output in an interactive shell:

4
9
2.2
-7.6000000000000005
16
3.8695652173913047
2
4
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "foo.py", line 26, in evaluate
    raise ValueError('Invalid input line "{}"!'.format(expr))
ValueError: Invalid input line "3 @ 4"!


问:
How to make symfony Controller variable a global?
```<code>public indexFunction(){
  $var = 'Apple';
  //set $var global
}
</code>```

So that $var can be accessed in base template.

答:
Dynamic:

In the bundle path (Example: src/AppBundle) add a file called "YourNameTwigExtension.php". This file will be a class (YourNameTwigExtension) that extends "\Twig_Extension" class and implements the interface "\Twig_Extension_GlobalsInterface". Inside the "YourNameTwigExtension" class implement the getGlobals() method. Example:

```<code>//....
class YourNameTwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsInterface {
    //...

    public function getGlobals() {
        $data = array();

        $data['user'] = $this->session->get('user');
        $data['menu'] = $this->session->get('menu');
        $data['actions'] = $this->session->get('actions');
        $data['view'] = $this->session->get('view');

        return $data;
    }
}
</code>```

In TWIG you will use: {{ user }}, {{ menu }}, {{ actions }}, etc...

Warning: Add in app/config/services.yml:

```<code> twig.extension.yourname_twig_extension:
        class: YourBundle\YourNameTwigExtension
        tags:
            - { name: twig.extension }
</code>```

Static:

If you need to use the static variables, in app/config/parameters.yml:

```<code>twig:
    globals:
        portal_name: 'Portal'
        portal_img_logo: logo.png
        portal_favicon: favicon.ico
        logowidth: 350px
</code>```

Symfony Doc: How to Inject Variables into all Templates (i.e. global Variables)

Sorry my English.. Good Work!

Body:
public indexFunction(){
  $var = 'Apple';
  //set $var global
}

So that $var can be accessed in base template.

Body:
Dynamic:

In the bundle path (Example: src/AppBundle) add a file called "YourNameTwigExtension.php". This file will be a class (YourNameTwigExtension) that extends "\Twig_Extension" class and implements the interface "\Twig_Extension_GlobalsInterface". Inside the "YourNameTwigExtension" class implement the getGlobals() method. Example:

//....
class YourNameTwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsInterface {
    //...

    public function getGlobals() {
        $data = array();

        $data['user'] = $this->session->get('user');
        $data['menu'] = $this->session->get('menu');
        $data['actions'] = $this->session->get('actions');
        $data['view'] = $this->session->get('view');

        return $data;
    }
}

In TWIG you will use: {{ user }}, {{ menu }}, {{ actions }}, etc...

Warning: Add in app/config/services.yml:

 twig.extension.yourname_twig_extension:
        class: YourBundle\YourNameTwigExtension
        tags:
            - { name: twig.extension }

Static:

If you need to use the static variables, in app/config/parameters.yml:

twig:
    globals:
        portal_name: 'Portal'
        portal_img_logo: logo.png
        portal_favicon: favicon.ico
        logowidth: 350px

Symfony Doc: How to Inject Variables into all Templates (i.e. global Variables)

Sorry my English.. Good Work!


问:
MySql icon missing from System Preferences panel
I'm trying to restart mysql (a whole different question), MySql is definitely installed (version 14.14), and from what i gather i SHOULD be seeing an icon for it toward the bottom of my System Preferences panel, but it's not there. Did something get botched during the install? Thanks for the help, beginner here! hah</p>

答: I usually use mysql.server start to start my MySQL server. Never heard of a GUI or icon in the system preferences?


问:
500 Internal server error in wp admin ,at update & plugin (Wordpress)
I'm having Internal server error in some sessions(parts) after I login in wp dashboard.

Issues are in wp-admin/plugins.php and some few other places where is relating with any plugins.
I have checked .htaccess, memory limit to my server and in wp file is ok, I have deactivated all the plugins, changed themes, updated WordPress and still have the same issue.

I have check the error log and this is what it shows:

[Thu Jun 09 12:22:25 2016] [error] [client 217.73.141.38] Premature end of script headers: update-core.php, referer: http://www.salus.al/wp-admin/

[Thu Jun 09 12:22:29 2016] [warn] [client 217.73.141.38] (104)Connection reset by peer: mod_fcgid: error reading data from FastCGI server, referer: http://www.salus.al/wp-admin/

[Thu Jun 09 12:22:29 2016] [error] [client 217.73.141.38] Premature end of script headers: plugins.php, referer: http://www.salus.al/wp-admin/

[Thu Jun 09 12:22:32 2016] [warn] [client 217.73.141.38] (104)Connection reset by peer: mod_fcgid: error reading data from FastCGI server, referer: http://www.salus.al/wp-admin/

答: Remove or rename your plugins folder and see if the problem goes away. If it does, then add each plugin one at a time to see which one produces the error. Perhaps clear all cache, cookies, etc as well.</p>


问:
QML ScrollBar/ListView sensitivity for mouse wheel. How to adjust
There is QML control ScrollBar , and mouse wheel scrolls the list fast, I need to perform this slower. Which properties can be used for that?

Qt 5.9

this is from an examples (rssnews sample project from Qt kit):

```<code>...
ListView {
    id: categories
    property int itemWidth: 190

    width: isPortrait ? parent.width : itemWidth
    height: isPortrait ? itemWidth : parent.height
    orientation: isPortrait ? ListView.Horizontal : ListView.Vertical
    anchors.top: parent.top
    model: rssFeeds
    delegate: CategoryDelegate { itemSize: categories.itemWidth }
    spacing: 3
}

ScrollBar {
    id: listScrollBar

    orientation: isPortrait ? Qt.Horizontal : Qt.Vertical
    height: isPortrait ? 8 : categories.height;
    width: isPortrait ? categories.width : 8
    scrollArea: categories;

    anchors.right: categories.right
}
...
</code>```

I see this for ScrollView:

```<code>/*! \internal */
property alias __wheelAreaScrollSpeed: wheelArea.scrollSpeed
</code>```

But can't find scrollSpeed property for my case...

答:
I don't think the ScrollBar is what makes the things go wild. It is the Flickable that is the base class of the ListView.

There you have the property: maximumFlickVelocity which is in pixel / second.

Try to set this to an appropriate value.

This will also affect the flicking behavior!

If it is the ScrollBar you might try the property: stepSize - set it to something smaller than 0.1. I don't have Qt5.9 so I can't try it. I don't belive this is the reason though.

In the worst case, layer a MouseArea ontop of the whole thing, that does not accept any buttons, but handles onWheel:

```<code>MouseArea {
    anchors.fill: parent
    acceptedButtons: Qt.NoButton
    //onWheel: manage the scrolling yourself, here.
}
</code>```

Body:
There is QML control ScrollBar , and mouse wheel scrolls the list fast, I need to perform this slower. Which properties can be used for that?

Qt 5.9

this is from an examples (rssnews sample project from Qt kit):

...
ListView {
    id: categories
    property int itemWidth: 190

    width: isPortrait ? parent.width : itemWidth
    height: isPortrait ? itemWidth : parent.height
    orientation: isPortrait ? ListView.Horizontal : ListView.Vertical
    anchors.top: parent.top
    model: rssFeeds
    delegate: CategoryDelegate { itemSize: categories.itemWidth }
    spacing: 3
}

ScrollBar {
    id: listScrollBar

    orientation: isPortrait ? Qt.Horizontal : Qt.Vertical
    height: isPortrait ? 8 : categories.height;
    width: isPortrait ? categories.width : 8
    scrollArea: categories;

    anchors.right: categories.right
}
...

I see this for ScrollView:

/*! \internal */
property alias __wheelAreaScrollSpeed: wheelArea.scrollSpeed

But can't find scrollSpeed property for my case...

Body:
I don't think the ScrollBar is what makes the things go wild. It is the Flickable that is the base class of the ListView.

There you have the property: maximumFlickVelocity which is in pixel / second.

Try to set this to an appropriate value.

This will also affect the flicking behavior!

If it is the ScrollBar you might try the property: stepSize - set it to something smaller than 0.1. I don't have Qt5.9 so I can't try it. I don't belive this is the reason though.

In the worst case, layer a MouseArea ontop of the whole thing, that does not accept any buttons, but handles onWheel:

MouseArea {
    anchors.fill: parent
    acceptedButtons: Qt.NoButton
    //onWheel: manage the scrolling yourself, here.
}


问:
Why does tf.train.batch add an extra dimension to output in TensorFlow?
In TensorFlow, say we have training data xs in numpy NHCW format. I want to sample batches from xs in Tensorflow, I did

```<code>xs = np.reshape(range(32), [4,2,2,2])
tensor_list = [tf.convert_to_tensors(x) for x in xs]
#x_tensor = tf.convert_to_tensors(xs) # tried this version too
x_batch = tf.train.shuffle_batch(tensor_list, batch_size=3, capacity=50, min_after_dequeue=10)
</code>```

Instead of sampling from tensor_list, this code returns a list whose length is the same of the number of data points (4 in this case), and each list element is a tensor where the first dimension is batch_size (3 in this case). Personally the intuitive outcome would be x_batch is a 4 dimensional tensor and the value of the first dimension is batch_size, and the contents are randomly sampled. Then each time we call sess.run(x_batch) we have a different batch.

Please let me know where I did wrong.

答:
Haven't figured this out, but found a different solution as below.

```<code>xs = np.reshape(range(32), [4,2,2,2])
x_tensor = tf.convert_to_tensor(xs)
dataset = tf.data.Dataset.from_tensor_slices(x_tensor)
dataset = dataset.batch(2)
dataset = dataset.shuffle(buffer_size=10000)
iterator = dataset.make_initializable_iterator()
sess.run(iterator.initializer)

while True:
  try:
    next_element = iterator.get_next()
  except tf.errors.OutOfRangeError:
    print("End of dataset")  # ==> "End of dataset"
</code>```

Then this will output a random batch of size 2 each time iterator.get_next() is called.

Body:
In TensorFlow, say we have training data xs in numpy NHCW format. I want to sample batches from xs in Tensorflow, I did

xs = np.reshape(range(32), [4,2,2,2])
tensor_list = [tf.convert_to_tensors(x) for x in xs]
#x_tensor = tf.convert_to_tensors(xs) # tried this version too
x_batch = tf.train.shuffle_batch(tensor_list, batch_size=3, capacity=50, min_after_dequeue=10)

Instead of sampling from tensor_list, this code returns a list whose length is the same of the number of data points (4 in this case), and each list element is a tensor where the first dimension is batch_size (3 in this case). Personally the intuitive outcome would be x_batch is a 4 dimensional tensor and the value of the first dimension is batch_size, and the contents are randomly sampled. Then each time we call sess.run(x_batch) we have a different batch.

Please let me know where I did wrong.

Body:
Haven't figured this out, but found a different solution as below.

xs = np.reshape(range(32), [4,2,2,2])
x_tensor = tf.convert_to_tensor(xs)
dataset = tf.data.Dataset.from_tensor_slices(x_tensor)
dataset = dataset.batch(2)
dataset = dataset.shuffle(buffer_size=10000)
iterator = dataset.make_initializable_iterator()
sess.run(iterator.initializer)

while True:
  try:
    next_element = iterator.get_next()
  except tf.errors.OutOfRangeError:
    print("End of dataset")  # ==> "End of dataset"

Then this will output a random batch of size 2 each time iterator.get_next() is called.