问:
How to set dynamically domain for a List
for example, i create list following

```<code>length(List,5),
List :: 1..5,
</code>```

I want to set second element of list, it looks like
List[1] :: 1..2     %List, from 0 to 4

I don't know how to realize it ?

thanks very much :)

答:
For example, using in operator in Swi-prolog, I can do like this:

```<code>init_static(List) :- length(List, 5), List in 1..5, List = [_,Y|_], Y in 1..2.
</code>```

if I know beforehand that I need specific constraints for the second element.

To generalize for any index:

```<code>init_dynamic(I, List) :- length(List, 5), List in 1..5, length(L1, I), Y in 1..2, append(L1, [Y|_], List).
</code>```

So a query for the second element is:

```<code>init_dynamic(1, [1,2,4,3,5]).
true.
</code>```

I assume that you can do similar things with :: operator in other Prolog variants.

Body:
for example, i create list following

length(List,5),
List :: 1..5,

I want to set second element of list, it looks like
List[1] :: 1..2     %List, from 0 to 4

I don't know how to realize it ?

thanks very much :)

Body:
For example, using in operator in Swi-prolog, I can do like this:

init_static(List) :- length(List, 5), List in 1..5, List = [_,Y|_], Y in 1..2.

if I know beforehand that I need specific constraints for the second element.

To generalize for any index:

init_dynamic(I, List) :- length(List, 5), List in 1..5, length(L1, I), Y in 1..2, append(L1, [Y|_], List).

So a query for the second element is:

init_dynamic(1, [1,2,4,3,5]).
true.

I assume that you can do similar things with :: operator in other Prolog variants.


来源: stackexchange

问:
UICollectionViewCell - Applying different CAGradientLayer to different UIView

TL;DR: Have 2 views (top and bottom) that need CAGradientLayer. Unexpected behavior is that only Top View displays gradient. Bottom doesn't display Gradient.

In our application, I have a view that has a UICollectionView as seen on the image:

For each UICollectionViewCell, I created a custom class to do the layout details. On the UICollectionViewCell, I have a "topBackground" and "bottomBackground", which are views that will content labels with info for each Cell:

```<code>@IBOutlet weak var topBackground: UIView!
@IBOutlet weak var bottomBackground: UIView!
</code>```

The Top and Bottom Views, Labels were displaying correctly and the constraints working.

We decided to add a gradient effect on the Top and Bottom View (see details on image, top gradient marked in red and bottom detail marked in yellow) .

For the code, we used the following:

```<code>override func layoutSubviews() {
        if !didLayout{
             // Top View
            let gradientLayer: CAGradientLayer = CAGradientLayer()
            gradientLayer.frame = topBackground.frame
            gradientLayer.colors =
                [UIColor.black.withAlphaComponent(0.5).cgColor, UIColor.black.withAlphaComponent(0).cgColor]
            gradientLayer.startPoint = CGPoint(x: 0.5, y: 0)
            gradientLayer.endPoint = CGPoint(x: 0.5, y: 0.9)
            topBackground.layer.insertSublayer(gradientLayer, at: 0)
            topBackground.backgroundColor = .clear
            topBackground.alpha = 0.5

            // Bottom View
            let gradientLayerBottom: CAGradientLayer = CAGradientLayer()
            gradientLayerBottom.frame = bottomBackground.frame
            gradientLayerBottom.colors =
                [UIColor.black.withAlphaComponent(0.5).cgColor, UIColor.black.withAlphaComponent(0).cgColor]
            gradientLayerBottom.startPoint = CGPoint(x: 0.5, y: 0.9)
            gradientLayerBottom.endPoint = CGPoint(x: 0.5, y: 0)
            bottomBackground.layer.insertSublayer(gradientLayerBottom, at: 0)
            bottomBackground.backgroundColor = .clear
            bottomBackground.alpha = 0.5

            didLayout = true
        } else {
            print("already performed layout")
        }
    }
</code>```

The variable didLayout is to avoid overlapping multiple gradients when scrolling the collection view.

Results:

The Top View is displaying the Gradient (Expected).

Bottom View is not displaying Gradient (Unexpected).

We know the bottom view is there with the constraints working, because if we change the color to other than .clear, it displays the other color. It's just gradientLayerBottom that is not being displayed.

Any ideas on how to get gradientLayerBottom to be displayed?

答:
Try this

```<code>extension UIView{
    func setGradientBackgroundImage(colorTop: UIColor, colorBottom: UIColor) {
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [colorTop.cgColor, colorBottom.cgColor]
        gradientLayer.frame = bounds
        layer.insertSublayer(gradientLayer, at: 0)
    }
}
</code>```

Put in UICollectionViewCell class

```<code>class CollVwCell : UICollectionViewCell{

    @IBOutlet weak var VwTop: UIView!
    @IBOutlet weak var VwBottom: UIView!

    override func awakeFromNib() {
        super.awakeFromNib()
        DispatchQueue.main.async {
            self.VwTop.setGradientBackgroundImage(colorTop: UIColor.red, colorBottom: UIColor.white)
            self.VwBottom.setGradientBackgroundImage(colorTop: UIColor.white, colorBottom: UIColor.purple)
        }
    }
}
</code>```

Output:

ContentLicense: CC BY-SA 4.0

Body:
TL;DR: Have 2 views (top and bottom) that need CAGradientLayer. Unexpected behavior is that only Top View displays gradient. Bottom doesn't display Gradient.

In our application, I have a view that has a UICollectionView as seen on the image:

For each UICollectionViewCell, I created a custom class to do the layout details. On the UICollectionViewCell, I have a "topBackground" and "bottomBackground", which are views that will content labels with info for each Cell:

@IBOutlet weak var topBackground: UIView!
@IBOutlet weak var bottomBackground: UIView!

The Top and Bottom Views, Labels were displaying correctly and the constraints working.

We decided to add a gradient effect on the Top and Bottom View (see details on image, top gradient marked in red and bottom detail marked in yellow) .

For the code, we used the following:

override func layoutSubviews() {
        if !didLayout{
             // Top View
            let gradientLayer: CAGradientLayer = CAGradientLayer()
            gradientLayer.frame = topBackground.frame
            gradientLayer.colors =
                [UIColor.black.withAlphaComponent(0.5).cgColor, UIColor.black.withAlphaComponent(0).cgColor]
            gradientLayer.startPoint = CGPoint(x: 0.5, y: 0)
            gradientLayer.endPoint = CGPoint(x: 0.5, y: 0.9)
            topBackground.layer.insertSublayer(gradientLayer, at: 0)
            topBackground.backgroundColor = .clear
            topBackground.alpha = 0.5

            // Bottom View
            let gradientLayerBottom: CAGradientLayer = CAGradientLayer()
            gradientLayerBottom.frame = bottomBackground.frame
            gradientLayerBottom.colors =
                [UIColor.black.withAlphaComponent(0.5).cgColor, UIColor.black.withAlphaComponent(0).cgColor]
            gradientLayerBottom.startPoint = CGPoint(x: 0.5, y: 0.9)
            gradientLayerBottom.endPoint = CGPoint(x: 0.5, y: 0)
            bottomBackground.layer.insertSublayer(gradientLayerBottom, at: 0)
            bottomBackground.backgroundColor = .clear
            bottomBackground.alpha = 0.5

            didLayout = true
        } else {
            print("already performed layout")
        }
    }

The variable didLayout is to avoid overlapping multiple gradients when scrolling the collection view.

Results:

The Top View is displaying the Gradient (Expected).

Bottom View is not displaying Gradient (Unexpected).

We know the bottom view is there with the constraints working, because if we change the color to other than .clear, it displays the other color. It's just gradientLayerBottom that is not being displayed.

Any ideas on how to get gradientLayerBottom to be displayed?

Body:
Try this

extension UIView{
    func setGradientBackgroundImage(colorTop: UIColor, colorBottom: UIColor) {
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [colorTop.cgColor, colorBottom.cgColor]
        gradientLayer.frame = bounds
        layer.insertSublayer(gradientLayer, at: 0)
    }
}

Put in UICollectionViewCell class

class CollVwCell : UICollectionViewCell{

    @IBOutlet weak var VwTop: UIView!
    @IBOutlet weak var VwBottom: UIView!

    override func awakeFromNib() {
        super.awakeFromNib()
        DispatchQueue.main.async {
            self.VwTop.setGradientBackgroundImage(colorTop: UIColor.red, colorBottom: UIColor.white)
            self.VwBottom.setGradientBackgroundImage(colorTop: UIColor.white, colorBottom: UIColor.purple)
        }
    }
}

Output:


问:
Image Map -like functionality in Flutter?
I've searched quite a bit and not found a solid answer, so if this is a dupe, I honestly tried.

I have an app I'm rewriting and moving away from an html-based hybrid platform (specifically Trigger.io); doing the rewrite in Flutter and Dart, on the quick.

Part of the app includes a pretty simple screen where the user can click on an image of a human body, and via an image map, get back an identifier and caption for the body part (right forearm, left knee, head, etc).

I simply can not find an analog to this behavior and capability in Flutter. Have I missed something simple because I was totally over thinking it?

Thanks much.

答:
You could wrap your Image in a GestureDetector and specify onTapDown (or onTapUp) callbacks that check the tapped coordinates and act accordingly.

(To convert global coordinates to local coordinates, see: flutter : Get Local position of Gesture Detector)

Here's a rough attempt:

import 'package:quiver/iterables.dart' show enumerate;

class ImageMap extends StatelessWidget {
  const ImageMap({
    Key key,
    @required this.image,
    @required this.onTap,
    @required this.regions,
  }) : super(key: key);

  final Widget image;
  final List<Path> regions;

  /// Callback that will be invoked with the index of the tapped region.
  final void Function(int) onTap;

  void _onTap(BuildContext context, Offset globalPosition) {
    RenderObject renderBox = context.findRenderObject();
    if (renderBox is RenderBox) {
      final localPosition = renderBox.globalToLocal(globalPosition);
      for (final indexedRegion in enumerate(regions)) {
        if (indexedRegion.value.contains(localPosition)) {
          onTap(indexedRegion.index);
          return;
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTapDown: (details) => _onTap(context, details.globalPosition),
      child: image,
    );
  }
}
```


问:
Adding custom permissions to imported models
In my Django project, I would like to add a custom permission to the User model imported from django.contrib.auth.

(Specifically, a permission to allow/deny the user to change their password).

I do understand how to add permissions to my own model, however, I would like the ability to extend an existing model.

Is this possible?

答: These instructions are a bit outdated, but should give you an idea on how to extend the User model via inheritance, so that you could add any new functionality to the subclass.

ContentLicense: CC BY-SA 3.0


问:
Ensuring component re-initialization when route params change
I have the following routes defined:

```<code><Switch>
    <Route path="/" exact component={HomePage} />
    <Route path="/project/:id/search" component={SearchPage} />
    <Route path="/project/:id/upload" component={UploadPage} />
</Switch>
</code>```

The issue is that search results (local state of the SearchPage component) remain when you navigate to another project's search page. I could solve it by manually clearing state in willReceiveProps when the ID changes but I want to avoid that as there are several sub-pages of /project that would need the logic.

Using render={()=> <SearchPage />} made no difference.

What's a clean way of ensuring that my components get re-initialized when the parameter in the URL changes?

答:
You may use 'key reset state' technique: if special prop key is different React will for sure recreate element instead of updating.

So it may be

```<code><Route
  path="/project/:id/search"
  render={({ match: {params: {id} } })=> <SearchPage key={id} />}
/>
</code>```

To me this affects readability in bad way. So using componentDidUpdate(willReceiveProps is deprecated) seems to be better maintainable.

Body:
I have the following routes defined:

<Switch>
    <Route path="/" exact component={HomePage} />
    <Route path="/project/:id/search" component={SearchPage} />
    <Route path="/project/:id/upload" component={UploadPage} />
</Switch>

The issue is that search results (local state of the SearchPage component) remain when you navigate to another project's search page. I could solve it by manually clearing state in willReceiveProps when the ID changes but I want to avoid that as there are several sub-pages of /project that would need the logic.

Using render={()=> <SearchPage />} made no difference.

What's a clean way of ensuring that my components get re-initialized when the parameter in the URL changes?

Body:
You may use 'key reset state' technique: if special prop key is different React will for sure recreate element instead of updating.

So it may be

<Route
  path="/project/:id/search"
  render={({ match: {params: {id} } })=> <SearchPage key={id} />}
/>

To me this affects readability in bad way. So using componentDidUpdate(willReceiveProps is deprecated) seems to be better maintainable.


问:
Start cast session for a cast device
I've got this use case:

Detect cast devices and save their id, names and information;

In automatic way, connect to predefined device and start cast session
with some content.

I've studied the Google Cast API v3 and it seems really hard. While with v2 it was possible since the sender app controls 90% of the process, i.e. connection with device and load content, with v3 the session is totally managed by the framework and a session is started only whit user intervention. The only method that it can be worth for my use case is the SessionManager.startSession(Intent intent) doc here, however it's totally undocumented how to use the intent, extra parameters, action and so on. Is there anyone with some knowledge about this method and intent?

答:
I found another way to connect to the cast device without using the intent, but with routes.

So first step is to initialise the cast with the class CastOptionsProvider and the cast context also. The 2nd step to get the devices and last step connect to the cast device by passing the route of the selected device that you retrieved on the 2nd step:

MediaRouter.getInstance(activity).selectRoute(route);

Title: Start cast session for a cast device


问:
Select column name per row for max value in PySpark
I have a dataframe like this, shown only two columns however there are many columns in original dataframe

```<code>data = [(("ID1", 3, 5)), (("ID2", 4, 12)), (("ID3", 8, 3))]
df = spark.createDataFrame(data, ["ID", "colA", "colB"])
df.show()

+---+----+----+
| ID|colA|colB|
+---+----+----+
|ID1|   3|   5|
|ID2|   4|  12|
|ID3|   8|   3|
+---+----+----+
</code>```

I want to extract the name of the column per row, which has the max value. Hence the expected output is like this

```<code>+---+----+----+-------+
| ID|colA|colB|Max_col|
+---+----+----+-------+
|ID1|   3|   5|   colB|
|ID2|   4|  12|   colB|
|ID3|   8|   3|   colA|
+---+----+----+-------+
</code>```

In case of tie, where colA and colB have same value, choose the first column.

How can I achieve this in pyspark

答:
There are multiple options to achieve this. I am a providing example for one and can provide a hint for rest-

```<code>from pyspark.sql import functions as F
from pyspark.sql.window import Window as W
from pyspark.sql import types as T

data = [(("ID1", 3, 5)), (("ID2", 4, 12)), (("ID3", 8, 3))]
df = spark.createDataFrame(data, ["ID", "colA", "colB"])
df.show()

+---+----+----+
| ID|colA|colB|
+---+----+----+
|ID1|   3|   5|
|ID2|   4|  12|
|ID3|   8|   3|
+---+----+----+

#Below F.array creates an array of column name and value pair like [['colA', 3], ['colB', 5]] then F.explode break this array into rows like different column and value pair should be in different rows

df = df.withColumn(
    "max_val",
    F.explode(
        F.array([
            F.array([F.lit(cl), F.col(cl)]) for cl in df.columns[1:]
        ])
    )
)
df.show()
+---+----+----+----------+
| ID|colA|colB|   max_val|
+---+----+----+----------+
|ID1|   3|   5| [colA, 3]|
|ID1|   3|   5| [colB, 5]|
|ID2|   4|  12| [colA, 4]|
|ID2|   4|  12|[colB, 12]|
|ID3|   8|   3| [colA, 8]|
|ID3|   8|   3| [colB, 3]|
+---+----+----+----------+

#Then select columns so that column name and value should be in different columns
df = df.select(
    "ID",
    "colA",
    "colB",
    F.col("max_val").getItem(0).alias("col_name"),
    F.col("max_val").getItem(1).cast(T.IntegerType()).alias("col_value"),
)
df.show()
+---+----+----+--------+---------+
| ID|colA|colB|col_name|col_value|
+---+----+----+--------+---------+
|ID1|   3|   5|    colA|        3|
|ID1|   3|   5|    colB|        5|
|ID2|   4|  12|    colA|        4|
|ID2|   4|  12|    colB|       12|
|ID3|   8|   3|    colA|        8|
|ID3|   8|   3|    colB|        3|
+---+----+----+--------+---------+

# Rank column values based on ID in desc order
df = df.withColumn(
    "rank",
    F.rank().over(W.partitionBy("ID").orderBy(F.col("col_value").desc()))
)
df.show()
+---+----+----+--------+---------+----+
| ID|colA|colB|col_name|col_value|rank|
+---+----+----+--------+---------+----+
|ID2|   4|  12|    colB|       12|   1|
|ID2|   4|  12|    colA|        4|   2|
|ID3|   8|   3|    colA|        8|   1|
|ID3|   8|   3|    colB|        3|   2|
|ID1|   3|   5|    colB|        5|   1|
|ID1|   3|   5|    colA|        3|   2|
+---+----+----+--------+---------+----+

#Finally Filter rank = 1 as max value have rank 1 because we ranked desc value
df.where("rank=1").show()
+---+----+----+--------+---------+----+
| ID|colA|colB|col_name|col_value|rank|
+---+----+----+--------+---------+----+
|ID2|   4|  12|    colB|       12|   1|
|ID3|   8|   3|    colA|        8|   1|
|ID1|   3|   5|    colB|        5|   1|
+---+----+----+--------+---------+----+
</code>```

Other Options are -

Use UDF on your base df and return column name having a max value

In the same example after making the column name and value column instead of rank use group by ID take max col_value. Then join with the previous df.

Body:
I have a dataframe like this, shown only two columns however there are many columns in original dataframe

data = [(("ID1", 3, 5)), (("ID2", 4, 12)), (("ID3", 8, 3))]
df = spark.createDataFrame(data, ["ID", "colA", "colB"])
df.show()

+---+----+----+
| ID|colA|colB|
+---+----+----+
|ID1|   3|   5|
|ID2|   4|  12|
|ID3|   8|   3|
+---+----+----+

I want to extract the name of the column per row, which has the max value. Hence the expected output is like this

+---+----+----+-------+
| ID|colA|colB|Max_col|
+---+----+----+-------+
|ID1|   3|   5|   colB|
|ID2|   4|  12|   colB|
|ID3|   8|   3|   colA|
+---+----+----+-------+

In case of tie, where colA and colB have same value, choose the first column.

How can I achieve this in pyspark

Body:
There are multiple options to achieve this. I am a providing example for one and can provide a hint for rest-

from pyspark.sql import functions as F
from pyspark.sql.window import Window as W
from pyspark.sql import types as T

data = [(("ID1", 3, 5)), (("ID2", 4, 12)), (("ID3", 8, 3))]
df = spark.createDataFrame(data, ["ID", "colA", "colB"])
df.show()

+---+----+----+
| ID|colA|colB|
+---+----+----+
|ID1|   3|   5|
|ID2|   4|  12|
|ID3|   8|   3|
+---+----+----+

#Below F.array creates an array of column name and value pair like [['colA', 3], ['colB', 5]] then F.explode break this array into rows like different column and value pair should be in different rows

df = df.withColumn(
    "max_val",
    F.explode(
        F.array([
            F.array([F.lit(cl), F.col(cl)]) for cl in df.columns[1:]
        ])
    )
)
df.show()
+---+----+----+----------+
| ID|colA|colB|   max_val|
+---+----+----+----------+
|ID1|   3|   5| [colA, 3]|
|ID1|   3|   5| [colB, 5]|
|ID2|   4|  12| [colA, 4]|
|ID2|   4|  12|[colB, 12]|
|ID3|   8|   3| [colA, 8]|
|ID3|   8|   3| [colB, 3]|
+---+----+----+----------+

#Then select columns so that column name and value should be in different columns
df = df.select(
    "ID",
    "colA",
    "colB",
    F.col("max_val").getItem(0).alias("col_name"),
    F.col("max_val").getItem(1).cast(T.IntegerType()).alias("col_value"),
)
df.show()
+---+----+----+--------+---------+
| ID|colA|colB|col_name|col_value|
+---+----+----+--------+---------+
|ID1|   3|   5|    colA|        3|
|ID1|   3|   5|    colB|        5|
|ID2|   4|  12|    colA|        4|
|ID2|   4|  12|    colB|       12|
|ID3|   8|   3|    colA|        8|
|ID3|   8|   3|    colB|        3|
+---+----+----+--------+---------+

# Rank column values based on ID in desc order
df = df.withColumn(
    "rank",
    F.rank().over(W.partitionBy("ID").orderBy(F.col("col_value").desc()))
)
df.show()
+---+----+----+--------+---------+----+
| ID|colA|colB|col_name|col_value|rank|
+---+----+----+--------+---------+----+
|ID2|   4|  12|    colB|       12|   1|
|ID2|   4|  12|    colA|        4|   2|
|ID3|   8|   3|    colA|        8|   1|
|ID3|   8|   3|    colB|        3|   2|
|ID1|   3|   5|    colB|        5|   1|
|ID1|   3|   5|    colA|        3|   2|
+---+----+----+--------+---------+----+

#Finally Filter rank = 1 as max value have rank 1 because we ranked desc value
df.where("rank=1").show()
+---+----+----+--------+---------+----+
| ID|colA|colB|col_name|col_value|rank|
+---+----+----+--------+---------+----+
|ID2|   4|  12|    colB|       12|   1|
|ID3|   8|   3|    colA|        8|   1|
|ID1|   3|   5|    colB|        5|   1|
+---+----+----+--------+---------+----+

Other Options are -

Use UDF on your base df and return column name having a max value

In the same example after making the column name and value column instead of rank use group by ID take max col_value. Then join with the previous df.


问:
Problems with merging multiple QPixmaps
I'm developing a painter-like application and i want my application to have multiple layers for different drawings. For that purpose i have an array, that contains QPixmaps with transparent background and i have a function that merges two QPixmaps (draws one on another). It's done like so:

```<code>    void MeasuresWidget::MergePixmaps(QPixmap source, QPixmap target)//draw source on target
{
    QPainter painter(&target);
    painter.drawPixmap(target.rect(),source,source.rect());
    painter.end();
    imageLabel->setPixmap(target);
}
</code>```

I'm for 100% sure that array of pixmaps (AllLayers array) contains all the drawing i want. Now i want to consistently merge all the drawings with the original image. Here's how i'm trying to achieve this:

```<code>void MeasuresWidget::on_actionAct_triggered()
{
    ForMerging = &OriginalImage;
    for(int i=0;i<5;i++)
        MergePixmaps(AllLayers[i], *ForMerging);
}
</code>```

where ForMerging is temporary QPixmap object for, well, merging, and OriginalImage is, undoubtedly, QPixMap, that contains original image.
Again, i'm 100% sure, that all layers contain it's image on transparent background. The problem i'm facing is that in result original image is merged only with the last drawing, i.e. with AllLayers[4]. If i make i to run from 0 to 2(not including), for example, the result will be original image merged only with AllLayers[1]. I've struggled with this problem for a period of time and have no idea what might be wrong so i'm seeking for any help possible.

答:
Try merge all QPixmap at the same call to MergePixmaps. For this change your Source variable at MergePixmap function to your AllLayers object like this:

```<code>void MeasuresWidget::MergePixmaps(AllLayers *source, QPixmap target)//draw source on target
{
    QPainter painter(&target);
    for(int i = 0; i < source->lenght();i++){
       painter.drawPixmap(target.rect(),source->at(i),source->at(i).rect());
    }
    painter.end();
    imageLabel->setPixmap(target);
}
</code>```

Title: Problems with merging multiple QPixmaps

Body:
I'm developing a painter-like application and i want my application to have multiple layers for different drawings. For that purpose i have an array, that contains QPixmaps with transparent background and i have a function that merges two QPixmaps (draws one on another). It's done like so:

    void MeasuresWidget::MergePixmaps(QPixmap source, QPixmap target)//draw source on target
{
    QPainter painter(&target);
    painter.drawPixmap(target.rect(),source,source.rect());
    painter.end();
    imageLabel->setPixmap(target);
}

I'm for 100% sure that array of pixmaps (AllLayers array) contains all the drawing i want. Now i want to consistently merge all the drawings with the original image. Here's how i'm trying to achieve this:

void MeasuresWidget::on_actionAct_triggered()
{
    ForMerging = &OriginalImage;
    for(int i=0;i<5;i++)
        MergePixmaps(AllLayers[i], *ForMerging);
}

where ForMerging is temporary QPixmap object for, well, merging, and OriginalImage is, undoubtedly, QPixMap, that contains original image.
Again, i'm 100% sure, that all layers contain it's image on transparent background. The problem i'm facing is that in result original image is merged only with the last drawing, i.e. with AllLayers[4]. If i make i to run from 0 to 2(not including), for example, the result will be original image merged only with AllLayers[1]. I've struggled with this problem for a period of time and have no idea what might be wrong so i'm seeking for any help possible.

Body:
Try merge all QPixmap at the same call to MergePixmaps. For this change your Source variable at MergePixmap function to your AllLayers object like this:

void MeasuresWidget::MergePixmaps(AllLayers *source, QPixmap target)//draw source on target
{
    QPainter painter(&target);
    for(int i = 0; i < source->lenght();i++){
       painter.drawPixmap(target.rect(),source->at(i),source->at(i).rect());
    }
    painter.end();
    imageLabel->setPixmap(target);
}


问:
Why is my nested setTimeout not firing removeAttr?
I've got two setTimeout functions that are operating properly but my removeAttr function is not firing. I have no idea why this is.

EDIT: The actual goal is to animate feGaussianBlur's variable "stdDeviation" from 0 to 7 on mouse in.... and 7 to 0 on mouse out... not just once, but an unlimited number of times. While the first path object is still animating, the second path object should also be able to animate separately.

Below is my code but because I'm using a plugin, please follow this link to Codepen: https://codepen.io/ownage/pen/MdzvjW

var polyhoveron = TweenMax.to("#feGaussianBlur", .5, {
  paused:true,
  attr:{"stdDeviation":7},
  onUpdateParams:["{self}"]
});
var polyhoveroff = TweenMax.to("#feGaussianBlur2", .5, {
  paused:true,
  attr:{"stdDeviation":0},
  onUpdateParams:["{self}"]
});

$("svg path").mouseenter(function() {
    $(this).attr("filter", "url(#f1)");
    polyhoveron.play();
    $("p").text("Mouse has entered");
}).mouseleave(function() {
    $(this).attr("filter", "url(#f2)");
    $("p").text("Mouse has left");
    setTimeout(function() {
        setTimeout(function() {
            $(this).removeAttr("filter");
            $("p").text("Why didn't removeAttr work? Now it's broken and can't be started over.");
        }, 500);
        polyhoveroff.play();
        $("p").text("<polyhoveroff function>")
    }, 500);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,body,svg {height:100%}
body {background:cornsilk;}
img,svg path {cursor:pointer;}</code>```

Ready to hover. Problem: This only animates once so enjoy it.

<svg viewBox="90 -10 300 200">

  <defs>

    <filter id="f1" x="-40%" y="-40%" height="200%" width="200%">
      <feOffset result="offOut" in="SourceAlpha" dx="0" dy="0" />
      <feGaussianBlur id="feGaussianBlur" result="blurOut" in="offOut" stdDeviation="0" />
      <feBlend in="SourceGraphic" in2="blurOut" mode="normal" />
    </filter>

    <filter id="f2" x="-40%" y="-40%" height="200%" width="200%">
      <feOffset result="offOut" in="SourceAlpha" dx="0" dy="0" />
      <feGaussianBlur id="feGaussianBlur2" result="blurOut" in="offOut" stdDeviation="7" />
      <feBlend in="SourceGraphic" in2="blurOut" mode="normal" />
    </filter>

  </defs>

  <path d="m 156.29028,68.019096 c 4.67931,-1.988204 -0.12418,-10.666555 10.32783,-11.26589 1.83984,-0.1055 3.04194,0.379201 5.51291,0.764346 0.069,-1.457882 0.39368,-7.513956 0.18783,-9.0114 -0.20581,-1.497443 -2.17888,-0.886775 -3.88749,-1.604662 -2.9137,-2.004347 -3.60967,-4.508091 -4.90279,-7.066947 -1.43623,-2.842048 -2.74829,-5.873666 -3.08935,-9.039685 -0.38465,-3.570722 1.01485,-7.116117 1.23297,-10.703361 1.08612,-0.941004 2.17224,-1.882009 3.25836,-2.823013 -0.40015,-1.882008 -0.8003,-3.764017 -1.20045,-5.646025 -1.881,-1.240819 -5.47796,-1.429412 -4.39448,-4.3669975 0.12147,-1.7496304 0.24294,-3.4992608 0.36441,-5.2488912 -1.71492,0 -3.42985,0 -5.14477,0 1.55912,1.9274484 0.0233,3.2815506 -1.44728,4.4870662 -4.33942,4.6764345 -17.98037,9.8959195 -21.082,8.7530705 -0.2683,-2.332216 -2.37086,2.393413 -3.28353,0.596362 1.34212,2.644214 0.18957,5.899268 -2.70665,6.345448 -2.3295,-1.915206 -4.30895,-5.103085 -7.56114,-3.218799 -3.12217,0.22867 -5.92518,-1.40308 -8.60189,-2.759866 -1.57069,-0.466831 -4.99248,0.07945 -1.89293,1.516781 2.16684,0.932005 4.2283,1.962703 3.53082,4.572657 0,1.793017 0,3.586035 0,5.379053 3.17614,1.071151 2.57339,6.821091 5.18841,6.882203 6.54256,0.152896 6.52233,0.756564 8.9075,3.546429 5.61657,6.569528 3.49195,14.688396 5.04055,24.775964 0.71231,4.639968 4.29374,10.456375 8.59444,10.753658 2.6538,0.183442 4.77082,-4.041744 6.62733,-5.400138 6.44957,-2.977631 3.60533,1.641529 10.42139,-0.217363 z"></path>

  <path d="m 260.769,66.023156 c 3.8349,-4.788158 8.79324,-8.576249 12.7991,-13.224205 1.75034,-2.886256 3.43676,-4.132595 5.93865,-4.863527 1.36048,-1.366469 0.7359,-3.785632 1.10386,-5.678447 -0.76366,-0.838347 -1.35457,-2.029861 -2.22664,-2.646575 -0.99259,-0.08879 -2.12712,0.169001 -3.03839,-0.118352 -1.30495,-1.404354 -2.86845,-2.614797 -4.1339,-4.011836 -2.15241,-6.618271 -4.5275,-13.195742 -5.71384,-20.074944 -1.99173,-9.307097 -2.15055,-5.084229 -4.23803,-2.694703 -1.89331,2.261054 -3.97742,4.394485 -5.75197,6.734975 -2.17919,4.369109 -4.35839,8.738218 -6.53758,13.107327 -1.71492,1.11744 -3.42985,2.234883 -5.14477,3.352328 -1.4828,-0.470312 -2.96182,-1.251763 -4.44692,-1.533208 -4.79877,2.860083 -3.39481,-3.099681 -4.61322,-1.645561 -0.83557,0.646548 -3.16443,2.417752 -4.33214,2.171548 -2.60394,0.20477 -3.7511,-0.08068 -6.2436,-0.757161 -3.3e-4,1.040982 -0.36041,4.077489 1.15977,3.597984 1.14715,0.14345 2.47104,-0.492629 3.62131,0.0082 3.61471,1.043297 7.56377,3.356319 10.11497,7.322839 4.58458,7.718114 4.36102,8.17007 5.13813,13.923417 0.58204,4.309185 2.91437,2.859459 4.04981,4.539599 1.2544,1.856164 1.73521,3.698395 2.9847,6.021742 1.82746,3.202236 1.66695,4.37289 3.5547,4.410115 1.50738,0.02972 2.06302,-2.206341 2.97507,-3.406861 1.09428,-1.440386 1.85013,-3.122803 2.98093,-4.534694 z"></path>

</svg>```

答:
the settimout does not identify $(this) as the selector : svg path

```<code>if i set    $("svg path").removeAttr("filter");
</code>```

it would work , you need to identify the right element selector

So Store this in a var to use for the settimeout:

```<code>var $thisSVG = $(this);
</code>```

then restart the animation before you play it  :
YourObject.restart();

then fine tune the delay
sorry its this one https://codepen.io/anon/pen/EzORXE

Body:
I've got two setTimeout functions that are operating properly but my removeAttr function is not firing. I have no idea why this is.

EDIT: The actual goal is to animate feGaussianBlur's variable "stdDeviation" from 0 to 7 on mouse in.... and 7 to 0 on mouse out... not just once, but an unlimited number of times. While the first path object is still animating, the second path object should also be able to animate separately.

Below is my code but because I'm using a plugin, please follow this link to Codepen: https://codepen.io/ownage/pen/MdzvjW

var polyhoveron = TweenMax.to("#feGaussianBlur", .5, {
  paused:true,
  attr:{"stdDeviation":7},
  onUpdateParams:["{self}"]
});
var polyhoveroff = TweenMax.to("#feGaussianBlur2", .5, {
  paused:true,
  attr:{"stdDeviation":0},
  onUpdateParams:["{self}"]
});

$("svg path").mouseenter(function() {
    $(this).attr("filter", "url(#f1)");
    polyhoveron.play();
    $("p").text("Mouse has entered");
}).mouseleave(function() {
    $(this).attr("filter", "url(#f2)");
    $("p").text("Mouse has left");
    setTimeout(function() {
        setTimeout(function() {
            $(this).removeAttr("filter");
            $("p").text("Why didn't removeAttr work? Now it's broken and can't be started over.");
        }, 500);
        polyhoveroff.play();
        $("p").text("<polyhoveroff function>")
    }, 500);
});

html,body,svg {height:100%}
body {background:cornsilk;}
img,svg path {cursor:pointer;}

Ready to hover. Problem: This only animates once so enjoy it.

<svg viewBox="90 -10 300 200">

  <defs>

    <filter id="f1" x="-40%" y="-40%" height="200%" width="200%">
      <feOffset result="offOut" in="SourceAlpha" dx="0" dy="0" />
      <feGaussianBlur id="feGaussianBlur" result="blurOut" in="offOut" stdDeviation="0" />
      <feBlend in="SourceGraphic" in2="blurOut" mode="normal" />
    </filter>

    <filter id="f2" x="-40%" y="-40%" height="200%" width="200%">
      <feOffset result="offOut" in="SourceAlpha" dx="0" dy="0" />
      <feGaussianBlur id="feGaussianBlur2" result="blurOut" in="offOut" stdDeviation="7" />
      <feBlend in="SourceGraphic" in2="blurOut" mode="normal" />
    </filter>

  </defs>

  <path d="m 156.29028,68.019096 c 4.67931,-1.988204 -0.12418,-10.666555 10.32783,-11.26589 1.83984,-0.1055 3.04194,0.379201 5.51291,0.764346 0.069,-1.457882 0.39368,-7.513956 0.18783,-9.0114 -0.20581,-1.497443 -2.17888,-0.886775 -3.88749,-1.604662 -2.9137,-2.004347 -3.60967,-4.508091 -4.90279,-7.066947 -1.43623,-2.842048 -2.74829,-5.873666 -3.08935,-9.039685 -0.38465,-3.570722 1.01485,-7.116117 1.23297,-10.703361 1.08612,-0.941004 2.17224,-1.882009 3.25836,-2.823013 -0.40015,-1.882008 -0.8003,-3.764017 -1.20045,-5.646025 -1.881,-1.240819 -5.47796,-1.429412 -4.39448,-4.3669975 0.12147,-1.7496304 0.24294,-3.4992608 0.36441,-5.2488912 -1.71492,0 -3.42985,0 -5.14477,0 1.55912,1.9274484 0.0233,3.2815506 -1.44728,4.4870662 -4.33942,4.6764345 -17.98037,9.8959195 -21.082,8.7530705 -0.2683,-2.332216 -2.37086,2.393413 -3.28353,0.596362 1.34212,2.644214 0.18957,5.899268 -2.70665,6.345448 -2.3295,-1.915206 -4.30895,-5.103085 -7.56114,-3.218799 -3.12217,0.22867 -5.92518,-1.40308 -8.60189,-2.759866 -1.57069,-0.466831 -4.99248,0.07945 -1.89293,1.516781 2.16684,0.932005 4.2283,1.962703 3.53082,4.572657 0,1.793017 0,3.586035 0,5.379053 3.17614,1.071151 2.57339,6.821091 5.18841,6.882203 6.54256,0.152896 6.52233,0.756564 8.9075,3.546429 5.61657,6.569528 3.49195,14.688396 5.04055,24.775964 0.71231,4.639968 4.29374,10.456375 8.59444,10.753658 2.6538,0.183442 4.77082,-4.041744 6.62733,-5.400138 6.44957,-2.977631 3.60533,1.641529 10.42139,-0.217363 z"></path>

  <path d="m 260.769,66.023156 c 3.8349,-4.788158 8.79324,-8.576249 12.7991,-13.224205 1.75034,-2.886256 3.43676,-4.132595 5.93865,-4.863527 1.36048,-1.366469 0.7359,-3.785632 1.10386,-5.678447 -0.76366,-0.838347 -1.35457,-2.029861 -2.22664,-2.646575 -0.99259,-0.08879 -2.12712,0.169001 -3.03839,-0.118352 -1.30495,-1.404354 -2.86845,-2.614797 -4.1339,-4.011836 -2.15241,-6.618271 -4.5275,-13.195742 -5.71384,-20.074944 -1.99173,-9.307097 -2.15055,-5.084229 -4.23803,-2.694703 -1.89331,2.261054 -3.97742,4.394485 -5.75197,6.734975 -2.17919,4.369109 -4.35839,8.738218 -6.53758,13.107327 -1.71492,1.11744 -3.42985,2.234883 -5.14477,3.352328 -1.4828,-0.470312 -2.96182,-1.251763 -4.44692,-1.533208 -4.79877,2.860083 -3.39481,-3.099681 -4.61322,-1.645561 -0.83557,0.646548 -3.16443,2.417752 -4.33214,2.171548 -2.60394,0.20477 -3.7511,-0.08068 -6.2436,-0.757161 -3.3e-4,1.040982 -0.36041,4.077489 1.15977,3.597984 1.14715,0.14345 2.47104,-0.492629 3.62131,0.0082 3.61471,1.043297 7.56377,3.356319 10.11497,7.322839 4.58458,7.718114 4.36102,8.17007 5.13813,13.923417 0.58204,4.309185 2.91437,2.859459 4.04981,4.539599 1.2544,1.856164 1.73521,3.698395 2.9847,6.021742 1.82746,3.202236 1.66695,4.37289 3.5547,4.410115 1.50738,0.02972 2.06302,-2.206341 2.97507,-3.406861 1.09428,-1.440386 1.85013,-3.122803 2.98093,-4.534694 z"></path>

</svg>

Body:
the settimout does not identify $(this) as the selector : svg path

if i set    $("svg path").removeAttr("filter");

it would work , you need to identify the right element selector

So Store this in a var to use for the settimeout:

var $thisSVG = $(this);

then restart the animation before you play it  :
YourObject.restart();

then fine tune the delay
sorry its this one https://codepen.io/anon/pen/EzORXE


问:
List of ASP.NET Versions?
Thanks to a Q&A on stackoverflow. I just found out how to determine the installed version on my hosting provider's server. Now I need to know what that number means.

Using <%=Environment.Version%> on my local machine returns 2.0.50727.3053.

Can someone give me a list of the version 1, 1.1, 2, etc. to the actual Environment.Version codes or break down what that code means?

答:
When you refer to a given .NET framework then all below can have different version at a given point of time:

.NET Framework

Common Language Run-time(CLR): Virtual Execution Environment of a process running a .NET EXE

C#: The programming language you're using to write code

ASP.NET (Part of .NET Framework library used for web development)

The code <%=Environment.Version%> referred in your post gives the version of CLR (2nd bullet point above) while you seem to be interested in version of ASP.NET library.

Each release of .NET Framework has ASP.NET library pre-built in it. All its versions can be found in below link:

https://en.wikipedia.org/wiki/ASP.NET

OwnerDisplayName: briankb

Title: List of ASP.NET Versions?

LastEditorDisplayName: briankb


问:
How to cast properties to boolean (deep)
I want to cast every type to boolean or object

```<code>type CastDeep<T, K = boolean> = {
  [P in keyof T]: K extends K[]
    ? K[]
    : T[P] extends ReadonlyArray<K>
      ? ReadonlyArray<CastDeep<K>>
      : CastDeep<T[P]>
}
</code>```

```<code>interface ITest {
  city: {
    name: string,
  }
}
</code>```

Expected result:

```<code>excludeProps<ITest>({
   city: true,
});
</code>```

or

```<code>excludeProps<ITest>({
 city: {
  name: true
 },
});
</code>```

Current error message:

```<code>  19     name: string,
           ~~~~
    The expected type comes from property 'name' which is declared here on type 'CastDeep<{ name: string; }, boolean>'

</code>```

答:
Ok, found a solution</p>

```<code>export type ICastDeep<T> = {
  [P in keyof T]: boolean | ICastDeep<T[P]>;
}
</code>```

Body:
I want to cast every type to boolean or object

type CastDeep<T, K = boolean> = {
  [P in keyof T]: K extends K[]
    ? K[]
    : T[P] extends ReadonlyArray<K>
      ? ReadonlyArray<CastDeep<K>>
      : CastDeep<T[P]>
}

interface ITest {
  city: {
    name: string,
  }
}

Expected result:

excludeProps<ITest>({
   city: true,
});

or

excludeProps<ITest>({
 city: {
  name: true
 },
});

Current error message:

  19     name: string,
           ~~~~
    The expected type comes from property 'name' which is declared here on type 'CastDeep<{ name: string; }, boolean>'

Body:
Ok, found a solution

export type ICastDeep<T> = {
  [P in keyof T]: boolean | ICastDeep<T[P]>;
}


问:
"No installed app with label 'admin'" running Django migration. The app is installed correctly
I am trying to use admin.LogEntry objects during a datamigration on Django 1.7

The 'django.contrib.admin' app is listed on INSTALLED_APPS.

On the shell, it works:

```<code>>>> from django.apps import apps
>>> apps.get_model('admin', 'LogEntry')
django.contrib.admin.models.LogEntry
</code>```

But during the migration, it fails:

```<code>def do_it(apps, schema_editor):
    LogEntry = apps.get_model('admin', 'LogEntry')
</code>```

Fails like this:

```<code>django-admin migrate
(...)
LookupError: No installed app with label 'admin'.
</code>```

Using a debugger, I got that the 'admin' is not installed:

```<code>ipdb> apps.get_apps()
[]
ipdb> apps.all_models.keys()
['website', 'google', 'allauth', 'twitter', 'busca', 'conteudo', 'django_mobile', 'django_filters', 'videocenter', 'tinymce', 'oferta', 'programacaotv', 'contenttypes', 'suit', 'haystack', 'destaque', 'filer', 'galeria', 'auth', 'facebook', 'paintstore', 'critica', 'disqus', 'fichas', 'omeletop', 'autocomplete_light', 'modelsv1', 'temas', 'django_extensions', 'adv_cache_tag', 'taggit', 'social', 'personalidade']
</code>```

WHY??

答:
For me it shows

```<code>raise LookupError(message)
</code>```

LookupError: No installed app with label 'admin'.

and I solve it by pip installing every requirements manually I m using ubuntu 16.04

Body:
I am trying to use admin.LogEntry objects during a datamigration on Django 1.7

The 'django.contrib.admin' app is listed on INSTALLED_APPS.

On the shell, it works:

>>> from django.apps import apps
>>> apps.get_model('admin', 'LogEntry')
django.contrib.admin.models.LogEntry

But during the migration, it fails:

def do_it(apps, schema_editor):
    LogEntry = apps.get_model('admin', 'LogEntry')

Fails like this:

django-admin migrate
(...)
LookupError: No installed app with label 'admin'.

Using a debugger, I got that the 'admin' is not installed:

ipdb> apps.get_apps()
[]
ipdb> apps.all_models.keys()
['website', 'google', 'allauth', 'twitter', 'busca', 'conteudo', 'django_mobile', 'django_filters', 'videocenter', 'tinymce', 'oferta', 'programacaotv', 'contenttypes', 'suit', 'haystack', 'destaque', 'filer', 'galeria', 'auth', 'facebook', 'paintstore', 'critica', 'disqus', 'fichas', 'omeletop', 'autocomplete_light', 'modelsv1', 'temas', 'django_extensions', 'adv_cache_tag', 'taggit', 'social', 'personalidade']

WHY??

Body:
For me it shows

raise LookupError(message)

LookupError: No installed app with label 'admin'.

and I solve it by pip installing every requirements manually I m using ubuntu 16.04


问:
Error with docker-compose up for Spring Cloud Dataflow - "DATAFLOW_VERSION is not set!"
I am a newbie to spring-cloud-data-flow. I am following the documentation of Spring Cloud Data Flow (https://dataflow.spring.io/docs/installation/local/docker/). I have downloaded docker-compose.yml file and put it in D:\Dev\spring-cloud-dataflow> directory.  When I try to run following commands:

```<code>    D:\Dev\spring-cloud-dataflow> set DATAFLOW_VERSION=2.1.0.RELEASE
    D:\Dev\spring-cloud-dataflow> set SKIPPER_VERSION=2.0.2.RELEASE
    D:\Dev\spring-cloud-dataflow> docker-compose up
</code>```

It gaves me following error:

```<code>    ERROR: Missing mandatory value for "image" option in service "dataflow-server": DATAFLOW_VERSION is not set!
</code>```

I am using Powershell, so I tried to use Set-Variable instead of set, but this gave me the same error.

```<code>    D:\Dev\spring-cloud-dataflow> Set-Variable -Name "DATAFLOW_VERSION" -Value "2.1.0.RELEASE"
    D:\Dev\spring-cloud-dataflow> Set-Variable -Name "SKIPPER_VERSION" -Value "2.0.2.RELEASE"
    D:\Dev\spring-cloud-dataflow> docker-compose up
</code>```

ERROR: Missing mandatory value for "image" option in service "dataflow-server": DATAFLOW_VERSION is not set!

I tried the short handed version in the tutorial but did not worked also:

```<code>    DATAFLOW_VERSION=2.1.0.RELEASE SKIPPER_VERSION=2.0.2.RELEASE docker-compose up
</code>```

I can see the variables are set:

```<code>    D:\Dev\spring-cloud-dataflow> echo $DATAFLOW_VERSION
    2.1.0.RELEASE
    D:\Dev\spring-cloud-dataflow> echo $SKIPPER_VERSION
    2.0.2.RELEASE
</code>```

I could not understand why this error pops up.

答:
Not sure about why it doesn't resolve the variables. Maybe the resolution of the variable doesn't take place in your environment (Windows?).

For the time being, can you set the version values explicitly inside the docker compose yml file and run to see if it sets up correctly?

Body:
I am a newbie to spring-cloud-data-flow. I am following the documentation of Spring Cloud Data Flow (https://dataflow.spring.io/docs/installation/local/docker/). I have downloaded docker-compose.yml file and put it in D:\Dev\spring-cloud-dataflow> directory.  When I try to run following commands:

    D:\Dev\spring-cloud-dataflow> set DATAFLOW_VERSION=2.1.0.RELEASE
    D:\Dev\spring-cloud-dataflow> set SKIPPER_VERSION=2.0.2.RELEASE
    D:\Dev\spring-cloud-dataflow> docker-compose up

It gaves me following error:

    ERROR: Missing mandatory value for "image" option in service "dataflow-server": DATAFLOW_VERSION is not set!

I am using Powershell, so I tried to use Set-Variable instead of set, but this gave me the same error.

    D:\Dev\spring-cloud-dataflow> Set-Variable -Name "DATAFLOW_VERSION" -Value "2.1.0.RELEASE"
    D:\Dev\spring-cloud-dataflow> Set-Variable -Name "SKIPPER_VERSION" -Value "2.0.2.RELEASE"
    D:\Dev\spring-cloud-dataflow> docker-compose up

ERROR: Missing mandatory value for "image" option in service "dataflow-server": DATAFLOW_VERSION is not set!

I tried the short handed version in the tutorial but did not worked also:

    DATAFLOW_VERSION=2.1.0.RELEASE SKIPPER_VERSION=2.0.2.RELEASE docker-compose up

I can see the variables are set:

    D:\Dev\spring-cloud-dataflow> echo $DATAFLOW_VERSION
    2.1.0.RELEASE
    D:\Dev\spring-cloud-dataflow> echo $SKIPPER_VERSION
    2.0.2.RELEASE

I could not understand why this error pops up.


问:
Function not returning the pyspark DataFrame
I have defined a function which returns a dataframe of intersection of all dataframes given as the input. However when I store the output of the function in some variable, it won't get stored in the variable. It is shown as a nonetype object

```<code>def intersection(list1, intersection_df,i):
    if (i == 1):
        intersection_df = list1[0]
        print(type(intersection_df))
        intersection(list1, intersection_df, i+1)
    elif (i>len(list1)):
        print(type(intersection_df))
        a = spark.createDataFrame(intersection_df.rdd)
        a.show()
        return a
    else:
        intersection_df = intersection_df.alias('intersection_df')
        tb = list1[i-1]
        tb = tb.alias('tb')
        intersection_df = intersection_df.join(tb, intersection_df['value'] == tb['value']).where(col('tb.value').isNotNull()).select(['intersection_df.value'])
        print(type(intersection_df))
        intersection(list1, intersection_df, i+1)
</code>```

e.g if I give the input as following,

```<code>list1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
list2 = [3,4,5,6,7,8,9,10,11,12,13,14,15,16]
list3 = [6,7,8,9,10,11,12,13,4,16,343]
df1 = spark.createDataFrame(list1, StringType())
df2 = spark.createDataFrame(list2, StringType())
df3 = spark.createDataFrame(list3, StringType())
list4 = [df1,df2,df3]
empty_df = []
intersection_df = intersection(list4, empty_df, 1)
</code>```

I expect the following output to be stored in interesection_df

```<code> +-----+
 |value|
 +-----+
 | 7   |
 | 11  |
 | 8   |
 | 6   |
 | 9   |
 | 10  |
 | 4   |
 | 12  |
 | 13  |
 +-----+
</code>```

答:
I think you got hit by the curse of recursion.

Problem:

You are calling intersection recursively but returning only in one of the if condition. So when it returns your df, it has no where to go (recall: each function call creates a stack).

Solution:

return when you call intersection from your if and else condition. for ex return intersection(list1, intersection_df, i+1) in your if condition.

Body:
I have defined a function which returns a dataframe of intersection of all dataframes given as the input. However when I store the output of the function in some variable, it won't get stored in the variable. It is shown as a nonetype object

def intersection(list1, intersection_df,i):
    if (i == 1):
        intersection_df = list1[0]
        print(type(intersection_df))
        intersection(list1, intersection_df, i+1)
    elif (i>len(list1)):
        print(type(intersection_df))
        a = spark.createDataFrame(intersection_df.rdd)
        a.show()
        return a
    else:
        intersection_df = intersection_df.alias('intersection_df')
        tb = list1[i-1]
        tb = tb.alias('tb')
        intersection_df = intersection_df.join(tb, intersection_df['value'] == tb['value']).where(col('tb.value').isNotNull()).select(['intersection_df.value'])
        print(type(intersection_df))
        intersection(list1, intersection_df, i+1)

e.g if I give the input as following,

list1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
list2 = [3,4,5,6,7,8,9,10,11,12,13,14,15,16]
list3 = [6,7,8,9,10,11,12,13,4,16,343]
df1 = spark.createDataFrame(list1, StringType())
df2 = spark.createDataFrame(list2, StringType())
df3 = spark.createDataFrame(list3, StringType())
list4 = [df1,df2,df3]
empty_df = []
intersection_df = intersection(list4, empty_df, 1)

I expect the following output to be stored in interesection_df

 +-----+
 |value|
 +-----+
 | 7   |
 | 11  |
 | 8   |
 | 6   |
 | 9   |
 | 10  |
 | 4   |
 | 12  |
 | 13  |
 +-----+


问:
How to get id's based on in between time using MySql
I want to get cubbersId based on in between  time

This is my table: table name cubbersavailability

```<code>+---------------------------------------+
|cubbersId  |   fromTime    |   toTime   |
+---------------------------------------+
|   1       |   09:30:00    |   18:30:00 |
|   1       |   09:30:00    |   18:30:00 |
|   1       |   09:30:00    |   18:30:00 |
|   1       |   09:30:00    |   12:30:00 |
+----------------------------------------+
</code>```

In the above table cubbersIsd have some times.

Conditions

If am choose fromTime as 10:30:00 and toTime as 12:00:00 means get last 1 columns

If am choose fromTime as 08:30:00 and toTime as 16:00:00 means don't select the columns

If am choose fromTime as 10:30:00 and toTime as 20:00:00 means don't select the columns

If am choose fromTime as 08:30:00 and toTime as 20:00:00 means don't select the columns

I tried this query but this not supported:

```<code>SELECT
    c.cubbersId,
    shopAvailTime.fromTime,
    shopAvailTime.toTime
FROM cubbers c
    LEFT JOIN
        (SELECT * FROM cubbersavailability ca WHERE CAST('08:30:00' as time) < ca.toTime AND CAST('12:00:00' as time) > ca.fromTime ) as shopAvailTime ON (c.cubbersId = shopAvailTime.cubbersId)
WHERE c.cubbersId = 1
</code>```

But it get all the list

Note: this question already asked but that not help my question;

答:
```<code>SELECT x.cubbersId
     , x.fromTime
     , x.toTime
  FROM cubbersavailability x
 WHERE '08:30:00' >= x.fromTime
   AND '12:00:00' <= x.toTime
   AND x.cubbersId = 1
</code>```

Body:
I want to get cubbersId based on in between  time

This is my table: table name cubbersavailability

+---------------------------------------+
|cubbersId  |   fromTime    |   toTime   |
+---------------------------------------+
|   1       |   09:30:00    |   18:30:00 |
|   1       |   09:30:00    |   18:30:00 |
|   1       |   09:30:00    |   18:30:00 |
|   1       |   09:30:00    |   12:30:00 |
+----------------------------------------+

In the above table cubbersIsd have some times.

Conditions

If am choose fromTime as 10:30:00 and toTime as 12:00:00 means get last 1 columns

If am choose fromTime as 08:30:00 and toTime as 16:00:00 means don't select the columns

If am choose fromTime as 10:30:00 and toTime as 20:00:00 means don't select the columns

If am choose fromTime as 08:30:00 and toTime as 20:00:00 means don't select the columns

I tried this query but this not supported:

SELECT
    c.cubbersId,
    shopAvailTime.fromTime,
    shopAvailTime.toTime
FROM cubbers c
    LEFT JOIN
        (SELECT * FROM cubbersavailability ca WHERE CAST('08:30:00' as time) < ca.toTime AND CAST('12:00:00' as time) > ca.fromTime ) as shopAvailTime ON (c.cubbersId = shopAvailTime.cubbersId)
WHERE c.cubbersId = 1

But it get all the list

Note: this question already asked but that not help my question;


问:
How to create AutoHotKey which starts script (i.e .bat) using Cmder command line arguments?
I am trying to create an autohotkey which starts a script (i.e .bat):

```<code>#!g::
  Run "Path\To\script\script.bat" debug
  Return
</code>```

The AutoHotKey works properly. However, I would like the .bat to be opened using Cmder instead of the default windows cmd.

I tried to set the Cmder as the default cmd by going to Settings-> Integration -> Default term and by checking the "Force ConEmu as default terminal for console applications", but this did not change anything in my particular case, and the script is still being ran in windows cmd.

答:
In the end I used below script to make it work:

```<code>; Win+Alt+y - Start script
#!y::
Run "d:\cmder\Cmder.exe" "d:\somePath\FolderContainingTheBat\"
sleep 1000
send script.bat debug{enter}

Return
</code>```

EDIT

Another solution for this does not involve AutoHotKey and works only with default windows cmd. I did the following:

Create a .bat file which contains the following

```<code>script.bat debug
</code>```

Create shortcut for the newly created bat file and assign to it a "keyboard shortcut": Right click on the created shortcut -> Properties -> "Shortcut" tab -> Shortcut key

Body:
I am trying to create an autohotkey which starts a script (i.e .bat):

#!g::
  Run "Path\To\script\script.bat" debug
  Return

The AutoHotKey works properly. However, I would like the .bat to be opened using Cmder instead of the default windows cmd.

I tried to set the Cmder as the default cmd by going to Settings-> Integration -> Default term and by checking the "Force ConEmu as default terminal for console applications", but this did not change anything in my particular case, and the script is still being ran in windows cmd.

Body:
In the end I used below script to make it work:

; Win+Alt+y - Start script
#!y::
Run "d:\cmder\Cmder.exe" "d:\somePath\FolderContainingTheBat\"
sleep 1000
send script.bat debug{enter}

Return

EDIT

Another solution for this does not involve AutoHotKey and works only with default windows cmd. I did the following:

Create a .bat file which contains the following

script.bat debug

Create shortcut for the newly created bat file and assign to it a "keyboard shortcut": Right click on the created shortcut -> Properties -> "Shortcut" tab -> Shortcut key


问:
Running unit tests in parallel with pytest?
How can I parallelize the execution of the unit tests written with pytest? Which tactics of parallelism can I choose from?</p>

答:
In order to run pytests in parallel you are going to need to install pytest-xdist. Please see the different  parallelism tactics listed below, you can use any of those (however I can bet that one of those suits best for your particular case):

```<code>pip install pytest-xdist

# The most primitive case, sending tests to multiple CPUs:
pytest -n NUM

# Execute tests within 3 subprocesses.
pytest --dist=each --tx 3*popen//python=python3.6

# Execute tests in 3 forked subprocess. Won't work on windows.
pytest --dist=each --tx 3*popen//python=python3.6 --boxed

# Sending tests to the ssh slaves
pytest --dist=each --tx ssh=first_slave --tx ssh=seconds_slave --rsyncdir package package

# Sending tests to the socket server, link is available below.
python socketserver.py :8889 &
python socketserver.py :8890 &
pytest --dist=each --tx socket=localhost:8889 --tx socket=localhost:8890

</code>```

You can provide different values for --dist(-d) parameter, which handles the way tests are distributed across workers, see documentation for more information regarding the usage of --dist.

NOTE: Once tests are executed the socket_server.py is down. I suggest you running socket server from separate terminal windows for debugging purposes

You can introduce more complicated flows, for instance running tests inside docker containers with have started socket servers kind of "pytest workers" and another docker container which communicates to them and serve as "pytest runner".

Body:
In order to run pytests in parallel you are going to need to install pytest-xdist. Please see the different  parallelism tactics listed below, you can use any of those (however I can bet that one of those suits best for your particular case):

pip install pytest-xdist

# The most primitive case, sending tests to multiple CPUs:
pytest -n NUM

# Execute tests within 3 subprocesses.
pytest --dist=each --tx 3*popen//python=python3.6

# Execute tests in 3 forked subprocess. Won't work on windows.
pytest --dist=each --tx 3*popen//python=python3.6 --boxed

# Sending tests to the ssh slaves
pytest --dist=each --tx ssh=first_slave --tx ssh=seconds_slave --rsyncdir package package

# Sending tests to the socket server, link is available below.
python socketserver.py :8889 &
python socketserver.py :8890 &
pytest --dist=each --tx socket=localhost:8889 --tx socket=localhost:8890

You can provide different values for --dist(-d) parameter, which handles the way tests are distributed across workers, see documentation for more information regarding the usage of --dist.

NOTE: Once tests are executed the socket_server.py is down. I suggest you running socket server from separate terminal windows for debugging purposes

You can introduce more complicated flows, for instance running tests inside docker containers with have started socket servers kind of "pytest workers" and another docker container which communicates to them and serve as "pytest runner".


问:
Building audio programs
I'm on Windows. I’ve been having this problem for months. Maybe I don’t understand the difference between including and linking. I’m overwhelmed by the number of files provided in the Portaudio directory, and sub-directories after auto-building.  I want to be able to build any project using Portaudio, hopefully without relying on an IDE. I want to build the example programs to get used to the build process, and not so much the coding itself. What do I need to do to make this happen? Can I simply include the Portaudio header file, or do I need to build a binary library from the source files, and link to it? Either way I would like to use a Makefile to accomplish these tasks. How would I want to edit my provided Makefile to accomplish either of these tasks? </p>

<p>Makefile </p>

```<code>    CC=gcc

    Include= -Iinclude/portaudio.h
    pink: paex_pink.c $(Include)
        $(CC) -o pink paex_pink.c
</code>```

答:
The answer to the last question is that you should have

```<code>Include := include/portaudio.h
</code>```

"no rule to make target" means Make does not know how to make -Iinclude/portaudio.h

for the other questions, they are too vague and your example too big.

The proper procedure is, that you must show effort before asking question. "Effort" means,  precisely state what the expected behaviour is, and what different behaviour you get. Show what you tried to do, and prepare the smallest possible reproducible example of your problem.

Title: Building audio programs

Body:
I'm on Windows. I’ve been having this problem for months. Maybe I don’t understand the difference between including and linking. I’m overwhelmed by the number of files provided in the Portaudio directory, and sub-directories after auto-building.  I want to be able to build any project using Portaudio, hopefully without relying on an IDE. I want to build the example programs to get used to the build process, and not so much the coding itself. What do I need to do to make this happen? Can I simply include the Portaudio header file, or do I need to build a binary library from the source files, and link to it? Either way I would like to use a Makefile to accomplish these tasks. How would I want to edit my provided Makefile to accomplish either of these tasks?

Makefile

    CC=gcc

    Include= -Iinclude/portaudio.h
    pink: paex_pink.c $(Include)
        $(CC) -o pink paex_pink.c

Body:
The answer to the last question is that you should have

Include := include/portaudio.h

"no rule to make target" means Make does not know how to make -Iinclude/portaudio.h

for the other questions, they are too vague and your example too big.

The proper procedure is, that you must show effort before asking question. "Effort" means,  precisely state what the expected behaviour is, and what different behaviour you get. Show what you tried to do, and prepare the smallest possible reproducible example of your problem.


问:
How change the order of overlapping line in line chart Power BI
When we want to emphasize one line with different color (my case "green"),
set the rest of the lines as "grey" , like below :

But the Problem the grey one which don't want to be emphasized
covering the main line like the arrangement in Power Point "Front" or "Backward"

How to arrange the order of line to decide which one on the top that won't be hidden by another lines ?

答:
Try the following workaround:

move the measure you want to emphasize to the top;

then save and reopen the pbix file (or simply go to another page and then back)

It should now bring the green line to the front.

Users have requested this capability as an explicit feature, but Microsoft hasn't implemented it yet, as far as I know.


问:
Elasticsearch querying number of dates in array matching query
I have documents in the following form

```<code>PUT test_index/_doc/1
{
    "dates" : [
      "2018-07-15T14:12:12",
      "2018-09-15T14:12:12",
      "2018-11-15T14:12:12",
      "2019-01-15T14:12:12",
      "2019-03-15T14:12:12",
      "2019-04-15T14:12:12",
      "2019-05-15T14:12:12"],
    "message" : "hello world"
}
</code>```

How do I query for documents such that there are n number of dates within the dates array falling in between two specified dates?

For example: Find all documents with 3 dates in the dates array falling in between "2018-05-15T14:12:12" and "2018-12-15T14:12:12" -- this should return the above document as "2018-07-15T14:12:12", "2018-09-15T14:12:12" and "2018-11-15T14:12:12" fall between "2018-05-15T14:12:12" and "2018-12-15T14:12:12".

答:
I found my own answer to this, although I'm not sure how efficient it is compared to the other answers:

```<code>GET test_index/_search
{
  "query":{
    "bool" : {
        "filter" : {
          "script" : {
            "script" : {"source":"""
            int count = 0;
            for (int i=0; i<doc['dates'].length; ++i) {
              if (params.first_date < doc['dates'][i].toInstant().toEpochMilli() && doc['dates'][i].toInstant().toEpochMilli() < params.second_date) {
                count += 1;
              }
            }
            if (count >= 2) {
              return true
            } else {
              return false
            }
            """,
            "lang":"painless",
            "params": {
              "first_date": 1554818400000,
              "second_date": 1583020800000
            }
            }
          }
        }
    }
  }
}
</code>```

where the parameters are the two dates in epoch time. I've chosen 2 matches here, but obviously you can generalise to any number.

Body:
I have documents in the following form

PUT test_index/_doc/1
{
    "dates" : [
      "2018-07-15T14:12:12",
      "2018-09-15T14:12:12",
      "2018-11-15T14:12:12",
      "2019-01-15T14:12:12",
      "2019-03-15T14:12:12",
      "2019-04-15T14:12:12",
      "2019-05-15T14:12:12"],
    "message" : "hello world"
}

How do I query for documents such that there are n number of dates within the dates array falling in between two specified dates?

For example: Find all documents with 3 dates in the dates array falling in between "2018-05-15T14:12:12" and "2018-12-15T14:12:12" -- this should return the above document as "2018-07-15T14:12:12", "2018-09-15T14:12:12" and "2018-11-15T14:12:12" fall between "2018-05-15T14:12:12" and "2018-12-15T14:12:12".

Body:
I found my own answer to this, although I'm not sure how efficient it is compared to the other answers:

GET test_index/_search
{
  "query":{
    "bool" : {
        "filter" : {
          "script" : {
            "script" : {"source":"""
            int count = 0;
            for (int i=0; i<doc['dates'].length; ++i) {
              if (params.first_date < doc['dates'][i].toInstant().toEpochMilli() && doc['dates'][i].toInstant().toEpochMilli() < params.second_date) {
                count += 1;
              }
            }
            if (count >= 2) {
              return true
            } else {
              return false
            }
            """,
            "lang":"painless",
            "params": {
              "first_date": 1554818400000,
              "second_date": 1583020800000
            }
            }
          }
        }
    }
  }
}

where the parameters are the two dates in epoch time. I've chosen 2 matches here, but obviously you can generalise to any number.


答:
I don't see a problem with the code except the grouping of the arithmetic operands is incorrect. You want to perform the multiply by 100 on the value from the division previously. So just do below. Further get rid of the if else statements as

```<code>awk -F "|" 'NR > 1 { print ((1 - ($45+$47+$49-_m) / ($44+$46+$48-_n)) *100)} { _n=$44+$46+$48; _m=$45+$47+$49 }'
99.9989
</code>```

Even wit printf(), it needs atleast 3 precision characters to print it without rounding of the value to the next whole number

```<code>awk -F "|" 'NR > 1 { printf "%.3f\n", ((1 - ($45+$47+$49-_m) / ($44+$46+$48-_n)) *100)} { _n=$44+$46+$48; _m=$45+$47+$49 }'
99.999
</code>```

Title: How to subtract some values in different line using awk?

Body:
I have a data that separated by "|". This date is occurs every 15th minutes. What I want to do is to subtract this data and multiply it with 100 but it seems didn't work.

bash-4.2$ cat kresna.txt
2019-05-29 16:48:01||196579|1637589633|0|109423435|101347165|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0||0|0|111|1554983|1554990|0||0|6347782|0|0|0|0|||1637602667|8747|13287295146|283512|1636036853|38771|||326516100|101703893|145340456|6988739|224616616|107247291|7764|101598218|19745231|0
2019-05-29 17:03:01||197446|1637876915|0|109456309|101349847|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0||0|0|111|1552437|1552441|0||0|6336110|0|0|0|0|||1637889948|8747|13290533845|283553|1636326689|38771|||326591972|101734973|145373623|6990480|224660545|107268556|7764|101629298|19748302|0

awk -F "|" '{if(NR>1){print (1 - ($45+$47+$49-_m) / ($44+$46+$48-_n) *100)};_n=$44+$46+$48;_m=$45+$47+$49}' kresna.txt
0.998926

That expected output is to e 99.98

Body:
I don't see a problem with the code except the grouping of the arithmetic operands is incorrect. You want to perform the multiply by 100 on the value from the division previously. So just do below. Further get rid of the if else statements as

awk -F "|" 'NR > 1 { print ((1 - ($45+$47+$49-_m) / ($44+$46+$48-_n)) *100)} { _n=$44+$46+$48; _m=$45+$47+$49 }'
99.9989

Even wit printf(), it needs atleast 3 precision characters to print it without rounding of the value to the next whole number

awk -F "|" 'NR > 1 { printf "%.3f\n", ((1 - ($45+$47+$49-_m) / ($44+$46+$48-_n)) *100)} { _n=$44+$46+$48; _m=$45+$47+$49 }'
99.999


问:
How to add extra hosts entries in helm charts
So i'm deploying my application stack on kubernetes sing helm charts and now i need to add some dependant server ip's and hostnames inside my pods /etc/hosts file so need help on this scenario</p>

答:
As standing in documentation you can add extra hosts to POD by using host aliases feature

Example from docs:

```<code>apiVersion: v1
kind: Pod
metadata:
  name: hostaliases-pod
spec:
  restartPolicy: Never
  hostAliases:
  - ip: "127.0.0.1"
    hostnames:
    - "foo.local"
    - "bar.local"
  - ip: "10.1.2.3"
    hostnames:
    - "foo.remote"
    - "bar.remote"
  containers:
  - name: cat-hosts
    image: busybox
    command:
    - cat
    args:
    - "/etc/hosts"
</code>```

Body:
As standing in documentation you can add extra hosts to POD by using host aliases feature

Example from docs:

apiVersion: v1
kind: Pod
metadata:
  name: hostaliases-pod
spec:
  restartPolicy: Never
  hostAliases:
  - ip: "127.0.0.1"
    hostnames:
    - "foo.local"
    - "bar.local"
  - ip: "10.1.2.3"
    hostnames:
    - "foo.remote"
    - "bar.remote"
  containers:
  - name: cat-hosts
    image: busybox
    command:
    - cat
    args:
    - "/etc/hosts"


问:
My DIVs are working differently since my site was deleted (by my awful Name host) & then re-UL'd
I have a gallery of images on my website. I had to alter a template I used to make it so that gallery showed images horizontally in rows of 3 or 4. I honestly don't recall how I did this, but when my Name host deleted my site recently (don't ask), and & re-UL'd my files, that gallery looked like it did when I first DL'd the template, and now I can't get the rows any longer.

I've tried commenting out some of the DIVs comparing what I have w/a similar mirror site, but I'm not seeing any change. The mirror site I set up differently so it's not as apt as I hoped it would be. Anyway, the gallery has images w/captions, and I've tried rearranging the info but to no avail. My temp fix is some really messy HTML on the actual site (therealitycomics.com -- gallery section, where there are currently just 5 images).

```<code><footer id="footer">
<div class="inner">

<div class="gallery cf">
<div>
<a target="_blank"
href="http://therealitycomics.com/images/Postcard.jpg">
<img src="http://therealitycomics.com/images/Postcard.jpg" alt="The
Reality" width="155" height="220">
</a>
<div>How our Intraverse<br>connects</div>
</div>
<div>
<a target="_blank"
href="http://www.therealitycomics.com/patreon/PK11.jpg">
<img src="http://www.therealitycomics.com/patreon/PK11.jpg" alt="Phantom
Kid layout" width="155" height="220">
</a>
<div>Phantom Kid pg<br>Layout 1</div>
</div>
<div>
<a target="_blank"
href="http://www.therealitycomics.com/patreon/PK11b.jpg">
<img src="http://www.therealitycomics.com/patreon/PK11b.jpg" alt="Phantom
Kid layout" width="155" height="220">
</a>
<div>Phantom Kid pg<br>Layout 2</div>
</div>
</code>```

I'n NOT a coder, I just used a template and figured out what changes I needed to make to build my site, so I'm not so great at the trouble-shooting. And, also, it's been so long, I no longer retain the info I !did! learn.

! So please, when you offer advice, be as basic in your descriptions as possible. =] !

Expected result: Those images would all appear in the same row, each one w/its caption.
Actual result: Each image is a row of its own, with the captions under each one.

The DIVs are causing this, but I don't quite get why they're causing it now but weren't before. I checked my main.css b/c I thought the Footer ID or the DIV class "inner" might be the cause based on definitions in the main.css, but I'm not seeing any width or border definitions that are relevant (to my eye), but ALSO when I remove the DIVs around each image and caption, everything jumps up onto one row. And a new row starts with each new DIV tag.

The site (w/its messed up gallery where I commented out all of the old gallery): TheRealitycomics.com
A URL where you can see it as it was: http://therealitycomics.com/indexB.html (again, this is the page where everything HAD been in rows of 3 or 4 but now is just one long column).

答:
@Janne answer is the best way to do it. But, if you don't want to use .css files (not recomended) you can inline the styles:

How our Intraverse
connects

         ...
         ...

```

With display-flex property you tell the container that it should place elements in a unidimensional way, the dimension is set with the property flex-direction ("row" or "column"). With the property flex-wrap you say the container what to do when one child item exceed his container's size, with wrap value his children jumps to another line.

Property flex-basis only set the size of each child, 25% to get 4 children for each row, 33% to get 3, etc...

Body:
I have a gallery of images on my website. I had to alter a template I used to make it so that gallery showed images horizontally in rows of 3 or 4. I honestly don't recall how I did this, but when my Name host deleted my site recently (don't ask), and & re-UL'd my files, that gallery looked like it did when I first DL'd the template, and now I can't get the rows any longer.

I've tried commenting out some of the DIVs comparing what I have w/a similar mirror site, but I'm not seeing any change. The mirror site I set up differently so it's not as apt as I hoped it would be. Anyway, the gallery has images w/captions, and I've tried rearranging the info but to no avail. My temp fix is some really messy HTML on the actual site (therealitycomics.com -- gallery section, where there are currently just 5 images).

How our Intraverse
connects

Phantom Kid pg
Layout 1

Phantom Kid pg
Layout 2

I'n NOT a coder, I just used a template and figured out what changes I needed to make to build my site, so I'm not so great at the trouble-shooting. And, also, it's been so long, I no longer retain the info I !did! learn.

! So please, when you offer advice, be as basic in your descriptions as possible. =] !

Expected result: Those images would all appear in the same row, each one w/its caption.
Actual result: Each image is a row of its own, with the captions under each one.

The DIVs are causing this, but I don't quite get why they're causing it now but weren't before. I checked my main.css b/c I thought the Footer ID or the DIV class "inner" might be the cause based on definitions in the main.css, but I'm not seeing any width or border definitions that are relevant (to my eye), but ALSO when I remove the DIVs around each image and caption, everything jumps up onto one row. And a new row starts with each new DIV tag.

The site (w/its messed up gallery where I commented out all of the old gallery): TheRealitycomics.com
A URL where you can see it as it was: http://therealitycomics.com/indexB.html (again, this is the page where everything HAD been in rows of 3 or 4 but now is just one long column).

Body:
@Janne answer is the best way to do it. But, if you don't want to use .css files (not recomended) you can inline the styles:

<div class="gallery cf" style="display: flex; flex-wrap: wrap; flex-direction: row;">
    <div style="flex-basis: 25%">
         <a target="_blank" href="http://therealitycomics.com/images/Postcard.jpg">
         <img src="http://therealitycomics.com/images/Postcard.jpg" alt="The Reality" width="155" height="220">
         </a>
        <div>How our Intraverse<br>connects</div>
     </div>
     <div style="flex-basis: 25%"> <!-- Other images -->
         ...
         ...
</div>

With display-flex property you tell the container that it should place elements in a unidimensional way, the dimension is set with the property flex-direction ("row" or "column"). With the property flex-wrap you say the container what to do when one child item exceed his container's size, with wrap value his children jumps to another line.

Property flex-basis only set the size of each child, 25% to get 4 children for each row, 33% to get 3, etc...


问:
Is there a way to simulate a click on an alert in JavaScript?
I have a page with an iframe whose source page is in a separate domain. From time to time, the source page generates an alert. When it does so, it stops what it is doing until the user clicks OK to the alert.

What I would like to do is programmatically click OK on this alert so the source page can get back to being useful. Is this possible?

答:
I highly doubt it. If by separate domain, do you mean one which you have no control over?

If you do have control, you could change the alerts to modal Javascript boxes, which you could control.

OwnerDisplayName: moffdub

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: alex


问:
Javascript error when html passed in JSON packet
I am going mad trying to resolve this issue. I have implemented a Coldfusion Ajax-like File Upload that uploads a file using a hidden frame and then grabs the contents returned by the frame. It is based on this article: http://www.bennadel.com/blog/1244-ColdFusion-jQuery-And-AJAX-File-Upload-Demo.htm

So, everything is working great, EXCEPT when I send back HTML in the data. So, if you look in the code below, I have provided the action page that streams data back to the hidden frame. The first line works, the second line with html does not.

```<code>    <!--- Create the return HTML. Remember, we are going to be treating the BODY of the returned document as if it were a JSON string. --->
    <cfsavecontent variable="strHTML">

        <cfset var sResponse = {} />
        <!--- THIS WORKS --->
        <cfset sResponse = {SUCCESS = true, ERRORS = [], DATA = "Hello World", RETURNID=""} />
        <!--- THIS DOES NOT WORK --->
        <cfset sResponse = {SUCCESS = true, ERRORS = [], DATA = #HtmlEditFormat('<div>Hello World</div>')#", RETURNID=""} />

        <cfoutput>
            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
            <html>
            <head></head>
            <body>#SerializeJSON( sResponse )#</body>
            </html>
        </cfoutput>
    </cfsavecontent>

<!--- Create binary response data. --->
<cfset binResponse = ToBinary( ToBase64( strHTML ) ) />

<!--- Tell the client how much data to expect. --->
<cfheader name="content-length" value="#ArrayLen( binResponse )#" />

<!--- Stream the "plain text" back to the client .--->
<cfcontent type="text/html" variable="#binResponse#" />
</code>```

The javascript for doing all of this is below. The line that it errors on when HTML is passed back is:

// Assuming that our return data is in JSON format, evaluate the body html to get our return data.
var objData = eval( "(" + jBody.html() + ")" );

```<code>//ShareForm Photo Upload Form Process (simulated Ajax)
$(document).ready(function() {
    // Attach an event to the submit method. Instead of submitting the actual form to the primary page, we are going to be submitting the form to a hidden iFrame that we dynamically create.
    $( "#frmShareForm" ).submit(
        function( objEvent ){
            var jThis = $( this );
            var photoUploadAction = $("#photoUploadAction").val();

            // Create a unique name for our iFrame. We can do this by using the tick count from the date.
            var strName = ("uploader" + (new Date()).getTime());

            // Create an iFrame with the given name that does not point to any page - we can use the address "about:blank" to get this to happen.
            var jFrame = $( "<iframe name=\"" + strName + "\" src=\"about:blank\" />" );

            // We now have an iFrame that is not attached to the document. Before we attach it, let's make sure it will not be seen.
            jFrame.css( "display", "none" );

            // Since we submitting the form to the iFrame, we will want to be able to get back data from the form submission.
            // To do this, we will have to set up an event listener for the LOAD event of the iFrame.
            jFrame.load(
                function( objEvent ){
                    // Get a reference to the body tag of the loaded iFrame. We are doing to assume that this element will contain our return data in JSON format.
                    var objUploadBody = window.frames[ strName ].document.getElementsByTagName( "body" )[ 0 ];

                    // Get a jQuery object of the body so that we can have better access to it.
                    var jBody = $( objUploadBody );

                    // Assuming that our return data is in JSON format, evaluate the body html to get our return data.
                    var objData = eval( "(" + jBody.html() + ")" );
                    alert(objData);

                    // A JSON-format struct is returned that will be used to do callback functionality
                    SharePhotoAjaxResponseHandler(objData);

                    // Remove the iFrame from the document. Because FireFox has some issues with "Infinite thinking", let's put a small delay on the frame removal.
                    setTimeout
                    (
                        function()
                        {
                            jFrame.remove();
                        }, 100
                    );
                }
            );

            // Attach to body.
            $( "body:first" ).append( jFrame );

            // Now that our iFrame it totally in place, hook up the frame to post to the iFrame.
            jThis
                .attr( "action",  photoUploadAction)
                .attr( "method", "post" )
                .attr( "enctype", "multipart/form-data" )
                .attr( "encoding", "multipart/form-data" )
                .attr( "target", strName );
    });
});
</code>```

The javascript error I get is usually something like:
"unterminated regular expression literal"

I have also tried removing the SerialiseJson on the CFM page, and the eval in the javascript, which both result in other js errors. I have also tried removing the surrounding html as well as change .html() to .text(), remove the eval() and combinations of all of them. No luck.

Please can someone tell me what the problem is. I know I can't be far off as it works without html.

Thanks

UPDATE: I ran the JSON output that Coldfusion generates through the JSON validator and it failed, due to (from what I can see) the double quotation marks:

```<code>{""RETURNID"":"""",""DATA"":""<div>Hello World<\/div>"",""SUCCESS"":true,""ERRORS"":[]}
</code>```

Now I really don't know why Coldfusion is doing double quotations?? Anyone have any ideas?

答:
The HTML is the response is being interpreted as malformed HTML.
SerializeJSON escapes the "/" in "
" as "<\/div>", causing the HTML parser to see malformed HTML.
On the javascript side, the "/div" looks like a bad regular expression.

For this to work you must force the browser to not interpret the data for you.
Send the data as in script block with a bad type (so browser does not run the script).

In Coldfusion:

```<code><!--- Create the return HTML. Remember, we are going to be treating the BODY of the returned document as if it were a JSON string. --->
<cfsavecontent variable="strHTML">

    <cfset sResponse = {SUCCESS = true, ERRORS = [], DATA = "<div>Hello World</div>", RETURNID=""} />
    <cfoutput>
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html>
        <head></head>
        <body><script id="data" type="json">#SerializeJSON( sResponse )#</script>
        </html>
    </cfoutput>
</cfsavecontent>

<!--- Create binary response data. --->
<cfset binResponse = ToBinary( ToBase64( strHTML ) ) />

<!--- Tell the client how much data to expect. --->
<cfheader name="content-length" value="#ArrayLen( binResponse )#" />

<cfcontent type="text/html" variable="#binResponse#" />
</code>```

In the broswer the json source is found using

```<code>var objUploadBody = window.frames[ strName ].document.getElementById( "data" );

// Get a jQuery object of the body so that we can have better access to it.
var jBody = $( objUploadBody );

// Assuming that our return data is in JSON format, evaluate the body html to get our return data.
var objData = eval( "(" + jBody.html() + ")" );
</code>```

Body:
I am going mad trying to resolve this issue. I have implemented a Coldfusion Ajax-like File Upload that uploads a file using a hidden frame and then grabs the contents returned by the frame. It is based on this article: http://www.bennadel.com/blog/1244-ColdFusion-jQuery-And-AJAX-File-Upload-Demo.htm

So, everything is working great, EXCEPT when I send back HTML in the data. So, if you look in the code below, I have provided the action page that streams data back to the hidden frame. The first line works, the second line with html does not.

    <cfsavecontent variable="strHTML">

        <cfset var sResponse = {} />

        <cfset sResponse = {SUCCESS = true, ERRORS = [], DATA = "Hello World", RETURNID=""} />

        <cfset sResponse = {SUCCESS = true, ERRORS = [], DATA = #HtmlEditFormat('
Hello World
')#", RETURNID=""} />

        <cfoutput>
            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

            #SerializeJSON( sResponse )#

        </cfoutput>
    </cfsavecontent>

<cfset binResponse = ToBinary( ToBase64( strHTML ) ) />

<cfheader name="content-length" value="#ArrayLen( binResponse )#" />

<cfcontent type="text/html" variable="#binResponse#" />

The javascript for doing all of this is below. The line that it errors on when HTML is passed back is:

// Assuming that our return data is in JSON format, evaluate the body html to get our return data.
var objData = eval( "(" + jBody.html() + ")" );

//ShareForm Photo Upload Form Process (simulated Ajax)
$(document).ready(function() {
    // Attach an event to the submit method. Instead of submitting the actual form to the primary page, we are going to be submitting the form to a hidden iFrame that we dynamically create.
    $( "#frmShareForm" ).submit(
        function( objEvent ){
            var jThis = $( this );
            var photoUploadAction = $("#photoUploadAction").val();

            // Create a unique name for our iFrame. We can do this by using the tick count from the date.
            var strName = ("uploader" + (new Date()).getTime());

            // Create an iFrame with the given name that does not point to any page - we can use the address "about:blank" to get this to happen.
            var jFrame = $( "" );

            // We now have an iFrame that is not attached to the document. Before we attach it, let's make sure it will not be seen.
            jFrame.css( "display", "none" );

            // Since we submitting the form to the iFrame, we will want to be able to get back data from the form submission.
            // To do this, we will have to set up an event listener for the LOAD event of the iFrame.
            jFrame.load(
                function( objEvent ){
                    // Get a reference to the body tag of the loaded iFrame. We are doing to assume that this element will contain our return data in JSON format.
                    var objUploadBody = window.frames[ strName ].document.getElementsByTagName( "body" )[ 0 ];

                    // Get a jQuery object of the body so that we can have better access to it.
                    var jBody = $( objUploadBody );

                    // Assuming that our return data is in JSON format, evaluate the body html to get our return data.
                    var objData = eval( "(" + jBody.html() + ")" );
                    alert(objData);

                    // A JSON-format struct is returned that will be used to do callback functionality
                    SharePhotoAjaxResponseHandler(objData);

                    // Remove the iFrame from the document. Because FireFox has some issues with "Infinite thinking", let's put a small delay on the frame removal.
                    setTimeout
                    (
                        function()
                        {
                            jFrame.remove();
                        }, 100
                    );
                }
            );

            // Attach to body.
            $( "body:first" ).append( jFrame );

            // Now that our iFrame it totally in place, hook up the frame to post to the iFrame.
            jThis
                .attr( "action",  photoUploadAction)
                .attr( "method", "post" )
                .attr( "enctype", "multipart/form-data" )
                .attr( "encoding", "multipart/form-data" )
                .attr( "target", strName );
    });
});

The javascript error I get is usually something like:
"unterminated regular expression literal"

I have also tried removing the SerialiseJson on the CFM page, and the eval in the javascript, which both result in other js errors. I have also tried removing the surrounding html as well as change .html() to .text(), remove the eval() and combinations of all of them. No luck.

Please can someone tell me what the problem is. I know I can't be far off as it works without html.

Thanks

UPDATE: I ran the JSON output that Coldfusion generates through the JSON validator and it failed, due to (from what I can see) the double quotation marks:

{""RETURNID"":"""",""DATA"":""
Hello World<\/div>"",""SUCCESS"":true,""ERRORS"":[]}

Now I really don't know why Coldfusion is doing double quotations?? Anyone have any ideas?

Body:
The HTML is the response is being interpreted as malformed HTML.
SerializeJSON escapes the "/" in "</div>" as "<\/div>", causing the HTML parser to see malformed HTML.
On the javascript side, the "/div" looks like a bad regular expression.

For this to work you must force the browser to not interpret the data for you.
Send the data as in script block with a bad type (so browser does not run the script).

In Coldfusion:

<!--- Create the return HTML. Remember, we are going to be treating the BODY of the returned document as if it were a JSON string. --->
<cfsavecontent variable="strHTML">

    <cfset sResponse = {SUCCESS = true, ERRORS = [], DATA = "<div>Hello World</div>", RETURNID=""} />
    <cfoutput>
        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html>
        <head></head>
        <body><script id="data" type="json">#SerializeJSON( sResponse )#</script>
        </html>
    </cfoutput>
</cfsavecontent>

<!--- Create binary response data. --->
<cfset binResponse = ToBinary( ToBase64( strHTML ) ) />

<!--- Tell the client how much data to expect. --->
<cfheader name="content-length" value="#ArrayLen( binResponse )#" />

<cfcontent type="text/html" variable="#binResponse#" />

In the broswer the json source is found using

var objUploadBody = window.frames[ strName ].document.getElementById( "data" );

// Get a jQuery object of the body so that we can have better access to it.
var jBody = $( objUploadBody );

// Assuming that our return data is in JSON format, evaluate the body html to get our return data.
var objData = eval( "(" + jBody.html() + ")" );


问:
When can java.nio.buffer.flip() throw NullPointerException?
I have a multithreaded application where the code is trying to read data from a File and then persist it in ByteBuffer via FileChannel.

It works fine for most of the time but sometimes fails with

```<code>java.util.concurrent.ExecutionException: java.lang.NullPointerException
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
</code>```

I found that this exception occurs during buffer.flip(). Here flip is done before reading the data from buffer.

Code snippet

```<code>buffer.clear();
int count = channel.read(buffer, position);
buffer.flip();
</code>```

So wanted to know in which scenario this occurs? Is it because some data might be null in file which is causing this issue or it is something related to multithread?

答:
Unless you have a funky custom subclass of Buffer, the flip method just changes 3 integer valued fields of the XxxBuffer object.   That can't generate an NPE, even if there are threading or memory coherency issues.

This means that the NPE must be happening because you are invoking flip() on a null reference.

Is it because some data might be null in file which is causing this issue or it is something related to multi-threading?

No and no.

UPDATE

```<code>buffer.clear();
int count = channel.read(buffer, position);
buffer.flip();
</code>```

If buffer was already null, you would get an NPE in the first line.  Otherwise, the only way that buffer.flip() is causing an NPE is if some other thread modifies1 the buffer variable.

1 - The modification could happen while this thread is blocked in read, or it could conceivably happen before then if this is a memory coherency problem.  For example, if it is caused by delayed flushing of writes made by another thread.

Body:
I have a multithreaded application where the code is trying to read data from a File and then persist it in ByteBuffer via FileChannel.

It works fine for most of the time but sometimes fails with

java.util.concurrent.ExecutionException: java.lang.NullPointerException
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)

I found that this exception occurs during buffer.flip(). Here flip is done before reading the data from buffer.

Code snippet

buffer.clear();
int count = channel.read(buffer, position);
buffer.flip();

So wanted to know in which scenario this occurs? Is it because some data might be null in file which is causing this issue or it is something related to multithread?

Body:
Unless you have a funky custom subclass of Buffer, the flip method just changes 3 integer valued fields of the XxxBuffer object.   That can't generate an NPE, even if there are threading or memory coherency issues.

This means that the NPE must be happening because you are invoking flip() on a null reference.

Is it because some data might be null in file which is causing this issue or it is something related to multi-threading?

No and no.

UPDATE

buffer.clear();
int count = channel.read(buffer, position);
buffer.flip();

If buffer was already null, you would get an NPE in the first line.  Otherwise, the only way that buffer.flip() is causing an NPE is if some other thread modifies1 the buffer variable.

1 - The modification could happen while this thread is blocked in read, or it could conceivably happen before then if this is a memory coherency problem.  For example, if it is caused by delayed flushing of writes made by another thread.


问:
Google App Maker: Can't associate draft record with record in draft datasource
I have two related tables. This is a relationship where parent can have zero or many notes. I am trying to save a note that's related to original record. Code itself is

```<code>  app.datasources.RadiosManualSave.load(function() {
    ...
    var existingRecord = app.datasources.RadiosManualSave.item;
    ... // update some fields of the existingRecord & save later
    try {
      app.datasources.RadiosManualSave.saveChanges(function() {

        var notesCreate = app.datasources.RadioNotes.modes.create ;
        var newNote = notesCreate.item ;
        newNote.Notes = tempRecord.Notes ;
        //newNote.Radios_fk = existingRecord.Id ;
        newNote.Radios = existingRecord ;

        notesCreate.createItem(function() {
          app.showPage(app.pages.Radios);
        });
      });
   } catch(e) {
        showSnackbar('Error saving record');
        app.datasources.RadiosManualSave.clearChanges();
   }
   ...
}
</code>```

The code fails when I associate the note with the existing record.

The error message is:

Can't associate draft record with record in draft datasource.

However existing record is not in draft datasource and is already in the table. Assigning to the foreign key works without problems.

答:
I had a similar issue where I had two related tables i.e. Employee and Attendance. Employee could have many Attendance. So when creating an Attendance I had to specify the Employee. On selecting the Employee from drop-down to associate it with Attendance, there would be the same error saying:

Can't associate draft record with record in draft datasource.

Nothing really actually worked. Going through the documentation I found some information about draft records
Draft Record

So setting my parent datasource(Employee) to automatic save mode actually did the work.

Body:
I have two related tables. This is a relationship where parent can have zero or many notes. I am trying to save a note that's related to original record. Code itself is

  app.datasources.RadiosManualSave.load(function() {
    ...
    var existingRecord = app.datasources.RadiosManualSave.item;
    ... // update some fields of the existingRecord & save later
    try {
      app.datasources.RadiosManualSave.saveChanges(function() {

        var notesCreate = app.datasources.RadioNotes.modes.create ;
        var newNote = notesCreate.item ;
        newNote.Notes = tempRecord.Notes ;
        //newNote.Radios_fk = existingRecord.Id ;
        newNote.Radios = existingRecord ;

        notesCreate.createItem(function() {
          app.showPage(app.pages.Radios);
        });
      });
   } catch(e) {
        showSnackbar('Error saving record');
        app.datasources.RadiosManualSave.clearChanges();
   }
   ...
}

The code fails when I associate the note with the existing record.

The error message is:

Can't associate draft record with record in draft datasource.

However existing record is not in draft datasource and is already in the table. Assigning to the foreign key works without problems.