问:
How to cancel a promise with $q in angular js
I have a service below. I will call this service every time when I open a model and when I close the model and then open another one the previous values are getting reflected and in this case I want to cancel the promise every time I close the model.

I have tried the following code,

Model closing.js

```<code>$scope.closeButton = function() {
    DetailDataSvc.storeDefer().resolve()
}
</code>```

My Service, (DetailDataSvc)

```<code>self.storeDefer = function() {
    return self.deferReturn;
};

self.getDetailReportData = function(postData, functionName) {
    var promises = {};

    var d = $q.defer(),
        metricDataType;
    self.deferReturn = $q.defer();
    promises = {
        detailReport: metricDataType,
        recommendedMetrics: DataSvc.getData(_logPrefix + functionName, recommendedMetricUrl),
        metricInfo: DataSvc.getData(_logPrefix + functionName, metricInfoUrl)
    };
    $q.all(promises).then(function(res) {
        $log.debug(_logPrefix + 'getDetailReportData(). Called from %s. $q.all Response (raw): ', functionName, res);
        else {
            if (response && !_.isEmpty(_.get(response, 'largeCard.chartData.dataValues.rows')) && response.overlayEnabled) {
                self.getMetricOverLay(pdata, functionName).then(function(overlayData) {
                    response.largeCard.chartData.overlay = overlayData;
                    d.resolve(response);
                }, function(msg, code) {
                    d.reject(msg);
                    $log.error(_logPrefix + 'getDetailReportData().   Error code: %s.  Error: ', code, msg);
                });
            } else {
                d.resolve(response);
            }
        }

    }, function(msg, code) {
        d.reject(msg);
        $log.error(_logPrefix + 'getDetailReportData().   Error code: %s.  Error: ', code, msg);
    });

    return d.promise;

};
</code>```

Can anyone please help me whether the process I followed is the right one.

答:
What you have attempted could be made to work but it's best fixed by racing the promise returned by $q.all() against a rejectable Deferred (ie. a Deferred, of which a reference is kept to its reject method), thus avoiding the deferred anti-pattern.

```<code>self.getDetailReportData = function(postData, functionName) {
    var metricDataType = ......; // ???
    var d = $q.defer();

    // cancel previous
    if(self.cancelDetailReport) {
        self.cancelDetailReport(new Error('previous getDetailReportData() cancelled'));
    }
    // keep a reference to the deferred's reject method for next time round.
    self.cancelDetailReport = d.reject;

    var promises = {
        'detailReport': metricDataType,
        'recommendedMetrics': DataSvc.getData(_logPrefix + functionName, recommendedMetricUrl),
        'metricInfo': DataSvc.getData(_logPrefix + functionName, metricInfoUrl)
    };

    // Race aggregated `promises` against `d.promise`, thus providing the required cancellation effect.
    return $q.race([$q.all(promises), d.promise])
    .then(function(response) {
        // arrive here only if all promises resolve and d.reject() has not been called.
        $log.debug(_logPrefix + 'getDetailReportData(). Called from %s. $q.all Response (raw): ', functionName, response);
        if (response && !_.isEmpty(_.get(response, 'largeCard.chartData.dataValues.rows')) && response.overlayEnabled) {
            return self.getMetricOverLay(pdata, functionName)
            .then(function(overlayData) {
                response.largeCard.chartData.overlay = overlayData;
                return response;
            });
        } else {
            return response;
        }
    })
    .catch(function(msg, code) { // signature?
        // all error cases including cancellation end up here.
        var message = _logPrefix + `getDetailReportData().   Error: (${code}): ${msg}`; // or similar
        $log.error(message);
        throw new Error(message); // see https://stackoverflow.com/a/42250798/3478010
    });
};
</code>```

Notes:

$q.race() is transparent to whichever promise wins the race, and opaque to the other. So, if the d is rejected before the promise returned by $q.all() settles, then d will win out; response handling will not happen and d's rejection will fall through to the .catch() clause. Alternatively, if the promise returned by $q.all(promises) wins out then flow will follow that promise's success path (ie response handling) or possibly its error path (which will drop through to the .catch() clause).

Not too sure about the signature of the .catch() callback. You would normally expect it to accept a single error argument.

Body:
I have a service below. I will call this service every time when I open a model and when I close the model and then open another one the previous values are getting reflected and in this case I want to cancel the promise every time I close the model.

I have tried the following code,

Model closing.js

$scope.closeButton = function() {
    DetailDataSvc.storeDefer().resolve()
}

My Service, (DetailDataSvc)

self.storeDefer = function() {
    return self.deferReturn;
};

self.getDetailReportData = function(postData, functionName) {
    var promises = {};

    var d = $q.defer(),
        metricDataType;
    self.deferReturn = $q.defer();
    promises = {
        detailReport: metricDataType,
        recommendedMetrics: DataSvc.getData(_logPrefix + functionName, recommendedMetricUrl),
        metricInfo: DataSvc.getData(_logPrefix + functionName, metricInfoUrl)
    };
    $q.all(promises).then(function(res) {
        $log.debug(_logPrefix + 'getDetailReportData(). Called from %s. $q.all Response (raw): ', functionName, res);
        else {
            if (response && !_.isEmpty(_.get(response, 'largeCard.chartData.dataValues.rows')) && response.overlayEnabled) {
                self.getMetricOverLay(pdata, functionName).then(function(overlayData) {
                    response.largeCard.chartData.overlay = overlayData;
                    d.resolve(response);
                }, function(msg, code) {
                    d.reject(msg);
                    $log.error(_logPrefix + 'getDetailReportData().   Error code: %s.  Error: ', code, msg);
                });
            } else {
                d.resolve(response);
            }
        }

    }, function(msg, code) {
        d.reject(msg);
        $log.error(_logPrefix + 'getDetailReportData().   Error code: %s.  Error: ', code, msg);
    });

    return d.promise;

};

Can anyone please help me whether the process I followed is the right one.

Body:
What you have attempted could be made to work but it's best fixed by racing the promise returned by $q.all() against a rejectable Deferred (ie. a Deferred, of which a reference is kept to its reject method), thus avoiding the deferred anti-pattern.

self.getDetailReportData = function(postData, functionName) {
    var metricDataType = ......; // ???
    var d = $q.defer();

    // cancel previous
    if(self.cancelDetailReport) {
        self.cancelDetailReport(new Error('previous getDetailReportData() cancelled'));
    }
    // keep a reference to the deferred's reject method for next time round.
    self.cancelDetailReport = d.reject;

    var promises = {
        'detailReport': metricDataType,
        'recommendedMetrics': DataSvc.getData(_logPrefix + functionName, recommendedMetricUrl),
        'metricInfo': DataSvc.getData(_logPrefix + functionName, metricInfoUrl)
    };

    // Race aggregated `promises` against `d.promise`, thus providing the required cancellation effect.
    return $q.race([$q.all(promises), d.promise])
    .then(function(response) {
        // arrive here only if all promises resolve and d.reject() has not been called.
        $log.debug(_logPrefix + 'getDetailReportData(). Called from %s. $q.all Response (raw): ', functionName, response);
        if (response && !_.isEmpty(_.get(response, 'largeCard.chartData.dataValues.rows')) && response.overlayEnabled) {
            return self.getMetricOverLay(pdata, functionName)
            .then(function(overlayData) {
                response.largeCard.chartData.overlay = overlayData;
                return response;
            });
        } else {
            return response;
        }
    })
    .catch(function(msg, code) { // signature?
        // all error cases including cancellation end up here.
        var message = _logPrefix + `getDetailReportData().   Error: (${code}): ${msg}`; // or similar
        $log.error(message);
        throw new Error(message); // see https://stackoverflow.com/a/42250798/3478010
    });
};

Notes:

$q.race() is transparent to whichever promise wins the race, and opaque to the other. So, if the d is rejected before the promise returned by $q.all() settles, then d will win out; response handling will not happen and d's rejection will fall through to the .catch() clause. Alternatively, if the promise returned by $q.all(promises) wins out then flow will follow that promise's success path (ie response handling) or possibly its error path (which will drop through to the .catch() clause).

Not too sure about the signature of the .catch() callback. You would normally expect it to accept a single error argument.


来源: stackexchange

问:
Group a Ruby Array of Dates by Month and Year into a Hash
Let's say I had a Ruby Array of Dates like:

```<code>2011-01-20
2011-01-23
2011-02-01
2011-02-15
2011-03-21
</code>```

What would be an easy and Ruby-esque way of creating a Hash that groups the Date elements by year and then month, like:

```<code>{
    2011 => {
        1   => [2011-01-20, 2011-01-23],
        2   => [2011-02-01, 2011-02-15],
        3  => [2011-03-21],
    }
}
</code>```

I can do this by iterating over everything and extracting years, months and so on, then comining them.

Ruby offers so many methods and blocks for Arrays and Hashes, there must be an easier way?

ContentLicense: CC BY-SA 3.0

Body:
Let's say I had a Ruby Array of Dates like:

2011-01-20
2011-01-23
2011-02-01
2011-02-15
2011-03-21

What would be an easy and Ruby-esque way of creating a Hash that groups the Date elements by year and then month, like:

{
    2011 => {
        1   => [2011-01-20, 2011-01-23],
        2   => [2011-02-01, 2011-02-15],
        3  => [2011-03-21],
    }
}

I can do this by iterating over everything and extracting years, months and so on, then comining them.

Ruby offers so many methods and blocks for Arrays and Hashes, there must be an easier way?

Body:
dates = %w(
2011-01-20
2011-01-23
2011-02-01
2011-02-15
2011-03-21
)
hash = {}
dates.each do |date|
   year, month = date.strftime('%Y,%B').split(',')
   hash[year] ||= {}
   hash[year][month] = hash[year][month].to_a << date
end


问:
How to separate each elements of a nested list and convert the list to the list of tuples?
I have a nested list like below:

```<code>Zeros = [[1], [2], [3, 4], [5, 6]]

</code>```

How can I separate each element and make a list of tuples, like below:

```<code>Modified_zeros = [(1), (2), (3), (4), (5), (6)]

</code>```

Thanks

答:
for nested list at multiple level

```<code>Zeros = [[1], [2], [3, 4], [5, 6,[1,2,3,4]]]

def fun(l):
    res=[]
    if isinstance(l,list):
        for i in l:
            res.extend(fun(i))
    elif isinstance(l,int):
        res.append((l,))
    return res

print(fun(Zeros))
</code>```

output

```<code>[(1,), (2,), (3,), (4,), (5,), (6,), (1,), (2,), (3,), (4,)]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a nested list like below:

Zeros = [[1], [2], [3, 4], [5, 6]]

How can I separate each element and make a list of tuples, like below:

Modified_zeros = [(1), (2), (3), (4), (5), (6)]

Thanks

Body:
for nested list at multiple level

Zeros = [[1], [2], [3, 4], [5, 6,[1,2,3,4]]]

def fun(l):
    res=[]
    if isinstance(l,list):
        for i in l:
            res.extend(fun(i))
    elif isinstance(l,int):
        res.append((l,))
    return res

print(fun(Zeros))

output

[(1,), (2,), (3,), (4,), (5,), (6,), (1,), (2,), (3,), (4,)]


问:
Modify plot axis so the order of its tick labels and their respective points change accordingly - without modifying the data itself
I want to reorder x-axis tick labels such that the data also changes appropriately.

Example

y = [5,8,9,10]
x = ['a', 'b', 'c', 'd']
plt.plot(y, x)

```

<p><img src="https://i.stack.imgur.com/5a6cg.png" alt="Original plot"></p>

<p>What I want the plot to look like by modifying the location of axis ticks.
<img src="https://i.stack.imgur.com/zqKUc.png" alt="Intended image"></p>

<p>Please note that I don't want to achieve this by modifying the order of my data</p>

<p><strong>My Try</strong></p>

```# attempt 1
fig, ax =plt.subplots()
plt.plot(y,x)
ax.set_xticklabels(['b', 'c', 'a', 'd'])
# this just overwrites the labels, not what we intended

# attempt2
fig, ax =plt.subplots()
plt.plot(y,x)
locs, labels = plt.xticks()
plt.xticks((1,2,0,3)); # This is essentially showing the location
# of the labels to dsiplay irrespective of the order of the tuple.

```

Edit:
Based on comments here are some further clarifications.

Let's say the first point (a,5) in fig 1. If I changed my x-axis definition such that a is now defined at the third position, then it gets reflected in the plot as well, which means, 5 on y-axis moves with a as shown in fig-2. One way to achieve this would be to re-order the data. However, I would like to see if it is possible to achieve it somehow by changing axis locations. To summarize, the data should be plotted based on how we define our custom axis without re-ordering the original data.

Edit2:
Based on the discussion in the comments it's not possible to do it by just modifying axis labels. Any approach would involve modifying the data. This was an oversimplification of the original problem I was facing. Finally, using dictionary-based labels in a pandas data frame helped me to sort the axis values in a specific order while also making sure that their respective values change accordingly.

答:
Toggling between two different orders of the x axis categories could look as follows,

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

x = ['a', 'b', 'c', 'd']
y = [5,8,9,10]

order1 = ['a', 'b', 'c', 'd']
order2 = ['b', 'c', 'a', 'd']

fig, ax = plt.subplots()
line, = ax.plot(x, y, marker="o")

def toggle(order):
    _, ind1 = np.unique(x, return_index=True)
    _, inv2 = np.unique(order, return_inverse=True)
    y_new = np.array(y)[ind1][inv2]

    line.set_ydata(y_new)
    line.axes.set_xticks(range(len(order)))
    line.axes.set_xticklabels(order)
    fig.canvas.draw_idle()

curr = [0]
orders = [order1, order2]
def onclick(evt):
    curr[0] = (curr[0] + 1) % 2
    toggle(orders[curr[0]])

fig.canvas.mpl_connect("button_press_event", onclick)

plt.show()
</code>```

Click anywhere on the plot to toggle between order1 and order2.

Body:
I want to reorder x-axis tick labels such that the data also changes appropriately.

Example

y = [5,8,9,10]
x = ['a', 'b', 'c', 'd']
plt.plot(y, x)

What I want the plot to look like by modifying the location of axis ticks.

Please note that I don't want to achieve this by modifying the order of my data

My Try

# attempt 1
fig, ax =plt.subplots()
plt.plot(y,x)
ax.set_xticklabels(['b', 'c', 'a', 'd'])
# this just overwrites the labels, not what we intended

# attempt2
fig, ax =plt.subplots()
plt.plot(y,x)
locs, labels = plt.xticks()
plt.xticks((1,2,0,3)); # This is essentially showing the location
# of the labels to dsiplay irrespective of the order of the tuple.

Edit:
Based on comments here are some further clarifications.

Let's say the first point (a,5) in fig 1. If I changed my x-axis definition such that a is now defined at the third position, then it gets reflected in the plot as well, which means, 5 on y-axis moves with a as shown in fig-2. One way to achieve this would be to re-order the data. However, I would like to see if it is possible to achieve it somehow by changing axis locations. To summarize, the data should be plotted based on how we define our custom axis without re-ordering the original data.

Edit2:
Based on the discussion in the comments it's not possible to do it by just modifying axis labels. Any approach would involve modifying the data. This was an oversimplification of the original problem I was facing. Finally, using dictionary-based labels in a pandas data frame helped me to sort the axis values in a specific order while also making sure that their respective values change accordingly.

Body:
Toggling between two different orders of the x axis categories could look as follows,

import numpy as np
import matplotlib.pyplot as plt

x = ['a', 'b', 'c', 'd']
y = [5,8,9,10]

order1 = ['a', 'b', 'c', 'd']
order2 = ['b', 'c', 'a', 'd']

fig, ax = plt.subplots()
line, = ax.plot(x, y, marker="o")

def toggle(order):
    _, ind1 = np.unique(x, return_index=True)
    _, inv2 = np.unique(order, return_inverse=True)
    y_new = np.array(y)[ind1][inv2]

    line.set_ydata(y_new)
    line.axes.set_xticks(range(len(order)))
    line.axes.set_xticklabels(order)
    fig.canvas.draw_idle()

curr = [0]
orders = [order1, order2]
def onclick(evt):
    curr[0] = (curr[0] + 1) % 2
    toggle(orders[curr[0]])

fig.canvas.mpl_connect("button_press_event", onclick)

plt.show()

Click anywhere on the plot to toggle between order1 and order2.


问:
NLP - negative sampling - how to draw negative samples from noise distribution?
From my understanding, negative sampling randomly samples K negative samples from a noise distribution, P(w). The noise distribution is basically the frequency distribution + some modification on words. Typically we choose K = 5 ~ 20 negative samples.

P(w) = Uw(w)^(3/4) / normalization_factor

And I've seen these two same equations that are represented in two different notations:

Three questions:

What is the meaning of the blue box? What is the significance of j and i?

The second equation does not seem to show anything that "randomly draws" words from the noise distribution. What is the meaning of k in red box?

How do you choose noise samples from the noise distribution?

Let's say that the normalized noise distribution looks as the following dictionary:

dist = {'apple': 0.0023, 'bee': 0.004, 'desk':0.032', 'chair': 0.032 ...}

How do you "randomly draw" K noise samples from dist?

答:
I figured this out and wrote a tutorial article about negative sampling.

The blue box means that u_j comes from the noise distribution P_n(w).

The blue box incorporates the "randomly draws" aspect of negative sampling. u_j is the i-th negative sample from the noise distribution, and also at the same time, j-th word vector in the output weight matrix.

You use something like np.random.choice()

The original cost function given in the original Word2Vec paper is actually quite confusing in terms of notations. A clearer form of cost function would be:

where c_pos is the word vector for positive word, and h is the hidden layer, and is equivalent to the word vector of the input word w. c_neg is the word vector of randomly drawn negative words, and W_neg is the word vector of all K negative words.

Noise distribution is normalized frequency distribution of words raised to the power of α. Mathematically, it can be expressed as:

A distribution of words based on how many times each word appeared in a corpus is called unigram distribution, and denoted as U(w). Z is a normalization factor, and α is a hyper-parameter that is typically α=3/4.

Raising the distribution to the power of α has an effect of smoothing out the distribution:

It attempts to combat the imbalance between common words and rare words by decreasing the probability of drawing common words, and increasing the probability drawing rare words.

Negative samples are randomly drawn from the noise distribution:

```<code>import numpy as np

unig_dist  = {'apple': 0.023, 'bee': 0.12, 'desk': 0.34, 'chair': 0.517}

sum(unig_dist.values())
>>> 1.0

alpha      = 3 / 4

noise_dist = {key: val ** alpha for key, val in unig_dist.items()}
Z = sum(noise_dist.values())
noise_dist_normalized = {key: val / Z for key, val in noise_dist.items()}
noise_dist_normalized
>>> {'apple': 0.044813853132981724,
 'bee': 0.15470428538870049,
 'desk': 0.33785130228003507,
 'chair': 0.4626305591982827}
</code>```

Initially, chair was the most common word and had the probability of being drawn 0.517. After the unigram distribution U(w) was raised to the power of 3/4, it has the probability of 0.463.

On the other hand, apple was the least common word of probability 0.023, but after transformation it has the probability of 0.045. The imbalance between the most common word (chair) and the least common word (apple) was mitigated.

Body:
I figured this out and wrote a tutorial article about negative sampling.

The blue box means that u_j comes from the noise distribution P_n(w).

The blue box incorporates the "randomly draws" aspect of negative sampling. u_j is the i-th negative sample from the noise distribution, and also at the same time, j-th word vector in the output weight matrix.

You use something like np.random.choice()

The original cost function given in the original Word2Vec paper is actually quite confusing in terms of notations. A clearer form of cost function would be:

where c_pos is the word vector for positive word, and h is the hidden layer, and is equivalent to the word vector of the input word w. c_neg is the word vector of randomly drawn negative words, and W_neg is the word vector of all K negative words.

Noise distribution is normalized frequency distribution of words raised to the power of α. Mathematically, it can be expressed as:

A distribution of words based on how many times each word appeared in a corpus is called unigram distribution, and denoted as U(w). Z is a normalization factor, and α is a hyper-parameter that is typically α=3/4.

Raising the distribution to the power of α has an effect of smoothing out the distribution:

It attempts to combat the imbalance between common words and rare words by decreasing the probability of drawing common words, and increasing the probability drawing rare words.

Negative samples are randomly drawn from the noise distribution:

import numpy as np

unig_dist  = {'apple': 0.023, 'bee': 0.12, 'desk': 0.34, 'chair': 0.517}

sum(unig_dist.values())
>>> 1.0

alpha      = 3 / 4

noise_dist = {key: val ** alpha for key, val in unig_dist.items()}
Z = sum(noise_dist.values())
noise_dist_normalized = {key: val / Z for key, val in noise_dist.items()}
noise_dist_normalized
>>> {'apple': 0.044813853132981724,
 'bee': 0.15470428538870049,
 'desk': 0.33785130228003507,
 'chair': 0.4626305591982827}

Initially, chair was the most common word and had the probability of being drawn 0.517. After the unigram distribution U(w) was raised to the power of 3/4, it has the probability of 0.463.

On the other hand, apple was the least common word of probability 0.023, but after transformation it has the probability of 0.045. The imbalance between the most common word (chair) and the least common word (apple) was mitigated.


问:
How to define manual colors for text on individual facets?
Trying to define manual colors for text on individual facets created by ggplot. But the code is assigning random colors.

I have included the code I tried to get the colors right.

library(ggplot2)

p <- ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  facet_grid(. ~ cyl) +
  theme(panel.spacing = unit(1, "lines"))

dat_text <- data.frame(
  label = c("4 cylinders", "6 cylinders", "8 cylinders"),
  cyl   = c(4, 6, 8),
  cl = c("red", "blue", "black"),
  x     = c(20, 27.5, 25),
  y     = c(4, 4, 4.5)
)

p + geom_text(
  data    = dat_text,
  mapping = aes(x = x, y = y, label = label, colour= cl)
)

```

The code is working except it is giving random colors instead of assigned colors.

答:
Alternatively you can plot them all on the same plot, and just change the colour of the points.

```<code>ggplot(data=mtcars) +
  geom_point(data = mt, aes(x = mpg, y = wt, color = factor(mt$cyl))) +
  scale_color_manual(values=c("red", "blue", "black")) +
  labs(color = "# of cylinders:")
</code>```

Body:
Trying to define manual colors for text on individual facets created by ggplot. But the code is assigning random colors.

I have included the code I tried to get the colors right.

library(ggplot2)

p <- ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  facet_grid(. ~ cyl) +
  theme(panel.spacing = unit(1, "lines"))

dat_text <- data.frame(
  label = c("4 cylinders", "6 cylinders", "8 cylinders"),
  cyl   = c(4, 6, 8),
  cl = c("red", "blue", "black"),
  x     = c(20, 27.5, 25),
  y     = c(4, 4, 4.5)
)

p + geom_text(
  data    = dat_text,
  mapping = aes(x = x, y = y, label = label, colour= cl)
)

The code is working except it is giving random colors instead of assigned colors.

Body:
Alternatively you can plot them all on the same plot, and just change the colour of the points.

ggplot(data=mtcars) +
  geom_point(data = mt, aes(x = mpg, y = wt, color = factor(mt$cyl))) +
  scale_color_manual(values=c("red", "blue", "black")) +
  labs(color = "# of cylinders:")


问:
I can not put file value in my formBuilder because of "Failed to set the 'value' property on 'HTMLInputElement'"
I am trying to make formgroup to register with an image.
here is my template for fileuploader:

```<code><label for="file-loader" class="float-right">
  <img src="assets/images/robot-02-icon.png" alt="robot" *ngIf="!imgURL">
  <img [src]="imgURL" height="200" *ngIf="imgURL">
</label>
<input type="file" formControlName="photo_id" id="file-loader" (change)="readURL($event)">
</code>```

here is my readURL function():

```<code>  readURL(event) {
    if (event.target.files.length === 0) {
      return;
    }
    const reader = new FileReader();
    this.imagePath = event.target.files;
    this.registerForm.patchValue({
      photo_id: event.target.files[0]
    });
    reader.readAsDataURL(event.target.files[0]);
    reader.onload = ( ) => {
      this.imgURL = reader.result;
      console.log(this.imgURL = reader.result);
      this.registerForm.patchValue({
        photo_id: reader.result
      });
    };
  }
</code>```

my formbuilder is like this:

```<code>this.registerForm = this.formBuilder.group({
  name: ['', Validators.required],
  email: ['', [Validators.required, Validators.email]],
  password: ['', Validators.required],
  photo_id: [''],
});
</code>```

and when I am trying to submit the form I receive this message in my console:

SingupComponent.html:10 ERROR DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.

答:
Well, in my opinion you should not have a formControlName in your input file. The error shows up because when you read up your selected file your are getting a data as follow in your FormControl:

```<code>C:\\some_directory\\file.png
</code>```

and when the FileReader ends up the process, the result is as follow:

```<code>data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCADIAMgDASIAAhEBAxEB/8QAHQAAAAcBAQEAAAA...
</code>```

then you are trying tu put that data into the FormControl again doing a patchValue and is for that reason the error thrown, because you are patching data incompatible with the input file interface. I recommend you remove the formControlName from the input file and everything should work with the (change).

On the other hand, you are being redundant because you are catching the file selected in two sides, in this case the FormControl and (change), in this last you are transforming the data and overriding it in the FormControl with other format. I hope I were clear -.-

Body:
I am trying to make formgroup to register with an image.
here is my template for fileuploader:

<input type="file" formControlName="photo_id" id="file-loader" (change)="readURL($event)">

here is my readURL function():

  readURL(event) {
    if (event.target.files.length === 0) {
      return;
    }
    const reader = new FileReader();
    this.imagePath = event.target.files;
    this.registerForm.patchValue({
      photo_id: event.target.files[0]
    });
    reader.readAsDataURL(event.target.files[0]);
    reader.onload = ( ) => {
      this.imgURL = reader.result;
      console.log(this.imgURL = reader.result);
      this.registerForm.patchValue({
        photo_id: reader.result
      });
    };
  }

my formbuilder is like this:

this.registerForm = this.formBuilder.group({
  name: ['', Validators.required],
  email: ['', [Validators.required, Validators.email]],
  password: ['', Validators.required],
  photo_id: [''],
});

and when I am trying to submit the form I receive this message in my console:

SingupComponent.html:10 ERROR DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.

Body:
Well, in my opinion you should not have a formControlName in your input file. The error shows up because when you read up your selected file your are getting a data as follow in your FormControl:

C:\\some_directory\\file.png

and when the FileReader ends up the process, the result is as follow:

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCADIAMgDASIAAhEBAxEB/8QAHQAAAAcBAQEAAAA...

then you are trying tu put that data into the FormControl again doing a patchValue and is for that reason the error thrown, because you are patching data incompatible with the input file interface. I recommend you remove the formControlName from the input file and everything should work with the (change).

On the other hand, you are being redundant because you are catching the file selected in two sides, in this case the FormControl and (change), in this last you are transforming the data and overriding it in the FormControl with other format. I hope I were clear -.-


问:
How to Check if a SYSTEM environment variable exists?
There is USER Environment Variables, and SYSTEM environment variables.

How can i make this condition check ONLY for SYSTEM env variable if it exists?

```<code>if (-not Test-Path 'env:VariableX ') {

    "doesnt exist!"
}
</code>```

this would not return anything if VariableX is defined as a USER variable. i want to ignore that and only focus on if its defined in SYSTEM env variables

答:
This would work:

if (-not [Environment]::GetEnvironmentVariable('VariableX', 'Machine'))
{
    "doesnt exist!"
}
```

Body:
There is USER Environment Variables, and SYSTEM environment variables.

How can i make this condition check ONLY for SYSTEM env variable if it exists?

if (-not Test-Path 'env:VariableX ') {

    "doesnt exist!"
}

this would not return anything if VariableX is defined as a USER variable. i want to ignore that and only focus on if its defined in SYSTEM env variables


问:
Merge Rows of Dataframe based on condition
I have a csv file with only one column "notes". I want to merge rows of data-frame based on some condition.

Input_data={'notes':
            ['aaa','bbb','*','hello','**','my name','is xyz',
             '(1)','this is','temp','name',
             '(2)','BTW','how to','solve this',
             '(3)','with python','I don’t want this to be added ',
             'I don’t want this to be added ']}

df_in = pd.DataFrame(Input_data)
```

<p>Input looks like this </p>

<p><img src="https://i.stack.imgur.com/CWOAt.png" alt="Sample input"></p>

<p>Output</p>

<pre class="lang-py prettyprint-override"><code>output_Data={'notes':
             ['aaa','bbb','*hello','**my name is xyz',
              '(1) this is temp name',
              '(2) BTW how to solve this',
              '(3) with python','I don’t want this to be added ',
              'I don’t want this to be added ']}
df_out=pd.DataFrame(output_Data)
</code>```

I want to merge the rows with the above row which have either "*" or "(number)" in it. So the output will look like

Other rows which can not be merged should be left.
Also, in case of last row as there is no proper way to know up-to what range we can merge lets say just add only one next row
I solved this but its very long. Any simpler way

```<code>df=pd.DataFrame(Input_data)
notes=[];temp=[];flag='';value='';c=0;chk_star='yes'
for i,row in df.iterrows():
    row[0]=str(row[0])
    if '*' in row[0].strip()[:5] and chk_star=='yes':
        value=row[0].strip()
        temp=temp+[value]
        value=''
        continue

    if '(' in row[0].strip()[:5]:
        chk_star='no'
        temp=temp+[value]
        value='';c=0
        flag='continue'
        value=row[0].strip()
    if flag=='continue' and '(' not in row[0][:5] :
        value=value+row[0]
        c=c+1
    if c>4:
        temp=temp+[value]
        print "111",value,temp
        break
if '' in temp:
    temp.remove('')
df=pd.DataFrame({'notes':temp})
</code>```

答:
I think it is easier when you design your logic to separate df_in into 3 parts: top, middle and bottom. Keeping top and bottom intact while joining middle part. Finally, concat 3 parts together into df_out

First, create m1 and m2 masks to separate df_in to 3 parts.

```<code>m1 = df_in.notes.str.strip().str.contains(r'^\*+|\(\d+\)$').cummax()
m2 =  ~df_in.notes.str.strip().str.contains(r'^I don’t want this to be added$')
top = df_in[~m1].notes
middle = df_in[m1 & m2].notes
bottom = df_in[~m2].notes
</code>```

Next, create groupby_mask to group rows and groupby and join:

```<code>groupby_mask = middle.str.strip().str.contains(r'^\*+|\(\d+\)$').cumsum()
middle_join = middle.groupby(groupby_mask).agg(' '.join)

Out[3110]:
notes
1                      * hello
2            ** my name is xyz
3        (1) this is temp name
4    (2) BTW how to solve this
5              (3) with python
Name: notes, dtype: object
</code>```

Finally, use pd.concat to concat top, middle_join, bottom

```<code>df_final = pd.concat([top, middle_join, bottom], ignore_index=True).to_frame()

Out[3114]:
                            notes
0                             aaa
1                             bbb
2                         * hello
3               ** my name is xyz
4           (1) this is temp name
5       (2) BTW how to solve this
6                 (3) with python
7  I don’t want this to be added
8  I don’t want this to be added
</code>```

Body:
I have a csv file with only one column "notes". I want to merge rows of data-frame based on some condition.

Input_data={'notes':
            ['aaa','bbb','*','hello','**','my name','is xyz',
             '(1)','this is','temp','name',
             '(2)','BTW','how to','solve this',
             '(3)','with python','I don’t want this to be added ',
             'I don’t want this to be added ']}

df_in = pd.DataFrame(Input_data)

Input looks like this

Output

output_Data={'notes':
             ['aaa','bbb','*hello','**my name is xyz',
              '(1) this is temp name',
              '(2) BTW how to solve this',
              '(3) with python','I don’t want this to be added ',
              'I don’t want this to be added ']}
df_out=pd.DataFrame(output_Data)

I want to merge the rows with the above row which have either "*" or "(number)" in it. So the output will look like

Other rows which can not be merged should be left.
Also, in case of last row as there is no proper way to know up-to what range we can merge lets say just add only one next row
I solved this but its very long. Any simpler way

df=pd.DataFrame(Input_data)
notes=[];temp=[];flag='';value='';c=0;chk_star='yes'
for i,row in df.iterrows():
    row[0]=str(row[0])
    if '*' in row[0].strip()[:5] and chk_star=='yes':
        value=row[0].strip()
        temp=temp+[value]
        value=''
        continue

    if '(' in row[0].strip()[:5]:
        chk_star='no'
        temp=temp+[value]
        value='';c=0
        flag='continue'
        value=row[0].strip()
    if flag=='continue' and '(' not in row[0][:5] :
        value=value+row[0]
        c=c+1
    if c>4:
        temp=temp+[value]
        print "111",value,temp
        break
if '' in temp:
    temp.remove('')
df=pd.DataFrame({'notes':temp})

Body:
I think it is easier when you design your logic to separate df_in into 3 parts: top, middle and bottom. Keeping top and bottom intact while joining middle part. Finally, concat 3 parts together into df_out

First, create m1 and m2 masks to separate df_in to 3 parts.

m1 = df_in.notes.str.strip().str.contains(r'^\*+|\(\d+\)$').cummax()
m2 =  ~df_in.notes.str.strip().str.contains(r'^I don’t want this to be added$')
top = df_in[~m1].notes
middle = df_in[m1 & m2].notes
bottom = df_in[~m2].notes

Next, create groupby_mask to group rows and groupby and join:

groupby_mask = middle.str.strip().str.contains(r'^\*+|\(\d+\)$').cumsum()
middle_join = middle.groupby(groupby_mask).agg(' '.join)

Out[3110]:
notes
1                      * hello
2            ** my name is xyz
3        (1) this is temp name
4    (2) BTW how to solve this
5              (3) with python
Name: notes, dtype: object

Finally, use pd.concat to concat top, middle_join, bottom

df_final = pd.concat([top, middle_join, bottom], ignore_index=True).to_frame()

Out[3114]:
                            notes
0                             aaa
1                             bbb
2                         * hello
3               ** my name is xyz
4           (1) this is temp name
5       (2) BTW how to solve this
6                 (3) with python
7  I don’t want this to be added
8  I don’t want this to be added


问:
How do you acces IdentityUser to change its role?
I want to change the role of a user in my application.

I used Dependency Injection to access  UserManager _usermanager in my controller. To change the role I'm supposed to call _usermanager.AddToRoleAsync(IdentityUser user, string role), but I can't seem to locate the a IdentityUser enity.

```<code>    [HttpPost]
    public async Task<IActionResult> BewerkGebruiker(int id , ... )
    {
        Gebruiker g;
        using (var context =  new UTILcontext())
        {
            _userManager.AddToRoleAsync(<<what do i put here?>>),Rol);
            _manager.UpdateGebruiker(g);
            return RedirectToAction("Gebruikers");
        };
</code>```

答:
Something like this should work. AppUser is a class derived from Microsoft.AspNetCore.Identity.IdentityUser that you would typically have in your Models directory.

```<code>[HttpPost]
public async Task<IActionResult> EditUser(int userId, string roleName, ...)
{
     AppUser user = await userManager.FindByIdAsync(model.Id);

     if (user != null)
         IdentityResult result = await userManager.AddToRoleAsync(user, roleName);
    . . .
}
</code>```

Body:
I want to change the role of a user in my application.

I used Dependency Injection to access  UserManager _usermanager in my controller. To change the role I'm supposed to call _usermanager.AddToRoleAsync(IdentityUser user, string role), but I can't seem to locate the a IdentityUser enity.

    [HttpPost]
    public async Task<IActionResult> BewerkGebruiker(int id , ... )
    {
        Gebruiker g;
        using (var context =  new UTILcontext())
        {
            _userManager.AddToRoleAsync(<<what do i put here?>>),Rol);
            _manager.UpdateGebruiker(g);
            return RedirectToAction("Gebruikers");
        };

Body:
Something like this should work. AppUser is a class derived from Microsoft.AspNetCore.Identity.IdentityUser that you would typically have in your Models directory.

[HttpPost]
public async Task<IActionResult> EditUser(int userId, string roleName, ...)
{
     AppUser user = await userManager.FindByIdAsync(model.Id);

     if (user != null)
         IdentityResult result = await userManager.AddToRoleAsync(user, roleName);
    . . .
}


问:
How do I trigger a function several components higher in React?
Just learning React, and I would like to add an onClick on the font awesome icon, and run the markTaskAsCompleted function. I'm having trouble because it's several components lower in the hierarchy. How would you ideally go about this? Bear in mind that I also have to pass the ID of the task in the function.

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

  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      tasks: [],
    };
  }

  componentDidMount() {
    this.onListenForTasks();
  }

  onListenForTasks() {
    this.setState({ loading: true });
    this.unsubscribe = this.props.firebase
      .tasks()
      .orderBy('created', 'desc')
      .onSnapshot(snapshot => {
        if (snapshot.size) {
          let tasks = [];
          snapshot.forEach(doc =>
            tasks.push({ ...doc.data(), uid: doc.id }),
          );
          this.setState({
            tasks: tasks,
            loading: false
          });
        } else {
          this.setState({ tasks: null, loading: false });
        }
    });
  }

  markTaskAsCompleted(){
    console.log("Completed");
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  render() {
    const { tasks, loading } = this.state;
    return (
      <div>
        {loading && <div>Loading ...</div>}
        {tasks ? (
          <TaskList tasks={tasks} />
        ):(
          <div>There are no tasks ...</div>
        )}
      </div>
    );
  }

}

const Tasks = withFirebase(TasksBase);

const TaskList = ({ tasks }) => (
  <ul className="tasks">
    {tasks.map( task => (
      <Task key={task.uid} task={task} />
    ))}
  </ul>
);

const Task = ({ task }) => (
  (!task.completed && !task.obsolete && !task.waitingForDependencies) &&
  <li className="task">
    <strong>{task.userId}</strong> {task.name}
    <div className="icons">
      <FontAwesomeIcon icon="check-circle"/>
      <FontAwesomeIcon icon="times-circle" />
    </div>
  </li>
);

const condition = authUser => !!authUser;

export default compose(
  withEmailVerification,
  withAuthorization(condition),
)(Tasks);
</code>```

答:
you will need to pass it down the tree as

markTaskAsCompleted={this.props.markTaskAsCompleted}

and make sure that the function is bound to the parent in the constructor.

u can use refs or document.getElementById to get the ID.

Body:
Just learning React, and I would like to add an onClick on the font awesome icon, and run the markTaskAsCompleted function. I'm having trouble because it's several components lower in the hierarchy. How would you ideally go about this? Bear in mind that I also have to pass the ID of the task in the function.

class TasksBase extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      tasks: [],
    };
  }

  componentDidMount() {
    this.onListenForTasks();
  }

  onListenForTasks() {
    this.setState({ loading: true });
    this.unsubscribe = this.props.firebase
      .tasks()
      .orderBy('created', 'desc')
      .onSnapshot(snapshot => {
        if (snapshot.size) {
          let tasks = [];
          snapshot.forEach(doc =>
            tasks.push({ ...doc.data(), uid: doc.id }),
          );
          this.setState({
            tasks: tasks,
            loading: false
          });
        } else {
          this.setState({ tasks: null, loading: false });
        }
    });
  }

  markTaskAsCompleted(){
    console.log("Completed");
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  render() {
    const { tasks, loading } = this.state;
    return (

        {loading &&
Loading ...
}
        {tasks ? (
          <TaskList tasks={tasks} />
        ):(

There are no tasks ...

        )}

    );
  }

}

const Tasks = withFirebase(TasksBase);

const TaskList = ({ tasks }) => (

    {tasks.map( task => (
      <Task key={task.uid} task={task} />
    ))}

);

const Task = ({ task }) => (
  (!task.completed && !task.obsolete && !task.waitingForDependencies) &&

    {task.userId} {task.name}

      <FontAwesomeIcon icon="check-circle"/>
      <FontAwesomeIcon icon="times-circle" />

);

const condition = authUser => !!authUser;

export default compose(
  withEmailVerification,
  withAuthorization(condition),
)(Tasks);


问:
How to add waits in-between pictures
I want to make two pictures that go on top of each other after I press the 'w' key to create a walking animation:

```<code>#Imports
import turtle
import time

#Registers Gifs
turtle.register_shape("ZeldaBackToolless1.gif")
turtle.register_shape("ZeldaBackToolless2.gif")

Zelda = turtle.Turtle()
Zelda.penup()

def move_up():
    if Waiting == True:
        time.sleep(.2)
        Zelda.shape("ZeldaBackToolless1.gif")
        Waiting = False
    else:
        time.sleep(.2)
        Zelda.shape("ZeldaBackToolless2.gif")
        Waiting = True

turtle.listen()
turtle.onkeypress(move_up, "w")
</code>```

If there's a way to make a boolean statement in the move_up() function with the boolean statement saving which state it was previously at, that would work great, I think.

答:
As much as I hate to suggest it, the easy way at this level of programming is to use a global state variable:

```<code>waiting = True

def move_up():
    global waiting

    time.sleep(.2)
    if waiting:
        Zelda.shape("ZeldaBackToolless1.gif")
    else:
        Zelda.shape("ZeldaBackToolless2.gif")

    waiting = !waiting
</code>```

Even shorter, you can use your flag as a list index:

```<code>waiting = True

def move_up():
    global waiting
    display = ["ZeldaBackToolless1.gif", "ZeldaBackToolless2.gif"]

    waiting = !waiting
    time.sleep(.2)
    Zelda.shape(dislpay[waiting])
</code>```

Title: How to add waits in-between pictures

Body:
I want to make two pictures that go on top of each other after I press the 'w' key to create a walking animation:

#Imports
import turtle
import time

#Registers Gifs
turtle.register_shape("ZeldaBackToolless1.gif")
turtle.register_shape("ZeldaBackToolless2.gif")

Zelda = turtle.Turtle()
Zelda.penup()

def move_up():
    if Waiting == True:
        time.sleep(.2)
        Zelda.shape("ZeldaBackToolless1.gif")
        Waiting = False
    else:
        time.sleep(.2)
        Zelda.shape("ZeldaBackToolless2.gif")
        Waiting = True

turtle.listen()
turtle.onkeypress(move_up, "w")

If there's a way to make a boolean statement in the move_up() function with the boolean statement saving which state it was previously at, that would work great, I think.

Body:
As much as I hate to suggest it, the easy way at this level of programming is to use a global state variable:

waiting = True

def move_up():
    global waiting

    time.sleep(.2)
    if waiting:
        Zelda.shape("ZeldaBackToolless1.gif")
    else:
        Zelda.shape("ZeldaBackToolless2.gif")

    waiting = !waiting

Even shorter, you can use your flag as a list index:

waiting = True

def move_up():
    global waiting
    display = ["ZeldaBackToolless1.gif", "ZeldaBackToolless2.gif"]

    waiting = !waiting
    time.sleep(.2)
    Zelda.shape(dislpay[waiting])


问:
Hide a list except the selected list option
I need some help with a nested list, what I want to do is to show one of the list options and hide the rest of the list,  a great example that I saw was in the filesonic.com languages selector or netlog status change in the header.

```<code><ul class="links">
  <li class="us">United States</li>
  <li class="canada">Canada</li>
  <li class="france">France</li>
  <li class="china">China</li>
  <li class="englande">England</li>
</code>```

United States is the default but when someone click on France, the rest of the list will hide and show will show.

thanks in advance.

答:
You could use something like:

```<code>if ($('.selected').length){
    return false;
}
else {
    $('.links li:first').addClass('selected');
}
$('.links li').click(
    function(){
        $('.selected').removeClass('selected');
        $(this).addClass('selected');
    });
</code>```

coupled with the CSS:

```<code>li {
    display: none;
}

li.selected {
    display: list-item;
}

ul:hover li {
    display: list-item;
}
</code>```

JS Fiddle demo.

Body:
I need some help with a nested list, what I want to do is to show one of the list options and hide the rest of the list,  a great example that I saw was in the filesonic.com languages selector or netlog status change in the header.

United States

Canada

France

China

England

United States is the default but when someone click on France, the rest of the list will hide and show will show.

thanks in advance.

Body:
You could use something like:

if ($('.selected').length){
    return false;
}
else {
    $('.links li:first').addClass('selected');
}
$('.links li').click(
    function(){
        $('.selected').removeClass('selected');
        $(this).addClass('selected');
    });

coupled with the CSS:

li {
    display: none;
}

li.selected {
    display: list-item;
}

ul:hover li {
    display: list-item;
}

JS Fiddle demo.


问:
Three.js Transform Controls causes lag
I've added transform controls to a sphere, so it can be moved around my scene. I have also added orbit controls to pan around my scene, which works fine. When the scene is first loaded up there is no lag and it works great, but as soon as I move the sphere, there is significant lag.

I can deal with this, but what I really want to fix is that even once I deselect the sphere and am not moving it anymore, there continues to be lag when just using the orbit controls.

Why does the lag continue even after I am not actively using the transform controls?

```<code>var renderer, scene, camera, controls;

init();

var geometry = new THREE.SphereGeometry( .025, 5, 5 );
var material = new THREE.MeshPhongMaterial( {color: 0xffffff} );
var sphere = new THREE.Mesh( geometry, material );
addControls(sphere,"translate");
scene.add(sphere);

render();

function addControls(object, type) {

   var transformControl = new THREE.TransformControls( camera,    renderer.domElement );

   transformControl.addEventListener( 'change', render );
   transformControl.addEventListener( 'dragging-changed', function ( event ) {

       controls.enabled = ! event.value;

   } );

   transformControl.attach( object );
   transformControl.setMode( type );
   transformControl.setSpace( "local" );
   scene.add( transformControl );

}

function init() {

   // Renderer
   renderer = new THREE.WebGLRenderer({ antialias: true });
   renderer.setSize(WIDTH, HEIGHT);
   renderer.setPixelRatio(window.devicePixelRatio);
   renderer.setClearColor(0xffffff);
   document.body.appendChild(renderer.domElement);

   // Camera
   camera = new THREE.PerspectiveCamera(100, WIDTH / HEIGHT, 0.1, 1000);
   camera.position.set(500, 0, 0);

   // Orbit Controls
   controls = new THREE.OrbitControls(camera, renderer.domElement);
   controls.maxDistance = 5;

   // Scene
   scene = new THREE.Scene();

}

function render() {

   renderer.render(scene, camera);
   requestAnimationFrame(render);

}

</code>```

I have tried removing the transform controls from the scene by placing the following inside addControls():

```<code>window.addEventListener( 'keypress', function ( event ) {

   transformControl.detach( object );
   transformControl.dispose();
   scene.remove(transformControl);

} );
</code>```

After I had moved the sphere around a bit, I would press a key and the transform controls would disappear, but the lag continued.
I expected that there may be some lag when moving the sphere, but that this would go away when it was not being moved.

Instead, there continues to be lag even when I am only using orbit controls.

How can I minimize this lag?

答:
Welcome to StackOverflow.

The reason is because you are stacking calls of requestAnimationFrame every time your controls get a change event. You call the render function, which in turn will request that it get called again on every frame update. You can imagine how quickly this blows up. This causes lag even after removing the transform controls.

To fix this behavior, you should decouple your render function from the animate loop.

```<code>function animate() {

  requestAnimationFrame( animate );

  render();

}

function render() {

  renderer.render( scene, camera );

}
</code>```

Now, changes on transform control will only render the scene, not mess with the animation loop.

JSFiddle Example

Title: Three.js Transform Controls causes lag

Body:
I've added transform controls to a sphere, so it can be moved around my scene. I have also added orbit controls to pan around my scene, which works fine. When the scene is first loaded up there is no lag and it works great, but as soon as I move the sphere, there is significant lag.

I can deal with this, but what I really want to fix is that even once I deselect the sphere and am not moving it anymore, there continues to be lag when just using the orbit controls.

Why does the lag continue even after I am not actively using the transform controls?

var renderer, scene, camera, controls;

init();

var geometry = new THREE.SphereGeometry( .025, 5, 5 );
var material = new THREE.MeshPhongMaterial( {color: 0xffffff} );
var sphere = new THREE.Mesh( geometry, material );
addControls(sphere,"translate");
scene.add(sphere);

render();

function addControls(object, type) {

   var transformControl = new THREE.TransformControls( camera,    renderer.domElement );

   transformControl.addEventListener( 'change', render );
   transformControl.addEventListener( 'dragging-changed', function ( event ) {

       controls.enabled = ! event.value;

   } );

   transformControl.attach( object );
   transformControl.setMode( type );
   transformControl.setSpace( "local" );
   scene.add( transformControl );

}

function init() {

   // Renderer
   renderer = new THREE.WebGLRenderer({ antialias: true });
   renderer.setSize(WIDTH, HEIGHT);
   renderer.setPixelRatio(window.devicePixelRatio);
   renderer.setClearColor(0xffffff);
   document.body.appendChild(renderer.domElement);

   // Camera
   camera = new THREE.PerspectiveCamera(100, WIDTH / HEIGHT, 0.1, 1000);
   camera.position.set(500, 0, 0);

   // Orbit Controls
   controls = new THREE.OrbitControls(camera, renderer.domElement);
   controls.maxDistance = 5;

   // Scene
   scene = new THREE.Scene();

}

function render() {

   renderer.render(scene, camera);
   requestAnimationFrame(render);

}

I have tried removing the transform controls from the scene by placing the following inside addControls():

window.addEventListener( 'keypress', function ( event ) {

   transformControl.detach( object );
   transformControl.dispose();
   scene.remove(transformControl);

} );

After I had moved the sphere around a bit, I would press a key and the transform controls would disappear, but the lag continued.
I expected that there may be some lag when moving the sphere, but that this would go away when it was not being moved.

Instead, there continues to be lag even when I am only using orbit controls.

How can I minimize this lag?

Body:
Welcome to StackOverflow.

The reason is because you are stacking calls of requestAnimationFrame every time your controls get a change event. You call the render function, which in turn will request that it get called again on every frame update. You can imagine how quickly this blows up. This causes lag even after removing the transform controls.

To fix this behavior, you should decouple your render function from the animate loop.

function animate() {

  requestAnimationFrame( animate );

  render();

}

function render() {

  renderer.render( scene, camera );

}

Now, changes on transform control will only render the scene, not mess with the animation loop.

JSFiddle Example


问:
Is there a way to stop items in a wrap panel from wrapping "too soon"?
I am trying to dynamically add buttons into a wrappanel that is inside a scrollviewer. I am having no problems adding the buttons, but I am having troubles with the wrap panel bring the buttons up "too soon". The buttons will wrap up, but only half of the button is shown when they are sent up. If I further expand the window the button is shown as it is supposed to.

I would inline an image of what is happening but I don't have enough reputation. Here is the direct link to the image instead, showing my problem.

https://i.imgur.com/NasypbG.png

Is there a way to tell the wrap panel to wait for the whole button to be able to fit before it wraps them up?

I've included the XAML code for the scroll viewer and wrap panel ( and the temporary button inside the wrap panel).

I've tried to play with the options in Visual Studio relating to the wrap panel, but I am at a loss. I know this is probably an easy fix.

```<code><ScrollViewer x:Name="gameSroller" Margin="106,10,10,10">
            <WrapPanel x:Name="gameWrapPanel" Height="900" Width="{Binding Path=ActualWidth,
                   RelativeSource={RelativeSource  AncestorType=Window}}" HorizontalAlignment="Left" RenderTransformOrigin="0.5,0.5" ItemWidth="360">
                <Button x:Name="button" Content="A Game" Width="350" Height="160" Padding="10,10,10,10" Margin="10">
                    <Button.Background>
                        <ImageBrush ImageSource="Resources/header.jpg"/>
                    </Button.Background>
                </Button>
            </WrapPanel>
        </ScrollViewer>
</code>```

答:
I have discovered what I did wrong here.
This part of the WrapPanel's options was incorrect :

```<code>RelativeSource={RelativeSource  AncestorType=Window}
</code>```

Removing it from the XAML now correctly displays the buttons at full size when I increase the size of the window. Sorry for cluttering up the questions section!

Body:
I am trying to dynamically add buttons into a wrappanel that is inside a scrollviewer. I am having no problems adding the buttons, but I am having troubles with the wrap panel bring the buttons up "too soon". The buttons will wrap up, but only half of the button is shown when they are sent up. If I further expand the window the button is shown as it is supposed to.

I would inline an image of what is happening but I don't have enough reputation. Here is the direct link to the image instead, showing my problem.

https://i.imgur.com/NasypbG.png

Is there a way to tell the wrap panel to wait for the whole button to be able to fit before it wraps them up?

I've included the XAML code for the scroll viewer and wrap panel ( and the temporary button inside the wrap panel).

I've tried to play with the options in Visual Studio relating to the wrap panel, but I am at a loss. I know this is probably an easy fix.

<ScrollViewer x:Name="gameSroller" Margin="106,10,10,10">
            <WrapPanel x:Name="gameWrapPanel" Height="900" Width="{Binding Path=ActualWidth,
                   RelativeSource={RelativeSource  AncestorType=Window}}" HorizontalAlignment="Left" RenderTransformOrigin="0.5,0.5" ItemWidth="360">
                <Button x:Name="button" Content="A Game" Width="350" Height="160" Padding="10,10,10,10" Margin="10">
                    <Button.Background>
                        <ImageBrush ImageSource="Resources/header.jpg"/>
                    </Button.Background>
                </Button>
            </WrapPanel>
        </ScrollViewer>

Body:
I have discovered what I did wrong here.
This part of the WrapPanel's options was incorrect :

RelativeSource={RelativeSource  AncestorType=Window}

Removing it from the XAML now correctly displays the buttons at full size when I increase the size of the window. Sorry for cluttering up the questions section!


答:
Bind your class function in the constructor:

```<code>this.markTaskAsCompleted = this.markTaskAsCompleted.bind(this);
</code>```

Pass the function into the child component with props:

```<code><TaskList tasks={tasks} handleMarkCompleted={this.markTaskAsCompleted} />
</code>```

Pass the function again to child component, this is prop drilling and is not the latest greatest approach but it works:

```<code>const TaskList = ({ tasks, handleMarkCompleted }) => (
  <ul className="tasks">
    {tasks.map( task => (
      <Task key={task.uid} task={task} handleMarkCompleted={handleMarkCompleted} />
    ))}
  </ul>
);
</code>```

Trigger the function with onClick:

```<code>inside <Task>...
<FontAwesomeIcon icon="check-circle" onClick={() => handleMarkCompleted(task.uid)} />
</code>```

If passing data into the function (ex. task.uid) make it a param in the function definition as well so you can use it:

```<code>markTaskAsCompleted(id){
    console.log("Completed", id);
}
</code>```

Title: How do I trigger a function several components higher in React?

Body:
Bind your class function in the constructor:

this.markTaskAsCompleted = this.markTaskAsCompleted.bind(this);

Pass the function into the child component with props:

<TaskList tasks={tasks} handleMarkCompleted={this.markTaskAsCompleted} />

Pass the function again to child component, this is prop drilling and is not the latest greatest approach but it works:

const TaskList = ({ tasks, handleMarkCompleted }) => (
  <ul className="tasks">
    {tasks.map( task => (
      <Task key={task.uid} task={task} handleMarkCompleted={handleMarkCompleted} />
    ))}
  </ul>
);

Trigger the function with onClick:

inside <Task>...
<FontAwesomeIcon icon="check-circle" onClick={() => handleMarkCompleted(task.uid)} />

If passing data into the function (ex. task.uid) make it a param in the function definition as well so you can use it:

markTaskAsCompleted(id){
    console.log("Completed", id);
}


问:
When exactly does the TCP handshake occur in a XMLHttpRequest?
The XMLHttpRequest interface provides both an open() and a send() method.

In the following sample code:

```<code>var xhr = new XMLHttpRequest();
xhr.open('GET', '/server', true);

xhr.onload = function () {
  // Request finished. Do processing here.
};

xhr.send('string');
</code>```

Does the TCP handshake occur when send() is invoked, or open()?

答:
Only with HTTP version less than 1.1 are the lifetimes of requests and their underlying connection directly related.

The lifetime of the HTTP request is independent of the lifetime of its underlying connection since HTTP 1.1. Many requests can be pipelined down a single connection.

XMLHttpRequest.open is an abstraction that is convenient for the user, but under-the-hood, if the browser already has available sockets connected to the host, they can be reused, meaning that the TCP handshake happened some time ago, independently of all but the first request that passed through the connection.

Body:
The XMLHttpRequest interface provides both an open() and a send() method.

In the following sample code:

var xhr = new XMLHttpRequest();
xhr.open('GET', '/server', true);

xhr.onload = function () {
  // Request finished. Do processing here.
};

xhr.send('string');

Does the TCP handshake occur when send() is invoked, or open()?


问:
Is it possible to programatically export an array of names, emails, and subject lines to the Google Forms "Send" feature?
I have a Google form.
I have a sheet using script that employs arrays storing a list of names, emails, and a subject line collected from my sheet

I want to run a script from my sheet that calls the form (via id, url, or whatever) and tells it to "send" the form to those email addresses.

I cannot find Form API that touches the Forms "Send" feature.

Is that possible? Or will I need to manually generate and send the emails using script the old fashioned way? So they will appear as an email with a link to click rather than the nicely formatted Google Forms email?

答: There is no Form API but there is the Google Apps Script Forms Service but it hasn't a "send" method but it has a getPublishedUrl() that you can use to grab the respond view and send it by using MailApp or GmailApp.</p>


问:
Confusion with scanf() or if()
I am not so familiar with C. Therefore, maybe someone will easily find a solution, I will not mind if you share it.
After entering the data in the first scanf() always gives the option else(): "Error".

I was looking for possible options for the problem. I found a lot of things like that,  but nothing that to help me specifically. I think the mistake is in the strcmp(). But I can not say for sure. Will you help?

```<code>#include <stdio.h>
#include <string.h>

int main()
{
        float celsius, fahrenheit;
        char tempConvering[10];

        printf("Enter what to convert to what (F to C; C to F): ");
        scanf(" %s", &tempConvering[10]);

        if(strcmp(tempConvering, "F to C") == 0)
        {
            printf("\nEnter temperature in Fahrenheit: ");
            scanf(" %f", &fahrenheit);
            celsius = fahrenheit * 1.8 + 32;
            printf("%.2f Fahrenheits = %.2f Celsius\n", fahrenheit, celsius);
        }
        else if(strcmp(tempConvering, "C to F") == 0)
        {
            printf("\nEnter temperature in Celsius: ");
            scanf(" %f", &celsius);
            celsius = (fahrenheit - 32) / 1.8;
            printf("%.2f Celsius = %.2f Fahrenheits\n", celsius, fahrenheit);
        }
        else
        {
            puts("\nError!");
        }
}
</code>```

答:
Don't put extra space while you execute the scanf() function.

This might be an issue sometimes!

This should work fine:

```<code>scanf("%s", tempConvering);
</code>```

By the way, while you take a string as an input, there is no need to use & before the string name.

Someone has already described the details above.

Title: Confusion with scanf() or if()

Body:
I am not so familiar with C. Therefore, maybe someone will easily find a solution, I will not mind if you share it.
After entering the data in the first scanf() always gives the option else(): "Error".

I was looking for possible options for the problem. I found a lot of things like that,  but nothing that to help me specifically. I think the mistake is in the strcmp(). But I can not say for sure. Will you help?

#include <stdio.h>
#include <string.h>

int main()
{
        float celsius, fahrenheit;
        char tempConvering[10];

        printf("Enter what to convert to what (F to C; C to F): ");
        scanf(" %s", &tempConvering[10]);

        if(strcmp(tempConvering, "F to C") == 0)
        {
            printf("\nEnter temperature in Fahrenheit: ");
            scanf(" %f", &fahrenheit);
            celsius = fahrenheit * 1.8 + 32;
            printf("%.2f Fahrenheits = %.2f Celsius\n", fahrenheit, celsius);
        }
        else if(strcmp(tempConvering, "C to F") == 0)
        {
            printf("\nEnter temperature in Celsius: ");
            scanf(" %f", &celsius);
            celsius = (fahrenheit - 32) / 1.8;
            printf("%.2f Celsius = %.2f Fahrenheits\n", celsius, fahrenheit);
        }
        else
        {
            puts("\nError!");
        }
}

Body:
Don't put extra space while you execute the scanf() function.

This might be an issue sometimes!

This should work fine:

scanf("%s", tempConvering);

By the way, while you take a string as an input, there is no need to use & before the string name.

Someone has already described the details above.


问:
Xamarin Essentials - Connectivity.NetworkAccess incorrect on Pixel 3?
I have a function similar to this:

```<code>private bool IsConnected()
{
    if (DeviceInfo.DeviceType == DeviceType.Unknown)
        return false;

    var current = Connectivity.NetworkAccess;

    if (current == NetworkAccess.Internet)
        return true;

    return false;
}
</code>```

My teammates have reported zero issues with this function, and are using a variety of devices.  My personal device is a Google Pixel 3, using Google Fi and Google VPN.  When I cut it into airplane mode, I see Connectivity.NetworkAccess is set to NetworkAccess.None. However, when I leave airplane mode off and turn both Mobile Data and Wifi off explicitly, I see Connectivity.NetworkAccess is set to NetworkAccess.Internet.

Related to this, the Connectivity.ConnectionProfiles reports a single profile: ConnectionProfile.Unknown.

Is this expected behavior?  Should I check a combination of Connectivity.ConnectionProfiles as well as Connectivity.NetworkAccess in attempting to determine if the device actually is connected to a network?

答:
If you can't access the internet and Connectivity.NetworkAccess is NetworkAccess.Internet then it is not expected behavior.

You can submit the issue on their github: https://github.com/xamarin/Essentials/issues

Body:
I have a function similar to this:

private bool IsConnected()
{
    if (DeviceInfo.DeviceType == DeviceType.Unknown)
        return false;

    var current = Connectivity.NetworkAccess;

    if (current == NetworkAccess.Internet)
        return true;

    return false;
}

My teammates have reported zero issues with this function, and are using a variety of devices.  My personal device is a Google Pixel 3, using Google Fi and Google VPN.  When I cut it into airplane mode, I see Connectivity.NetworkAccess is set to NetworkAccess.None. However, when I leave airplane mode off and turn both Mobile Data and Wifi off explicitly, I see Connectivity.NetworkAccess is set to NetworkAccess.Internet.

Related to this, the Connectivity.ConnectionProfiles reports a single profile: ConnectionProfile.Unknown.

Is this expected behavior?  Should I check a combination of Connectivity.ConnectionProfiles as well as Connectivity.NetworkAccess in attempting to determine if the device actually is connected to a network?


问:
I have a couple of Linux commands, which i want to run on windows machine. How to Run Linux commands from Python on Windows
I have some Linux commands which will generate token. I've automated those commands using OS library form Python on Linux machine. It is working fine.

But, When I try the same code in the windows it is returning nothing.

The following is the code I've tried.

```<code>uniqueKey = os.popen('echo -n kittu | base64')
data = uniqueKey.read()
print data
</code>```

in Linux I got the following output

```<code>a210dHU=
</code>```

in windows it is empty.

答: If you use intend to use Linux commands a lot but still want a Windows machine, you can install a Linux subsystem: microsoft documentation</p>

Body:
I have some Linux commands which will generate token. I've automated those commands using OS library form Python on Linux machine. It is working fine.

But, When I try the same code in the windows it is returning nothing.

The following is the code I've tried.

uniqueKey = os.popen('echo -n kittu | base64')
data = uniqueKey.read()
print data

in Linux I got the following output

a210dHU=

in windows it is empty.


问:
Javascript params from string value
I want to set dynamic parameters for the TagEditor (or any other plugin that has parameters) plugin according to an array of paramaters in string (from php), I have a div in this way.

```<code><textarea class="tag-editor" type="text" name="xxxx" data-attributes-js="{placeholder:'1,2,3,4',other_para,:true,....}"></textarea>
</code>```

So in the JS I want to obtain those parameters and return them evaluated so that tagEditor works with those dynamic parameters.

```<code>var $input = $('.tag-editor');
$input.tagEditor( $input.attr("data-attributes-js") );
</code>```

but this does not work, how can I make this work this way?

答:
Not sure what capabilities you have at your PHP server but in general:

create a real object then stringify it

send it over as a JSON string

parse the JSON back into an object

pass the object to .tag-editor()

/* Server Back-end */
/*
this is not code for server -- it's just to provide the JSON string that would come
from a server for demonstration purposes.
*/

let object = {initialTags: ["object", "json-stringify", "data", "json-parse", "tag-editor"]};

let data = JSON.stringify(object);

/* Client Front-end */

$(".tag-editor").data('attributes-js', data);

data = $(".tag-editor").data('attributes-js');

object = JSON.parse(data);

$(".tag-editor").tagEditor(object);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tag-editor/1.0.20/jquery.tag-editor.min.css" />

<textarea class="tag-editor"></textarea>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tag-editor/1.0.20/jquery.tag-editor.min.js"></script></code>```

Title: Javascript params from string value

Body:
I want to set dynamic parameters for the TagEditor (or any other plugin that has parameters) plugin according to an array of paramaters in string (from php), I have a div in this way.

<textarea class="tag-editor" type="text" name="xxxx" data-attributes-js="{placeholder:'1,2,3,4',other_para,:true,....}"></textarea>

So in the JS I want to obtain those parameters and return them evaluated so that tagEditor works with those dynamic parameters.

var $input = $('.tag-editor');
$input.tagEditor( $input.attr("data-attributes-js") );

but this does not work, how can I make this work this way?

Body:
Not sure what capabilities you have at your PHP server but in general:

create a real object then stringify it

send it over as a JSON string

parse the JSON back into an object

pass the object to .tag-editor()

/* Server Back-end */
/*
this is not code for server -- it's just to provide the JSON string that would come
from a server for demonstration purposes.
*/

let object = {initialTags: ["object", "json-stringify", "data", "json-parse", "tag-editor"]};

let data = JSON.stringify(object);

/* Client Front-end */

$(".tag-editor").data('attributes-js', data);

data = $(".tag-editor").data('attributes-js');

object = JSON.parse(data);

$(".tag-editor").tagEditor(object);

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tag-editor/1.0.20/jquery.tag-editor.min.css" />

<textarea class="tag-editor"></textarea>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tag-editor/1.0.20/jquery.tag-editor.min.js"></script>


问:
Git merge deletes empty packages
I have pushed a java application to a bitbucket repository, including a couple of empty packages. Two development branches were created from the master branch and some classes were added to different packages. When I've tried to merge the other branch in my local development branch, no conflict appeared but my packages were deleted.I can see my commits in error log, I can even open my classes in IntelliJ through the Verion Control window, but they got deleted with the merge commit. </p>

<p>How can I revert back my changes? I can't cherry pick the commit, since it's already included in the branch. Git reset doesn't work as well. I can recreate the same classes and copy changes one by one if there is nothing else to do, but there must be some better solution.  </p>

答:
This happened because someone—presumably not you—deleted the code.

Remember that merge does not mean make these the same.  You tell Git:

```<code>git checkout somebranch
git merge anotherbranch
</code>```

That doesn't mean make a new commit in somebranch that exactly matches the last commit in anotherbranch.  Instead, this tells Git:

Find some commit at or before the tip of somebranch, that's also at or before the tip of anotherbranch.  This commit that comes before either tip has to be on both branches, and should be the best common ancestor.  Git calls this commit the merge base.

Now that we know that whoever made somebranch—perhaps us—started with commit B (for base), and whoever made anotherbranch (maybe this was us instead) also started with commit B, compare commit B to the tip of somebranch to see what we/they changed.  Then, compare B to the tip of anotherbranch to see what they/we changed.

The merge now combines these two sets of changes.  For the merge to have decided that file somedir/somepackage.java should be deleted, the change from B to one tip must have been: do nothing at all.  The change from B to the other tip must have been: delete file somedir/somepackage.java.  The combination of these two changes is obvious: delete the file!

Hence, the correct merge result—the combination of the change made by person S on somebranch who said delete the file, and the non-change by person A on anotherbranch who didn't say anything at all—is to delete the file, and Git did that.  (Or, if I have the two branches swapped, it doesn't matter: that's still the automatically-right result.  It's right for Git even if, by your smarter-than-Git human evaluation, it's wrong.)

The file is still complete, whole and intact, in one of the two commits just before the merge, and also in the merge-base commit.  (It's obviously non-existent in the other.)  Just extract it from any commit that has it.  Those commits still exist, and still hold all their files in their committed state, forever: that's why you have a version control system, so as to hold everything everyone ever did.

Getting a file back

To get the file with path P from commit H (where H is some commit hash such as a123456), run:

git checkout H -- P

e.g., git checkout a123456 -- somedir/somepackage.java.  This will extract the copy that's in the commit, placing that copy into your index (ready for your next commit) and your work-tree (ready for you to view it).

Title: Git merge deletes empty packages

Body:
I have pushed a java application to a bitbucket repository, including a couple of empty packages. Two development branches were created from the master branch and some classes were added to different packages. When I've tried to merge the other branch in my local development branch, no conflict appeared but my packages were deleted.I can see my commits in error log, I can even open my classes in IntelliJ through the Verion Control window, but they got deleted with the merge commit.

How can I revert back my changes? I can't cherry pick the commit, since it's already included in the branch. Git reset doesn't work as well. I can recreate the same classes and copy changes one by one if there is nothing else to do, but there must be some better solution.

Body:
This happened because someone—presumably not you—deleted the code.

Remember that merge does not mean make these the same.  You tell Git:

git checkout somebranch
git merge anotherbranch

That doesn't mean make a new commit in somebranch that exactly matches the last commit in anotherbranch.  Instead, this tells Git:

Find some commit at or before the tip of somebranch, that's also at or before the tip of anotherbranch.  This commit that comes before either tip has to be on both branches, and should be the best common ancestor.  Git calls this commit the merge base.

Now that we know that whoever made somebranch—perhaps us—started with commit B (for base), and whoever made anotherbranch (maybe this was us instead) also started with commit B, compare commit B to the tip of somebranch to see what we/they changed.  Then, compare B to the tip of anotherbranch to see what they/we changed.

The merge now combines these two sets of changes.  For the merge to have decided that file somedir/somepackage.java should be deleted, the change from B to one tip must have been: do nothing at all.  The change from B to the other tip must have been: delete file somedir/somepackage.java.  The combination of these two changes is obvious: delete the file!

Hence, the correct merge result—the combination of the change made by person S on somebranch who said delete the file, and the non-change by person A on anotherbranch who didn't say anything at all—is to delete the file, and Git did that.  (Or, if I have the two branches swapped, it doesn't matter: that's still the automatically-right result.  It's right for Git even if, by your smarter-than-Git human evaluation, it's wrong.)

The file is still complete, whole and intact, in one of the two commits just before the merge, and also in the merge-base commit.  (It's obviously non-existent in the other.)  Just extract it from any commit that has it.  Those commits still exist, and still hold all their files in their committed state, forever: that's why you have a version control system, so as to hold everything everyone ever did.

Getting a file back

To get the file with path P from commit H (where H is some commit hash such as a123456), run:

git checkout H -- P

e.g., git checkout a123456 -- somedir/somepackage.java.  This will extract the copy that's in the commit, placing that copy into your index (ready for your next commit) and your work-tree (ready for you to view it).


问:
run py script from another py script using relative path
There are answers for when both scripts are in the same directory.

However, I can't get any of the answers mentioned here  working for a relative path. They are for when the full path is known.

I have the following folder hierarchy

i need to call and run sub.py in commander.py

the following is in commander.py

```<code>import importlib.util
spec = importlib.util.spec_from_file_location('sub.py', '..//main/sub/sub.py')
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.main()
</code>```

it certainly recognized the directory as I can see the pycache 'folder getting created in sub folder.

However the sub script doesn't run.
I have launched the sub script manually and i know it is functional.

the sub script has the following structure

```<code>import stuff

def main():
   do stuff
return

while true:
  main()
break
</code>```

I am new to python.
I have also tried:

```<code>import sys
    sys.path.insert(0, '..\\main\sub')

    import sub.py

    sub.main()
</code>```

i'm using py 3.7
there are no errors

答:
```<code>import subprocess
import os
main_path = os.getcwd()
relative_path =r'..\\Main\sub'

filepath=os.path.join(main_path, relative_path[9:])
subprocess.call('python {filepath}', shell=True)
</code>```

Body:
There are answers for when both scripts are in the same directory.

However, I can't get any of the answers mentioned here  working for a relative path. They are for when the full path is known.

I have the following folder hierarchy

i need to call and run sub.py in commander.py

the following is in commander.py

import importlib.util
spec = importlib.util.spec_from_file_location('sub.py', '..//main/sub/sub.py')
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.main()

it certainly recognized the directory as I can see the pycache 'folder getting created in sub folder.

However the sub script doesn't run.
I have launched the sub script manually and i know it is functional.

the sub script has the following structure

import stuff

def main():
   do stuff
return

while true:
  main()
break

I am new to python.
I have also tried:

import sys
    sys.path.insert(0, '..\\main\sub')

    import sub.py

    sub.main()

i'm using py 3.7
there are no errors


问:
Zabbix not display text on graphs
I'm running zabbix 4 on EC2 Amazon Linux 2 instance. After last update:

```<code>May 29 08:06:46 Updated: zabbix-web-mysql-4.0.8-1.el7.noarch
May 29 08:06:46 Updated: zabbix-web-4.0.8-1.el7.noarch
May 29 08:06:46 Updated: zabbix-get-4.0.8-1.el7.x86_64
May 29 08:06:47 Updated: zabbix-server-mysql-4.0.8-1.el7.x86_64
May 29 08:06:47 Updated: zabbix-agent-4.0.8-1.el7.x86_64
</code>```

All my dashboards graphs lost text description. Even in host configuration, when I click preview in graph there is no text.
Checked on Chrome and Firefox. Tried to recreate dashboard, cleaned browser cache. I googled that it can be issue with fonts. Checked... Still not solved.

screen_of_my_dashboard

screen_of_graph_preview

答:
Resolved on my 4.2.2.

verify permissions for '/usr/share/zabbix/assets', if not 'www-data:www:data'

chown www-data:www-data assets/

If the file does not exist (/usr/share/zabbix/fonts/graphfont.ttf):

cd assets/fonts/

Copy the file graphfont.ttf to /usr/share/zabbix/assets/fonts/: (source: https://support.zabbix.com/browse/ZBX-16182)

cp /usr/share/zabbix/fonts/graphfont.ttf /usr/share/zabbix/assets/fonts/

Or link the file:

ln -s /usr/share/zabbix/fonts/graphfont.ttf /usr/share/zabbix/assets/fonts/

by, Bruno Dolastro - Br4zil

Title: Zabbix not display text on graphs

Body:
I'm running zabbix 4 on EC2 Amazon Linux 2 instance. After last update:

May 29 08:06:46 Updated: zabbix-web-mysql-4.0.8-1.el7.noarch
May 29 08:06:46 Updated: zabbix-web-4.0.8-1.el7.noarch
May 29 08:06:46 Updated: zabbix-get-4.0.8-1.el7.x86_64
May 29 08:06:47 Updated: zabbix-server-mysql-4.0.8-1.el7.x86_64
May 29 08:06:47 Updated: zabbix-agent-4.0.8-1.el7.x86_64

All my dashboards graphs lost text description. Even in host configuration, when I click preview in graph there is no text.
Checked on Chrome and Firefox. Tried to recreate dashboard, cleaned browser cache. I googled that it can be issue with fonts. Checked... Still not solved.

screen_of_my_dashboard

screen_of_graph_preview