问:
Is it possible to turn off antialiasing when using ImageBrush tiling?
Is it possible to turn off anti-aliasing in WPF when using an ImageBrush?

Given the following code:

```<code>var handleImage = new BitmapImage(new Uri($"pack://application:,,,/Resources/myimage.png"));
var imageBrush = new ImageBrush(handleImage);
imageBrush.AlignmentY = AlignmentY.Top;
imageBrush.AlignmentX = AlignmentX.Left;
imageBrush.Stretch = Stretch.Uniform;
imageBrush.Viewport = new Rect(0, 0, _handleImage.Width, _handleImage.Height);
imageBrush.ViewportUnits = BrushMappingMode.Absolute;
imageBrush.TileMode = TileMode.Tile;
drawingContext.DrawRectangle(imageBrush, null, new Rect(0, 0, width, height));
</code>```

Gives me something like:

But I'm expecting:

WPF's default antialiasing makes it look terrible. I've tried UseLayoutRounding=true, SnapsToDevicePixels=true, RenderOptions.SetBitmapScalingMode(this, BitmapScalingMode.HighQuality),
RenderOptions.SetBitmapScalingMode(this, BitmapScalingMode.NearestNeighbor) RenderOptions.SetEdgeMode(this, EdgeMode.Unspecified); on the window. The only one that changes any visual difference is BitmapScalingMode.NearestNeighbor however it still looks odd and the tiling overlaps itself.

EDIT: Download full working sample: WpfImageBrushExample.zip

答:
The problem here was that the BitmapImage width and height were different fractional numbers - in this case it was 5.333 x 6x666 instead of the expected 4 x 5 pixels. If I use _handleImage.PixelWidth and _handleImage.PixelHeight the problem is fixed and I don't get weird aliasing under any of those rendering options set.

var handleImage = new BitmapImage(new Uri($"pack://application:,,,/Resources/myimage.png"));
var imageBrush = new ImageBrush(handleImage);
imageBrush.AlignmentY = AlignmentY.Top;
imageBrush.AlignmentX = AlignmentX.Left;
imageBrush.Stretch = Stretch.Uniform;
imageBrush.Viewport = new Rect(0, 0, _handleImage.PixelWidth, _handleImage.PixelHeight);
imageBrush.ViewportUnits = BrushMappingMode.Absolute;
imageBrush.TileMode = TileMode.Tile;
drawingContext.DrawRectangle(imageBrush, null, new Rect(0, 0, width, height));
```

Produces:

Body:
Is it possible to turn off anti-aliasing in WPF when using an ImageBrush?

Given the following code:

var handleImage = new BitmapImage(new Uri($"pack://application:,,,/Resources/myimage.png"));
var imageBrush = new ImageBrush(handleImage);
imageBrush.AlignmentY = AlignmentY.Top;
imageBrush.AlignmentX = AlignmentX.Left;
imageBrush.Stretch = Stretch.Uniform;
imageBrush.Viewport = new Rect(0, 0, _handleImage.Width, _handleImage.Height);
imageBrush.ViewportUnits = BrushMappingMode.Absolute;
imageBrush.TileMode = TileMode.Tile;
drawingContext.DrawRectangle(imageBrush, null, new Rect(0, 0, width, height));

Gives me something like:

But I'm expecting:

WPF's default antialiasing makes it look terrible. I've tried UseLayoutRounding=true, SnapsToDevicePixels=true, RenderOptions.SetBitmapScalingMode(this, BitmapScalingMode.HighQuality),
RenderOptions.SetBitmapScalingMode(this, BitmapScalingMode.NearestNeighbor) RenderOptions.SetEdgeMode(this, EdgeMode.Unspecified); on the window. The only one that changes any visual difference is BitmapScalingMode.NearestNeighbor however it still looks odd and the tiling overlaps itself.

EDIT: Download full working sample: WpfImageBrushExample.zip

Body:
The problem here was that the BitmapImage width and height were different fractional numbers - in this case it was 5.333 x 6x666 instead of the expected 4 x 5 pixels. If I use _handleImage.PixelWidth and _handleImage.PixelHeight the problem is fixed and I don't get weird aliasing under any of those rendering options set.

var handleImage = new BitmapImage(new Uri($"pack://application:,,,/Resources/myimage.png"));
var imageBrush = new ImageBrush(handleImage);
imageBrush.AlignmentY = AlignmentY.Top;
imageBrush.AlignmentX = AlignmentX.Left;
imageBrush.Stretch = Stretch.Uniform;
imageBrush.Viewport = new Rect(0, 0, _handleImage.PixelWidth, _handleImage.PixelHeight);
imageBrush.ViewportUnits = BrushMappingMode.Absolute;
imageBrush.TileMode = TileMode.Tile;
drawingContext.DrawRectangle(imageBrush, null, new Rect(0, 0, width, height));

Produces:


来源: stackexchange

问:
Why does one variable get the same value as another value
So the function "thinkOfANumber" gives the variable "x" the value 108. Then, we go in to the function "mindReading" that has the variable "secrets" which isn't given any value. But somehow it get the same value as "x". My guess is that it has something to do with the stack and memory. Could someone explain it for me?

The code:

```<code>void thinkOfANumber(){
    int x = 108;
    printf( "This function thinks of a secret number (%d)\n", x);
}

void mindReading(){
    int secret;
    printf( "This function believes that the other functions secret is: %d!\n", secret); //Prints 108
}

void main(){
    thinkOfANumber();
    mindReading();
    return 0;
}

</code>```

答:
Reading from a default initialized int is undefined behavior, since it has an indeterminate value.

When reading from secret, the compiler might be reading the value from a register that just happened to be holding the value of x.

In any case, this is not behavior that you can rely upon, even on the same machine, with the same compiler, with the same compilation flags, etc.

ContentLicense: CC BY-SA 4.0

Body:
So the function "thinkOfANumber" gives the variable "x" the value 108. Then, we go in to the function "mindReading" that has the variable "secrets" which isn't given any value. But somehow it get the same value as "x". My guess is that it has something to do with the stack and memory. Could someone explain it for me?

The code:

void thinkOfANumber(){
    int x = 108;
    printf( "This function thinks of a secret number (%d)\n", x);
}

void mindReading(){
    int secret;
    printf( "This function believes that the other functions secret is: %d!\n", secret); //Prints 108
}

void main(){
    thinkOfANumber();
    mindReading();
    return 0;
}


问:
How to run an async task for every x mins in android?
how to run the async task at specific time? (I want to run it every 2 mins)

I tried using  post delayed but it's not working?

```<code>    tvData.postDelayed(new Runnable(){

    @Override
    public void run() {
        readWebpage();

    }}, 100);
</code>```

In the above code readwebpage is function which calls the async task for me..

Right now below is the method which I am using

```<code>   public void onCreate(Bundle savedInstanceState) {

         readwebapage();

   }

   public void readWebpage() {
    DownloadWebPageTask task = new DownloadWebPageTask();
    task.execute("http://www.google.com");

   }

   private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        String response1 = "";
        response1=read();
                   //read is my another function which does the real work
        response1=read();
        super.onPostExecute(response1);
        return response1;
    }

      protected void onPostExecute(String result) {

         try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            TextView tvData = (TextView) findViewById(R.id.TextView01);
            tvData.setText(result);

        DownloadWebPageTask task = new DownloadWebPageTask();
        task.execute(new String[] { "http://www.google.com" });

    }

    }
</code>```

This is what I  my code is and it works perfectly fine but the big problem I drains my battery?

答:
Use Handler and PostDelayed:

```<code>final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
        readWebpage();
        handler.postDelayed(this, 120000); //now is every 2 minutes
    }
 }, 120000); //Every 120000 ms (2 minutes)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
how to run the async task at specific time? (I want to run it every 2 mins)

I tried using  post delayed but it's not working?

    tvData.postDelayed(new Runnable(){

    @Override
    public void run() {
        readWebpage();

    }}, 100);

In the above code readwebpage is function which calls the async task for me..

Right now below is the method which I am using

   public void onCreate(Bundle savedInstanceState) {

         readwebapage();

   }

   public void readWebpage() {
    DownloadWebPageTask task = new DownloadWebPageTask();
    task.execute("http://www.google.com");

   }

   private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        String response1 = "";
        response1=read();
                   //read is my another function which does the real work
        response1=read();
        super.onPostExecute(response1);
        return response1;
    }

      protected void onPostExecute(String result) {

         try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            TextView tvData = (TextView) findViewById(R.id.TextView01);
            tvData.setText(result);

        DownloadWebPageTask task = new DownloadWebPageTask();
        task.execute(new String[] { "http://www.google.com" });

    }

    }

This is what I  my code is and it works perfectly fine but the big problem I drains my battery?

Body:
Use Handler and PostDelayed:

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
        readWebpage();
        handler.postDelayed(this, 120000); //now is every 2 minutes
    }
 }, 120000); //Every 120000 ms (2 minutes)


问:
Using D3.select to change the thickness of text in a radial dendrogram with a mouseover
With assistance, I've uncovered the way to change elements in a radial dendrogram.
The lines below perform that function.
However, I'm trying to guess at what I need to bold text with the same mouse over.  Can someone tell me what I'm missing?

// responsible for changing the style and type of the nodes when mousing over them

```<code>d3.selectAll('g.node').attr("id", function(d,i){ return "node"+i});
d3.selectAll('path.link').attr("id", function(d,i){ return "link"+i}); //my guess is on the line
below
d3.selectAll('text').attr("id", function(d,i){ return "text"+i});
</code>```

// still trying to figure out how to make the text bold on mouse over

```<code>   d3.selectAll('g.node').each(function(d, i) {
   d3.select('#node'+i).on("mouseover", function() {
   d3.select('#link'+(i-1))
   .attr('style','stroke-width: 4px','style','font-weight: bold');  // my 2nd guess is on the next
line
   d3.select('text').attr("font-weight",function(d,i) {return i*800+800;});
</code>```

}).on("mouseout", function() {
       d3.select('#link'+(i-1)).attr('style', 'stroke-width: 1.5px','stroke-opacity: 0.4','stroke:
    #555');
   });
   });

答:
In order to set font-weight - which is a CSS property -, .style should be used instead of .attr:

```<code>d3.select('#link'+(i-1))
   .style('font-weight','bold');
</code>```

Useful reference: modifying elements with d3-selection.

Body:
With assistance, I've uncovered the way to change elements in a radial dendrogram.
The lines below perform that function.
However, I'm trying to guess at what I need to bold text with the same mouse over.  Can someone tell me what I'm missing?

// responsible for changing the style and type of the nodes when mousing over them

d3.selectAll('g.node').attr("id", function(d,i){ return "node"+i});
d3.selectAll('path.link').attr("id", function(d,i){ return "link"+i}); //my guess is on the line
below
d3.selectAll('text').attr("id", function(d,i){ return "text"+i});

// still trying to figure out how to make the text bold on mouse over

   d3.selectAll('g.node').each(function(d, i) {
   d3.select('#node'+i).on("mouseover", function() {
   d3.select('#link'+(i-1))
   .attr('style','stroke-width: 4px','style','font-weight: bold');  // my 2nd guess is on the next
line
   d3.select('text').attr("font-weight",function(d,i) {return i*800+800;});

}).on("mouseout", function() {
       d3.select('#link'+(i-1)).attr('style', 'stroke-width: 1.5px','stroke-opacity: 0.4','stroke:
    #555');
   });
   });

Body:
In order to set font-weight - which is a CSS property -, .style should be used instead of .attr:

d3.select('#link'+(i-1))
   .style('font-weight','bold');

Useful reference: modifying elements with d3-selection.


问:
Hook to listen when RN screen changes (when navigation is called)
Using react-native navigation:
https://reactnavigation.org/docs/use-navigation/

is there a way to listen for when the view/screen changes? When nav.navigate() is called?
We could create our own wrapper and then call the hooks ourselves, but I am wonder if there is a built-in way to listen for changes to the view/screen? The goal is hide the snackbar if it's being displayed, if the user navigates.

答:
You have two ways to listen to screen changes:

Subscribe to state changes, you can read more here

Using the onStateChange prop of the NavigationContainer, you can read more here

You could do your checks there and hide the snackbar whenever you want. The advantage it has over wrapping the useNavigation hook is that it will work not only with your custom hook but also with the navigation prop passed to all the screens within your navigator.


问:
How to resolve branches when git diff .. returns nothing but git diff ... returns changes?
I think my master and release branches somehow diverged and I'm wondering what the best way to bring them back in sync is.

I have a master branch which is supposed to be used for development, but then I'll merge this master branch into a release branch to create final builds that can be deployed. It was working fine, but as of a week ago, whenever I try to create a pull request merging from master into release, I get a list of commits that should've already been in release. I'll merge the PR, but this keeps happening with every new PR trying to merge from master to release.

I tried looking at changes to make sure both branches are identical

git diff upstream/master..upstream/release gives me no diffs.

git diff upstream/release..upstream/master also gives me no diffs.

However git diff upstream/master...upstream/release gives me the changes from all the commits since the one that probably diverged my two branches.

I think what might be happening is that my two branches are identical in raw code, but they have different commits? I'm still taking classes on git and how to use it more effectively so any help would be greatly appreciated!

答:
TIL : git diff has a different interpretation of .. and ... from git log.

git diff a..b (two dots) is the same as git diff a b

git diff a...b (three dots) compares the merge base of a and b to b

See the docs, the "Description" section.

Run : git log --oneline --graph upstream/master upstream/release, you will view how the commits are laid out.

Your two dots diff command indeed shows you that the two branches have the same content.

The "merge base" is the forking point between the two branches, what you see in your three dots diff is the diff between that commit and the head commit of the branch.


问:
How to detect and combine elements in a vector in R?
I have a data list including many elements of which I only need the columns 'interval..s' (bout duration) and 'ActivityCode'(0 to 5), see picture (datalist).
I try to extract all 0 and 5 in the column 'ActivityCode' with their corresponding value from the column 'interval..s'.

I already wrote a code to extract the bout durations (from column 'interval..s') with an activity code 0 and 5, but bout durations should be summed when 0 and 5 are two consecutive bouts

```<code>setwd("/Users/lucp9693/Desktop/csvfolder")
mydir = "csvfolder"
myfiles = list.files(path = mydir, pattern = ".csv",full.names = TRUE)
setwd("/Users/lucp9693/Desktop/csvfolder")
list.files(pattern = ".csv$")
list.filenames = list.files(pattern = ".csv$")
list.data = list()
ind = 0
result = vector("numeric",length(list.filenames))
for(i in 1:length(list.filenames))
{
  ind = ind +1
  list.data[[i]] = read.csv(list.filenames[i])
  document = read.csv(list.filenames[i],header = TRUE, sep = ",")
  W = document$Interval..s.[bestand$ActivityCode..0.sedentary.1.standing.2.stepping.2.1.cycling.3.1.primary.lying..3.2.secondary.lying.4.non.wear.5.travelling.==0]
</code>```

It there any possibility to do this? Thanks!

答:
Here's my reading of your question (with some sample data):

```<code>library(dplyr)
library(tidyr)
library(tibble)

data <- tibble(
  Interval = round(runif(n = 100, min = 1, max = 1000), 1),
  ActivityCode = round(runif(n = 100, min = 0, max = 5),0)
)

data <- data %>%
  filter(ActivityCode == 0 | ActivityCode == 5) %>%
  mutate(sum = ifelse(ActivityCode == lag(ActivityCode, 1),Interval + lag(Interval, 1), Interval))
</code>```

I remove all lines except those with an ActivityCode of 0 and 5. If there are adjacent or consecutive occurrences of either 0 or 5 the two adjacent Intervals are summed.
With this output:

```<code>> print.data.frame(data)
   Interval ActivityCode    sum
1      87.1            0     NA
2      38.7            0  125.8
3     843.1            5  843.1
4     680.6            5 1523.7
5     151.3            5  831.9
6      37.8            0   37.8
7     539.6            0  577.4
8     978.6            5  978.6
9     140.0            5 1118.6
10    145.1            5  285.1
11    252.5            0  252.5
12     90.0            0  342.5
13    588.8            5  588.8
14    459.1            0  459.1
</code>```

Was this what you were after?

Body:
I have a data list including many elements of which I only need the columns 'interval..s' (bout duration) and 'ActivityCode'(0 to 5), see picture (datalist).
I try to extract all 0 and 5 in the column 'ActivityCode' with their corresponding value from the column 'interval..s'.

I already wrote a code to extract the bout durations (from column 'interval..s') with an activity code 0 and 5, but bout durations should be summed when 0 and 5 are two consecutive bouts

setwd("/Users/lucp9693/Desktop/csvfolder")
mydir = "csvfolder"
myfiles = list.files(path = mydir, pattern = ".csv",full.names = TRUE)
setwd("/Users/lucp9693/Desktop/csvfolder")
list.files(pattern = ".csv$")
list.filenames = list.files(pattern = ".csv$")
list.data = list()
ind = 0
result = vector("numeric",length(list.filenames))
for(i in 1:length(list.filenames))
{
  ind = ind +1
  list.data[[i]] = read.csv(list.filenames[i])
  document = read.csv(list.filenames[i],header = TRUE, sep = ",")
  W = document$Interval..s.[bestand$ActivityCode..0.sedentary.1.standing.2.stepping.2.1.cycling.3.1.primary.lying..3.2.secondary.lying.4.non.wear.5.travelling.==0]

It there any possibility to do this? Thanks!

Body:
Here's my reading of your question (with some sample data):

library(dplyr)
library(tidyr)
library(tibble)

data <- tibble(
  Interval = round(runif(n = 100, min = 1, max = 1000), 1),
  ActivityCode = round(runif(n = 100, min = 0, max = 5),0)
)

data <- data %>%
  filter(ActivityCode == 0 | ActivityCode == 5) %>%
  mutate(sum = ifelse(ActivityCode == lag(ActivityCode, 1),Interval + lag(Interval, 1), Interval))

I remove all lines except those with an ActivityCode of 0 and 5. If there are adjacent or consecutive occurrences of either 0 or 5 the two adjacent Intervals are summed.
With this output:

> print.data.frame(data)
   Interval ActivityCode    sum
1      87.1            0     NA
2      38.7            0  125.8
3     843.1            5  843.1
4     680.6            5 1523.7
5     151.3            5  831.9
6      37.8            0   37.8
7     539.6            0  577.4
8     978.6            5  978.6
9     140.0            5 1118.6
10    145.1            5  285.1
11    252.5            0  252.5
12     90.0            0  342.5
13    588.8            5  588.8
14    459.1            0  459.1

Was this what you were after?


问:
`tf.data.Dataset` runs on CPU, except of `PrefetchDataset`?
After reading through the tf.data documentation (here for TF 1.15), related TF code (both Python and C++), I realized that most of it seems to run purely on CPU, except of PrefetchDataset.

Is that true?

The documentation for prefetch_to_device says:

NOTE: Although the transformation creates a tf.data.Dataset, the
  transformation must be the final Dataset in the input pipeline.

Which suggest that all other datasets cannot handle such a GPU-based dataset.

While looking through the code, there seems to be some internal datasets, e.g. _CopyToDeviceDataset and _MapOnGpuDataset, which might handle GPU datasets.

If I want to have my preprocessing (e.g. data augmentation, some other clever non-trivial stuff) on GPU, that means that I cannot use tf.data? (I also want to use graph mode, but not sure if that is relevant.)

Now I also found _GeneratorDataset. That kernel also is defined on GPU. So that means that if my next_func returns a tensor on GPU, it will always stay on GPU?

答:
You are correct, tf.data currently does all of its processing on CPU. Usually this is desirable to avoid contending with the GPU, and because much preprocessing is easier to implement on the CPU. However, there isn't anything fundamentally preventing tf.data from doing processing on the GPU - it's just a matter of implementing such support. From the looks of it, map_on_gpu does offer a way to apply a map function on GPU, though map_on_gpu isn't yet exported in the public API. If you're interested in such functionality, please create a Github Issue describing your use case

To answer your last question, if you have a _GeneratorDataset which is placed on GPU, the tensors it produces will also be on GPU. However, you cannot apply additional dataset transformations other than prefetch because those dataset transformations don't have GPU implementations.


问:
Determining the number of decimal numbers for a currency
On the iPhone:

```
Using the US locale, a currency looks like this: $1,234.56
Using the UK locale, a currency looks like this: £1,234.56
Using the German (Germany) locale, a currency looks like this: 1.234,56 €

and finally, a Japanese currency: ¥1,234
```

The Japanese currency has no decimals and this impacts my custom keyboard significantly. I'm trying to find a method in the Cocoa-touch framework which will tell me how many decimal places a specific currency has - my hard-coded value of 2 isn't doing me justice :(

Can anyone help?

答:
I had a similar problem but the answers above didn't really solve my problem.

I ended up using the maximumFractionDigits method on NSNumberFormatter which gave me 0 for Japanese locale. Make sure you use a NSNumberFormatterCurrencyStyle for the formatter, otherwise you'll see decimal places in other formatters.

```<code>    NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
    [currencyFormatter setLocale:[NSLocale currentLocale]];
    [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

    NSLog(@"Number of decimal places %i", [currencyFormatter maximumFractionDigits]);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
On the iPhone:

Using the US locale, a currency looks like this: $1,234.56
Using the UK locale, a currency looks like this: £1,234.56
Using the German (Germany) locale, a currency looks like this: 1.234,56 €

and finally, a Japanese currency: ¥1,234

The Japanese currency has no decimals and this impacts my custom keyboard significantly. I'm trying to find a method in the Cocoa-touch framework which will tell me how many decimal places a specific currency has - my hard-coded value of 2 isn't doing me justice :(

Can anyone help?

Body:
I had a similar problem but the answers above didn't really solve my problem.

I ended up using the maximumFractionDigits method on NSNumberFormatter which gave me 0 for Japanese locale. Make sure you use a NSNumberFormatterCurrencyStyle for the formatter, otherwise you'll see decimal places in other formatters.

    NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
    [currencyFormatter setLocale:[NSLocale currentLocale]];
    [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

    NSLog(@"Number of decimal places %i", [currencyFormatter maximumFractionDigits]);


问:
How to transform list of hierarchyid into a binary tree
I am working on a multi-level marketing (binary) which looks like this:

(but the binary tree is not required to be perfect. A node can have 0-2 child)

My problem is the data that I fetch from the database is flat list.

Notice that I am using hierarchyid (sql server 2014)

Basically the TextNode column is like a breadcrumb.

every slash / represents a level.

If I have TextNode of /1/ as root. then every node that starts with /1/ belongs to that root which are /1/, /1/1/ and /1/1/1/ (the root node is included which will be the level 0)

I've tried the accepted answer in this question but its not working.

How can I transform the flatlist to a Binary Tree so that I can easily traverse and display it on a screen?

Im using C#, ASP MVC 5, SQL Server 2014 if it matters.

答:
I implement exactly this code According to Alex implementation but as is mentioned in some case it didn't work correctly .. have a look to my Image and my code (which copied from Alex post) [data in the database are correct but in tree view seems some problems ]

```<code>public class Row : IRow<string>
{
    public string TextNode { get; }
    public string Value { get; }
    public long Id { get; }
    public string FIN { get; }
    public Row(string textNode, string userName, long id, string fin)
    {
        FIN = fin;
        Id = id;
        TextNode = textNode;
        Value = userName;
    }
}

public interface IRow<out T>
{
    string TextNode { get; }
    long Id { get; }
    string FIN { get; }
    T Value { get; }
}

public class TreeNode<T>
{
    private struct NodeDescriptor
    {
        public int Level { get; }
        public int ParentIndex { get; }

        public NodeDescriptor(IRow<T> row)
        {
            var split = row.TextNode.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
            Level = split.Length;
            ParentIndex = split.Length > 1 ? int.Parse(split[split.Length - 2]) - 1 : 0;
        }
    }
    public T title { get; }
    public long Id { get; }
    public string FIN { get; }
    public List<TreeNode<T>> children { get; }

    private TreeNode(T value, long id, string fin)
    {
        Id = id;
        FIN = fin;
        title = value;
        children = new List<TreeNode<T>>();
    }

    public static TreeNode<T> Parse(IReadOnlyList<IRow<T>> rows)
    {
        if (rows.Count == 0)
            return null;
        var result = new TreeNode<T>(rows[0].Value, rows[0].Id, rows[0].FIN);
        FillParents(new[] { result }, rows, 1, 1);
        return result;
    }

    private static void FillParents(IList<TreeNode<T>> parents, IReadOnlyList<IRow<T>> rows, int index, int currentLevel)
    {
        var result = new List<TreeNode<T>>();
        for (int i = index; i < rows.Count; i++)
        {
            var descriptor = new NodeDescriptor(rows[i]);
            if (descriptor.Level != currentLevel)
            {
                FillParents(result, rows, i, descriptor.Level);
                return;
            }
            var treeNode = new TreeNode<T>(rows[i].Value, rows[i].Id, rows[i].FIN);
            parents[descriptor.ParentIndex].children.Add(treeNode);
            result.Add(treeNode);
        }
    }
}
</code>```

g

this is also my JSON output for more information :

```<code>{"title":"Earth","Id":32,"FIN":"FIN","children":[{"title":"Europe","Id":33,"FIN":"FIN001","children":[{"title":"France","Id":35,"FIN":"FIN001001","children":[{"title":"Paris","Id":36,"FIN":"FIN001001001","children":[]},{"title":"Brasilia","Id":41,"FIN":"FIN002001001","children":[]},{"title":"Bahia","Id":42,"FIN":"FIN002001002","children":[]}]},{"title":"Spain","Id":38,"FIN":"FIN001002","children":[{"title":"Madrid","Id":37,"FIN":"FIN001002001","children":[{"title":"Salvador","Id":43,"FIN":"FIN002001002001","children":[]}]}]},{"title":"Italy","Id":45,"FIN":"FIN001003","children":[]},{"title":"Germany","Id":48,"FIN":"FIN001004","children":[]},{"title":"test","Id":10049,"FIN":"FIN001005","children":[]}]},{"title":"South America","Id":34,"FIN":"FIN002","children":[{"title":"Brazil","Id":40,"FIN":"FIN002001","children":[{"title":"Morano","Id":47,"FIN":"FIN001003001","children":[]}]}]},{"title":"Antarctica","Id":39,"FIN":"FIN003","children":[{"title":"McMurdo Station","Id":44,"FIN":"FIN003001","children":[]}]}]}
</code>```

Body:
I implement exactly this code According to Alex implementation but as is mentioned in some case it didn't work correctly .. have a look to my Image and my code (which copied from Alex post) [data in the database are correct but in tree view seems some problems ]

public class Row : IRow<string>
{
    public string TextNode { get; }
    public string Value { get; }
    public long Id { get; }
    public string FIN { get; }
    public Row(string textNode, string userName, long id, string fin)
    {
        FIN = fin;
        Id = id;
        TextNode = textNode;
        Value = userName;
    }
}

public interface IRow<out T>
{
    string TextNode { get; }
    long Id { get; }
    string FIN { get; }
    T Value { get; }
}

public class TreeNode<T>
{
    private struct NodeDescriptor
    {
        public int Level { get; }
        public int ParentIndex { get; }

        public NodeDescriptor(IRow<T> row)
        {
            var split = row.TextNode.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
            Level = split.Length;
            ParentIndex = split.Length > 1 ? int.Parse(split[split.Length - 2]) - 1 : 0;
        }
    }
    public T title { get; }
    public long Id { get; }
    public string FIN { get; }
    public List<TreeNode<T>> children { get; }

    private TreeNode(T value, long id, string fin)
    {
        Id = id;
        FIN = fin;
        title = value;
        children = new List<TreeNode<T>>();
    }

    public static TreeNode<T> Parse(IReadOnlyList<IRow<T>> rows)
    {
        if (rows.Count == 0)
            return null;
        var result = new TreeNode<T>(rows[0].Value, rows[0].Id, rows[0].FIN);
        FillParents(new[] { result }, rows, 1, 1);
        return result;
    }

    private static void FillParents(IList<TreeNode<T>> parents, IReadOnlyList<IRow<T>> rows, int index, int currentLevel)
    {
        var result = new List<TreeNode<T>>();
        for (int i = index; i < rows.Count; i++)
        {
            var descriptor = new NodeDescriptor(rows[i]);
            if (descriptor.Level != currentLevel)
            {
                FillParents(result, rows, i, descriptor.Level);
                return;
            }
            var treeNode = new TreeNode<T>(rows[i].Value, rows[i].Id, rows[i].FIN);
            parents[descriptor.ParentIndex].children.Add(treeNode);
            result.Add(treeNode);
        }
    }
}

g

this is also my JSON output for more information :

{"title":"Earth","Id":32,"FIN":"FIN","children":[{"title":"Europe","Id":33,"FIN":"FIN001","children":[{"title":"France","Id":35,"FIN":"FIN001001","children":[{"title":"Paris","Id":36,"FIN":"FIN001001001","children":[]},{"title":"Brasilia","Id":41,"FIN":"FIN002001001","children":[]},{"title":"Bahia","Id":42,"FIN":"FIN002001002","children":[]}]},{"title":"Spain","Id":38,"FIN":"FIN001002","children":[{"title":"Madrid","Id":37,"FIN":"FIN001002001","children":[{"title":"Salvador","Id":43,"FIN":"FIN002001002001","children":[]}]}]},{"title":"Italy","Id":45,"FIN":"FIN001003","children":[]},{"title":"Germany","Id":48,"FIN":"FIN001004","children":[]},{"title":"test","Id":10049,"FIN":"FIN001005","children":[]}]},{"title":"South America","Id":34,"FIN":"FIN002","children":[{"title":"Brazil","Id":40,"FIN":"FIN002001","children":[{"title":"Morano","Id":47,"FIN":"FIN001003001","children":[]}]}]},{"title":"Antarctica","Id":39,"FIN":"FIN003","children":[{"title":"McMurdo Station","Id":44,"FIN":"FIN003001","children":[]}]}]}


问:
jQuery Toggle Display none and animate.css classes
I have a div that is initially hidden by display: none in the css.

```<code><div id="myDiv" class="animate__animated">Div content Here</div>
</code>```

I this have a function:

```<code>function togglefunc() {

    $('#myDiv').toggle().toggleClass('animate__slideInRight animate__slideInLeft');

}
</code>```

What I want to do is to toggle display: none and block but also toggle classes:

```<code>animate__slideInRight and animate__slideInLeft
</code>```

So...

If it's hidden and the function is called, it shows up with the effect animate__slideInRight (animate.css class)

otherwise

If it's visible and the function is called, it will hide with the effect animate__slideInLeft (animate.css class)

My function shows fine with the effect animate__slideInRight but when I click again if quickly hides with no effect.

How can I fix this?

答: Sadly, you can't animate an element going from display: none to display: block. You can however use visibility: hidden and visibility: visible.

Body:
I have a div that is initially hidden by display: none in the css.

Div content Here

I this have a function:

function togglefunc() {

    $('#myDiv').toggle().toggleClass('animate__slideInRight animate__slideInLeft');

}

What I want to do is to toggle display: none and block but also toggle classes:

animate__slideInRight and animate__slideInLeft

So...

If it's hidden and the function is called, it shows up with the effect animate__slideInRight (animate.css class)

otherwise

If it's visible and the function is called, it will hide with the effect animate__slideInLeft (animate.css class)

My function shows fine with the effect animate__slideInRight but when I click again if quickly hides with no effect.

How can I fix this?


问:
Visual Studio 2008 Test Sets
Is it possible to group tests together so I can run a subset of all tests available?</p>

答:
Two simple ways would be: by class and by namespace.

There is a run tests in context option, you can use to run a specific test method, but also a test class or namespace. It just depends on what you are pointing at. Open one test in the editor, and put the cursor on the namespace and check it out.

OwnerDisplayName: blu

Title: Visual Studio 2008 Test Sets

OwnerDisplayName: Freddy Rios

LastEditorDisplayName: Freddy Rios


问:
How to set maximum characters per line in tinyMCE, version 5.0.11?
So I have a angular 8 application and I am using tinyMCE

and I want to set the maximum characters per line in the textArea of tinymce.

Of course I googled a lot. But I can't find any solution.

So this is to long. So I want that the user can only put half of the text of the showing line.

So  I want to archive maximum characters per line not in total.

But how to archive this?

Thank you.

So this is input field of tinyMce:

```<code>
        <ng-container *ngIf="is('HtmlDisplay')">
          <editor
            [init]="tinyMCESettings"
            name="html"
            ngModel
            #html="ngModel"
          ></editor>
        </ng-container>

</code>```

and this is ts script:

```<code> public tinyMCESettings = {
    base_url: '/assets/tinymce',
    suffix: '.min',
    plugins: 'link lists image code advlist',
    toolbar: 'undo redo | bold italic | bullist numlist outdent indent | link | image | code'
  };
</code>```

答:
You can limit the width of the text being entered by modifying the TinyMCE CSS. For example, using content_style,

```<code>content_style: "body { margin: 1rem auto; max-width: 900px; }"
</code>```

There are also two predefined stylesheets that set larger margins - document and writer. You may also find these useful. You can apply them with content_css; for example:

```<code>content_css: "writer"
</code>```

or

```<code>content_css: "document"
</code>```

Body:
So I have a angular 8 application and I am using tinyMCE

and I want to set the maximum characters per line in the textArea of tinymce.

Of course I googled a lot. But I can't find any solution.

So this is to long. So I want that the user can only put half of the text of the showing line.

So  I want to archive maximum characters per line not in total.

But how to archive this?

Thank you.

So this is input field of tinyMce:

        <ng-container *ngIf="is('HtmlDisplay')">
          <editor
            [init]="tinyMCESettings"
            name="html"
            ngModel
            #html="ngModel"
          ></editor>
        </ng-container>

and this is ts script:

 public tinyMCESettings = {
    base_url: '/assets/tinymce',
    suffix: '.min',
    plugins: 'link lists image code advlist',
    toolbar: 'undo redo | bold italic | bullist numlist outdent indent | link | image | code'
  };

Body:
You can limit the width of the text being entered by modifying the TinyMCE CSS. For example, using content_style,

content_style: "body { margin: 1rem auto; max-width: 900px; }"

There are also two predefined stylesheets that set larger margins - document and writer. You may also find these useful. You can apply them with content_css; for example:

content_css: "writer"

or

content_css: "document"


问:
How to hide both line and circle in Python Bokeh plot using legend click policy?
I have a Python Bokeh plot (multiple plot lines+circle) as follows:

```<code> output_notebook()

source = ColumnDataSource(da)

col_names = paises

p = figure(
 title = "A",
 x_axis_type="datetime",
 plot_width=800,
 plot_height=400,
 sizing_mode='scale_width',
 toolbar_location='above',
 tools ="box_zoom,reset,wheel_zoom" )

p_dict = dict()

for col, c, col_name in zip(da.columns, color, col_names):
 p_dict[col_name] = p.circle('date', col, source=source, color=c, size=3.5, line_width=0.5, fill_color=None)
 p_dict[col_name] = p.line('date', col, source=source, color=c, line_width=1)

 p.add_tools(HoverTool(
     toggleable=False,
     renderers=[p_dict[col_name]],
     tooltips=[('datetime','@date{%F}'),(col, f'@{col}')],
     formatters={'@date': 'datetime'}
 ))

legend = Legend(items=[(x, [p_dict[x]]) for x in p_dict])

p.add_layout(legend)

p.legend.click_policy="hide"

p.legend.label_text_font_size = "1vw"
p.legend.location = 'top_left'
p.left[0].formatter.use_scientific = False

show(p)

</code>```

I am using legend.click_policy="hide" to hide the lines but when clicking the legend, only hides the circle but not the line. Is there a way to hide both line and circle?

Thanks!

答:
I realized that I had to post the complete code (I already changed it so that the question is well understood). I found the solution adding the legend to the for loop:</p>

```<code>output_notebook()

source = ColumnDataSource(da)

col_names = paises

p = figure(
    title = "A",
    x_axis_type="datetime",
    plot_width=800,
    plot_height=400,
    sizing_mode='scale_width',
    toolbar_location='above',
    tools ="box_zoom,reset,wheel_zoom" )

p_dict = dict()

for col, c, col_name, leg in zip(da.columns, color, col_names, paises):
    p_dict[col_name] = p.circle('date', col, source=source, color=c, size=3.5, line_width=0.5, fill_color=None, legend_label = leg)
    p_dict[col_name] = p.line('date', col, source=source, color=c, line_width=1, legend_label = leg)

    p.add_tools(HoverTool(
        toggleable=False,
        renderers=[p_dict[col_name]],
        tooltips=[('datetime','@date{%F}'),(col, f'@{col}')],
        formatters={'@date': 'datetime'}
    ))

p.legend.click_policy="hide"

p.legend.label_text_font_size = "1vw"
p.legend.location = 'top_left'
p.left[0].formatter.use_scientific = False

show(p)
</code>```

Body:
I have a Python Bokeh plot (multiple plot lines+circle) as follows:

 output_notebook()

source = ColumnDataSource(da)

col_names = paises

p = figure(
 title = "A",
 x_axis_type="datetime",
 plot_width=800,
 plot_height=400,
 sizing_mode='scale_width',
 toolbar_location='above',
 tools ="box_zoom,reset,wheel_zoom" )

p_dict = dict()

for col, c, col_name in zip(da.columns, color, col_names):
 p_dict[col_name] = p.circle('date', col, source=source, color=c, size=3.5, line_width=0.5, fill_color=None)
 p_dict[col_name] = p.line('date', col, source=source, color=c, line_width=1)

 p.add_tools(HoverTool(
     toggleable=False,
     renderers=[p_dict[col_name]],
     tooltips=[('datetime','@date{%F}'),(col, f'@{col}')],
     formatters={'@date': 'datetime'}
 ))

legend = Legend(items=[(x, [p_dict[x]]) for x in p_dict])

p.add_layout(legend)

p.legend.click_policy="hide"

p.legend.label_text_font_size = "1vw"
p.legend.location = 'top_left'
p.left[0].formatter.use_scientific = False

show(p)

I am using legend.click_policy="hide" to hide the lines but when clicking the legend, only hides the circle but not the line. Is there a way to hide both line and circle?

Thanks!

Body:
I realized that I had to post the complete code (I already changed it so that the question is well understood). I found the solution adding the legend to the for loop:

output_notebook()

source = ColumnDataSource(da)

col_names = paises

p = figure(
    title = "A",
    x_axis_type="datetime",
    plot_width=800,
    plot_height=400,
    sizing_mode='scale_width',
    toolbar_location='above',
    tools ="box_zoom,reset,wheel_zoom" )

p_dict = dict()

for col, c, col_name, leg in zip(da.columns, color, col_names, paises):
    p_dict[col_name] = p.circle('date', col, source=source, color=c, size=3.5, line_width=0.5, fill_color=None, legend_label = leg)
    p_dict[col_name] = p.line('date', col, source=source, color=c, line_width=1, legend_label = leg)

    p.add_tools(HoverTool(
        toggleable=False,
        renderers=[p_dict[col_name]],
        tooltips=[('datetime','@date{%F}'),(col, f'@{col}')],
        formatters={'@date': 'datetime'}
    ))

p.legend.click_policy="hide"

p.legend.label_text_font_size = "1vw"
p.legend.location = 'top_left'
p.left[0].formatter.use_scientific = False

show(p)


问:
Lombok is woking in commad line but it is not in "Run Java Application"(Eclipse
I am using Lombok(1.18.12) and Eclipse-2020-03-(4.15.0). I am already the intallation  of Lombok, to JAR. I already see in file "eclipse.ini" the your configuration. But It is not working when I execute the program(Spring boot + Maven) for Eclipse(Run Application), but when I execute the program for command line It work.

Why?

Thanks for help.

答: Check that Eclipse is loading lombok, you can do that by opening the About Eclipse dialog, you should see  Lombok v1.18.12 "Envious Ferret" is installed. If you don't see that, then lombok is not running. On my machine I have that problem when I start eclipse with ./eclipse instead of using Eclipse.app wich loads lombok just fine.


问:
Use NumPy cleverly to speed up this loop
This is quite a theoretical question. It is about the for loop at the end of the code attached.

I have three compatible arrays, Z, Wt_1 and Wt_2.

I used the vectorized columns to speed up the loop, ie I code with columns as though they were scalars, and the whole process works.
But this loop still takes forever (2min+). Here, N = 5000 and a column is 100000 long.

Is there a syntax that speeds this up ?

```<code>M=100000

N=5000
t0=0.132
T=0.22
dt=T / N

Z0=8
Y0=7

ssqZ=0.04
ssqY=0.01
sigma_Z=np.sqrt(ssqZ)
sigma_Y=np.sqrt(ssqY)
rho=- 0.4

print("Genreating the Brownian Motions...")
Wt_1=rd.randn(M//2,N)
# shape is (50 000,5 000)
Wt_1=np.vstack((Wt_1,-Wt_1))
#print(np.shape(Wt_1))
Wt_2=rd.randn(M//2,N)
Wt_2=np.vstack((Wt_2,-Wt_2))
print("BM generated!\n")

Z=np.zeros((M,N+1))
# shape is (100 000, 5 001)
Y=np.zeros((M,N+1))
#in SciPy indexing starts from 0 :
Z[:,0]=Z0
Y[:,0]=Y0

for i in range(1,N+1) :
    Z[:,i]=Z[:,i-1] - 0.5*(sigma_Z**2)*dt + sigma_Z*np.sqrt(dt)*Wt_1[:,i-1]

    Y[:,i]=Y[:,i-1] + sigma_Y*np.sqrt(dt)* (rho*Wt_1[:,i-1] + np.sqrt(1 - rho**2)*Wt_2[:,i-1])
</code>```

I should add that the same routine in Matlab takes 19s, whereas this Python one takes 137s, which is counter intuitive to me

答:
This problem is quite hard to efficiently vectorize Numpy. In your version you have a vectorized command, which iterates over values which are not contiguously stored in memory Numpy/C row-major, Fortran/Matlab/Julia is column major.

If you want to use Numpy probably the easiest way is to transpose all arrays and operations or use Fortran-ordered arrays (should give a factor of 4).

Another way is to write out the loops and make use of Numba Numba or Cython.

Numba Example

```<code>@nb.njit(fastmath=True,parallel=True,cache=True)
def Numba(Z0,Y0,sigma_Y,sigma_Z,Wt_1,Wt_2,rho,dt):
    N,M=Wt_1.shape

    Z=np.empty((M,N+1))
    Y=np.empty((M,N+1))
    Z[:,0]=Z0
    Y[:,0]=Y0
    #the possibillity of negative values can lead to a slow wrap-around check
    for i in nb.prange(M):
        #only beneficial for very large
        for j in range(N):
            Z[i,j+1]=Z[i,j] - 0.5*(sigma_Z**2)*dt + sigma_Z*np.sqrt(dt)*Wt_1[i,j]
            Y[i,j+1]=Y[i,j] + sigma_Y*np.sqrt(dt)* (rho*Wt_1[i,j] + np.sqrt(1 - rho**2)*Wt_2[i,j])
    return Z,Y
</code>```

Your Numpy example

It would also be good to add an example how you got your timings, since generating the Inputs takes more time than the actual computation (at least for the Numba version).

```<code>def Numpy_not_aligned(Z0,Y0,sigma_Y,sigma_Z,Wt_1,Wt_2,rho,dt):
    Z=np.zeros((M,N+1))
    # shape is (100 000, 5 001)
    Y=np.zeros((M,N+1))
    #in SciPy indexing starts from 0 :
    Z[:,0]=Z0
    Y[:,0]=Y0

    for i in range(1,N+1) :
        Z[:,i]=Z[:,i-1] - 0.5*(sigma_Z**2)*dt + sigma_Z*np.sqrt(dt)*Wt_1[:,i-1]
        Y[:,i]=Y[:,i-1] + sigma_Y*np.sqrt(dt)* (rho*Wt_1[:,i-1] + np.sqrt(1 - rho**2)*Wt_2[:,i-1])
    return Y,Z
</code>```

Timings

```<code># M=M=50000
%timeit Numpy_not_aligned(Z0,Y0,sigma_Y,sigma_Z,Wt_1,Wt_2,rho,dt)
#25.9 s ± 82.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit Numba(Z0,Y0,sigma_Y,sigma_Z,Wt_1,Wt_2,rho,dt)
#1.03 s ± 127 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code>```

Body:
This is quite a theoretical question. It is about the for loop at the end of the code attached.

I have three compatible arrays, Z, Wt_1 and Wt_2.

I used the vectorized columns to speed up the loop, ie I code with columns as though they were scalars, and the whole process works.
But this loop still takes forever (2min+). Here, N = 5000 and a column is 100000 long.

Is there a syntax that speeds this up ?

M=100000

N=5000
t0=0.132
T=0.22
dt=T / N

Z0=8
Y0=7

ssqZ=0.04
ssqY=0.01
sigma_Z=np.sqrt(ssqZ)
sigma_Y=np.sqrt(ssqY)
rho=- 0.4

print("Genreating the Brownian Motions...")
Wt_1=rd.randn(M//2,N)
# shape is (50 000,5 000)
Wt_1=np.vstack((Wt_1,-Wt_1))
#print(np.shape(Wt_1))
Wt_2=rd.randn(M//2,N)
Wt_2=np.vstack((Wt_2,-Wt_2))
print("BM generated!\n")

Z=np.zeros((M,N+1))
# shape is (100 000, 5 001)
Y=np.zeros((M,N+1))
#in SciPy indexing starts from 0 :
Z[:,0]=Z0
Y[:,0]=Y0

for i in range(1,N+1) :
    Z[:,i]=Z[:,i-1] - 0.5*(sigma_Z**2)*dt + sigma_Z*np.sqrt(dt)*Wt_1[:,i-1]

    Y[:,i]=Y[:,i-1] + sigma_Y*np.sqrt(dt)* (rho*Wt_1[:,i-1] + np.sqrt(1 - rho**2)*Wt_2[:,i-1])

I should add that the same routine in Matlab takes 19s, whereas this Python one takes 137s, which is counter intuitive to me

Body:
This problem is quite hard to efficiently vectorize Numpy. In your version you have a vectorized command, which iterates over values which are not contiguously stored in memory Numpy/C row-major, Fortran/Matlab/Julia is column major.

If you want to use Numpy probably the easiest way is to transpose all arrays and operations or use Fortran-ordered arrays (should give a factor of 4).

Another way is to write out the loops and make use of Numba Numba or Cython.

Numba Example

@nb.njit(fastmath=True,parallel=True,cache=True)
def Numba(Z0,Y0,sigma_Y,sigma_Z,Wt_1,Wt_2,rho,dt):
    N,M=Wt_1.shape

    Z=np.empty((M,N+1))
    Y=np.empty((M,N+1))
    Z[:,0]=Z0
    Y[:,0]=Y0
    #the possibillity of negative values can lead to a slow wrap-around check
    for i in nb.prange(M):
        #only beneficial for very large
        for j in range(N):
            Z[i,j+1]=Z[i,j] - 0.5*(sigma_Z**2)*dt + sigma_Z*np.sqrt(dt)*Wt_1[i,j]
            Y[i,j+1]=Y[i,j] + sigma_Y*np.sqrt(dt)* (rho*Wt_1[i,j] + np.sqrt(1 - rho**2)*Wt_2[i,j])
    return Z,Y

Your Numpy example

It would also be good to add an example how you got your timings, since generating the Inputs takes more time than the actual computation (at least for the Numba version).

def Numpy_not_aligned(Z0,Y0,sigma_Y,sigma_Z,Wt_1,Wt_2,rho,dt):
    Z=np.zeros((M,N+1))
    # shape is (100 000, 5 001)
    Y=np.zeros((M,N+1))
    #in SciPy indexing starts from 0 :
    Z[:,0]=Z0
    Y[:,0]=Y0

    for i in range(1,N+1) :
        Z[:,i]=Z[:,i-1] - 0.5*(sigma_Z**2)*dt + sigma_Z*np.sqrt(dt)*Wt_1[:,i-1]
        Y[:,i]=Y[:,i-1] + sigma_Y*np.sqrt(dt)* (rho*Wt_1[:,i-1] + np.sqrt(1 - rho**2)*Wt_2[:,i-1])
    return Y,Z

Timings

# M=M=50000
%timeit Numpy_not_aligned(Z0,Y0,sigma_Y,sigma_Z,Wt_1,Wt_2,rho,dt)
#25.9 s ± 82.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit Numba(Z0,Y0,sigma_Y,sigma_Z,Wt_1,Wt_2,rho,dt)
#1.03 s ± 127 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


问:
Find Object in Array of Objects based off key using Array.find()
So I have an array of names:

```<code>const names = ['student1', 'student2', 'student3']
</code>```

and I have an array of attendance objects:

```<code>const attendance = [
  {student1: ['On Time', 'Late']},
  {student2: ['Late', 'Late']},
  {student3: ['On Time', 'Excused']},
]
</code>```

I wanted to find the student object in the attendance array based off the names from the names array.

So currently I have:

```<code>names.forEach(person => {
  function attendanceData(p) {
     return Object.keys(attendance).toString() == p.toString()
  }
  console.log(attendance.find(attendanceData(person)))
})
</code>```

However, this gives me an error saying:

```<code>Uncaught (in promise) TypeError: false is not a function
</code>```

The next stack says "at Array.find()"

I'm wondering how I'm not using this correctly and if there was a better way to do this, what should I do?

答:
try it

```<code>let result = attendance.filter(obj => names.includes(Object.keys(obj)[0]))
console.log(result)
</code>```

Use array's method "filter" for getting items. You need get keys of object and take first key. And then you'll can check presence in names array, via array's method "includes"

more information about this methods here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Filter

Body:
So I have an array of names:

const names = ['student1', 'student2', 'student3']

and I have an array of attendance objects:

const attendance = [
  {student1: ['On Time', 'Late']},
  {student2: ['Late', 'Late']},
  {student3: ['On Time', 'Excused']},
]

I wanted to find the student object in the attendance array based off the names from the names array.

So currently I have:

names.forEach(person => {
  function attendanceData(p) {
     return Object.keys(attendance).toString() == p.toString()
  }
  console.log(attendance.find(attendanceData(person)))
})

However, this gives me an error saying:

Uncaught (in promise) TypeError: false is not a function

The next stack says "at Array.find()"

I'm wondering how I'm not using this correctly and if there was a better way to do this, what should I do?

Body:
try it

let result = attendance.filter(obj => names.includes(Object.keys(obj)[0]))
console.log(result)

Use array's method "filter" for getting items. You need get keys of object and take first key. And then you'll can check presence in names array, via array's method "includes"

more information about this methods here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Filter


问:
Does this smali class decrypt data? what encryption is it using?
Q: Does this smali class decrypt data? what encryption is it using?

I need help finding out what this code uses to decrypt the file text it receives?
the encrypted text prints out as expected in a jumbled mess, is there a way to manually decrypt the text using the information I need help understanding?

```<code>package utils;

import android.util.Log;
import com.crashlytics.android.Crashlytics;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.io.FileUtils;

public class EFileIO {
   private static byte[] df(byte[] var0, byte[] var1) throws Exception {
      SecretKeySpec var2 = new SecretKeySpec(var0, "AES");
      Cipher var3 = Cipher.getInstance("AES");
      var3.init(2, var2);
      return var3.doFinal(var1);
   }

   private static byte[] ef(byte[] var0, byte[] var1) throws Exception {
      SecretKeySpec var2 = new SecretKeySpec(var0, "AES");
      Cipher var3 = Cipher.getInstance("AES");
      var3.init(1, var2);
      return var3.doFinal(var1);
   }

   private static byte[] gk(String var0) throws Exception {
      byte[] var1 = var0.getBytes("UTF-8");
      KeyGenerator var2 = KeyGenerator.getInstance("AES");
      SecureRandom var3 = SecureRandom.getInstance("SHA1PRNG", "Crypto");
      var3.setSeed(var1);
      var2.init(128, var3);
      return var2.generateKey().getEncoded();
   }

   public static String rf(File var0) {
      String var1 = "";

      String var3;
      String var5;
      try {
         byte[] var2 = df(gk("AIzaSyDVQJ323-Th1pPJIcDrSt0KYFMTuLJR7Vw"), FileUtils.readFileToByteArray(var0));
         var3 = new String(var2, "UTF-8");
      } catch (Exception var4) {
         Crashlytics.log(6, "EFILEIO.java", "rf,  mf.getName(): " + var0.getName());
         Crashlytics.logException(var4);
         var4.printStackTrace();
         var5 = var1;
         return var5;
      }

      var5 = var3;
      return var5;
   }

   public static void wr(StringBuilder var0, File var1) {
      try {
         FileOutputStream var3 = new FileOutputStream(var1);
         BufferedOutputStream var2 = new BufferedOutputStream(var3);
         byte[] var5 = ef(gk("AIzaSyDVQJ323-Th1pPJIcDrSt0KYFMTuLJR7Vw"), var0.toString().trim().getBytes("UTF-8"));
         StringBuilder var6 = new StringBuilder();
         Log.e("FileIo", var6.append("wr: content ").append(var5).toString());
         var2.write(var5);
         var2.flush();
         var2.close();
      } catch (Exception var4) {
         Crashlytics.log(6, "EFILEIO.java", "wr,  mf.getName(): " + var1.getName());
         Crashlytics.logException(var4);
         var4.printStackTrace();
      }
</code>```

答:
The (short) answer to your question is YES.

Your class (method wr) is encrypting a String (wrapped in a StringBuilder) with a fixed key and saves the ciphertext to a file on the disc. Another method (rf) is reading the file with the ciphertext, decrypts it with the fixed key and prints the
decrypted / plaintext to the console.

These are the 5 methods in your class with a short description:

gk = generates a fixed 16 byte (128 bit) long key for AES en-/decryption

ef = encrypts a byte array with the generated key

df = decrypts a byte array with the generated key

wr = writes the encrypted byte array (using method ef) to a file on the disc

rf = reads the contents of a file to a byte array, decrypts it with method df and shows the decrypted text

The class uses the AES/ECB/PKCS5PADDING mode for encryption (I done the decryption manually on OpenJDK 11, so maybe the mode has another name with your crypto service provider on Android). The initialisation in methods ef + df with
"Cipher.getInstance("AES")" results in the "standard" ECB-PKCS5PADDING mode which is insecure and should be no longer used.

If you created a ciphertextfile "cipher.dat" you can use this simple program to decrypt the content and show it on the console (there is no proper exception handling...):

```<code>import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class SimpleDecryption {
    public static void main(String[] args) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, IOException, BadPaddingException, IllegalBlockSizeException {
        System.out.println("Simple decryption method for\n" +
                "https://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java");
        String filename = "cipher.dat";
        byte[] fixedKey = hexStringToByteArray("e409c02fb48745a14f5e1c03e3c6f0ca");
        Cipher aesCipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        SecretKeySpec secretKeySpec = new SecretKeySpec(fixedKey, "AES");
        aesCipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        System.out.println("decrypted text: " + new String(aesCipher.doFinal(Files.readAllBytes(Paths.get(filename))),"UTF-8"));
    }
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }
}
</code>```

Sample output:

```<code>Simple decryption method for
https://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java
decrypted text: This text needs to get encrypted
</code>```

Body:
Q: Does this smali class decrypt data? what encryption is it using?

I need help finding out what this code uses to decrypt the file text it receives?
the encrypted text prints out as expected in a jumbled mess, is there a way to manually decrypt the text using the information I need help understanding?

package utils;

import android.util.Log;
import com.crashlytics.android.Crashlytics;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.io.FileUtils;

public class EFileIO {
   private static byte[] df(byte[] var0, byte[] var1) throws Exception {
      SecretKeySpec var2 = new SecretKeySpec(var0, "AES");
      Cipher var3 = Cipher.getInstance("AES");
      var3.init(2, var2);
      return var3.doFinal(var1);
   }

   private static byte[] ef(byte[] var0, byte[] var1) throws Exception {
      SecretKeySpec var2 = new SecretKeySpec(var0, "AES");
      Cipher var3 = Cipher.getInstance("AES");
      var3.init(1, var2);
      return var3.doFinal(var1);
   }

   private static byte[] gk(String var0) throws Exception {
      byte[] var1 = var0.getBytes("UTF-8");
      KeyGenerator var2 = KeyGenerator.getInstance("AES");
      SecureRandom var3 = SecureRandom.getInstance("SHA1PRNG", "Crypto");
      var3.setSeed(var1);
      var2.init(128, var3);
      return var2.generateKey().getEncoded();
   }

   public static String rf(File var0) {
      String var1 = "";

      String var3;
      String var5;
      try {
         byte[] var2 = df(gk("AIzaSyDVQJ323-Th1pPJIcDrSt0KYFMTuLJR7Vw"), FileUtils.readFileToByteArray(var0));
         var3 = new String(var2, "UTF-8");
      } catch (Exception var4) {
         Crashlytics.log(6, "EFILEIO.java", "rf,  mf.getName(): " + var0.getName());
         Crashlytics.logException(var4);
         var4.printStackTrace();
         var5 = var1;
         return var5;
      }

      var5 = var3;
      return var5;
   }

   public static void wr(StringBuilder var0, File var1) {
      try {
         FileOutputStream var3 = new FileOutputStream(var1);
         BufferedOutputStream var2 = new BufferedOutputStream(var3);
         byte[] var5 = ef(gk("AIzaSyDVQJ323-Th1pPJIcDrSt0KYFMTuLJR7Vw"), var0.toString().trim().getBytes("UTF-8"));
         StringBuilder var6 = new StringBuilder();
         Log.e("FileIo", var6.append("wr: content ").append(var5).toString());
         var2.write(var5);
         var2.flush();
         var2.close();
      } catch (Exception var4) {
         Crashlytics.log(6, "EFILEIO.java", "wr,  mf.getName(): " + var1.getName());
         Crashlytics.logException(var4);
         var4.printStackTrace();
      }

Body:
The (short) answer to your question is YES.

Your class (method wr) is encrypting a String (wrapped in a StringBuilder) with a fixed key and saves the ciphertext to a file on the disc. Another method (rf) is reading the file with the ciphertext, decrypts it with the fixed key and prints the
decrypted / plaintext to the console.

These are the 5 methods in your class with a short description:

gk = generates a fixed 16 byte (128 bit) long key for AES en-/decryption

ef = encrypts a byte array with the generated key

df = decrypts a byte array with the generated key

wr = writes the encrypted byte array (using method ef) to a file on the disc

rf = reads the contents of a file to a byte array, decrypts it with method df and shows the decrypted text

The class uses the AES/ECB/PKCS5PADDING mode for encryption (I done the decryption manually on OpenJDK 11, so maybe the mode has another name with your crypto service provider on Android). The initialisation in methods ef + df with
"Cipher.getInstance("AES")" results in the "standard" ECB-PKCS5PADDING mode which is insecure and should be no longer used.

If you created a ciphertextfile "cipher.dat" you can use this simple program to decrypt the content and show it on the console (there is no proper exception handling...):

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class SimpleDecryption {
    public static void main(String[] args) throws InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, IOException, BadPaddingException, IllegalBlockSizeException {
        System.out.println("Simple decryption method for\n" +
                "https://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java");
        String filename = "cipher.dat";
        byte[] fixedKey = hexStringToByteArray("e409c02fb48745a14f5e1c03e3c6f0ca");
        Cipher aesCipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        SecretKeySpec secretKeySpec = new SecretKeySpec(fixedKey, "AES");
        aesCipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        System.out.println("decrypted text: " + new String(aesCipher.doFinal(Files.readAllBytes(Paths.get(filename))),"UTF-8"));
    }
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }
}

Sample output:

Simple decryption method for
https://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java
decrypted text: This text needs to get encrypted


问:
How to fix favicon.ico error: "Failed to load resource: net::ERR_EMPTY_RESPONSE"
I downloaded the Netbeans IDE to code in HTML. When I run my code, chrome is opening and everything is working just fine. I'm getting some sort of error in the Output - Browser Log.

```<code>Failed to load resource: net::ERR_EMPTY_RESPONSE (20:00:55:963 | error, network)
at http://localhost:8383/favicon.ico
</code>```

How do I fix it?

答:
It's a nightmare since each browser/device handles it differently.

Favicon generator helps me a lot for those applications where we need to cover the most possible scenarios.

https://realfavicongenerator.net/

You just need a png image 260px x 260px (at least) and from there the generator will create all references you need within your web page.

You just need to add this references and images to your application.

Body:
I downloaded the Netbeans IDE to code in HTML. When I run my code, chrome is opening and everything is working just fine. I'm getting some sort of error in the Output - Browser Log.

Failed to load resource: net::ERR_EMPTY_RESPONSE (20:00:55:963 | error, network)
at http://localhost:8383/favicon.ico

How do I fix it?


问:
How can I get jQTouch mobile views working with Devise for "sign in" and "register"?
I have a Rails 3 app and I'm using Devise and jQTouch.

I've got all of my mobile views working except for "sign in" and "register".

When I try to sign in using the mobile version, I get the following:

```<code>Missing template user_sessions/create with {:locale=>[:en, :en], :formats=>[:mobile],     :handlers=>[:rxml, :erb, :rjs, :builder, :rhtml]} in view paths
</code>```

For other controllers, I added format.mobile and created mobile views, but for sign in and register I am having trouble sorting them out.

Any ideas on how to get my jQTouch mobile views working with Devise for sign in and register?

答:
You need to do 2 things.

1) in config/initializers/devise.rb you need to add :mobile as an accepted type.
To do this find the line that says:

```<code>config.navigational_formats = [:html]
</code>```

And add :mobile to it so it should now read:

```<code>config.navigational_formats = [:html, :mobile]
</code>```

2) You need to create another initializer file and add the following code to it:

```<code>ActionController::Responder.class_eval do
  alias :to_mobile :to_html
end
</code>```

This will make it so that all devise redirects work.

If you need more information check out the devise wiki

https://github.com/plataformatec/devise/wiki

Body:
I have a Rails 3 app and I'm using Devise and jQTouch.

I've got all of my mobile views working except for "sign in" and "register".

When I try to sign in using the mobile version, I get the following:

Missing template user_sessions/create with {:locale=>[:en, :en], :formats=>[:mobile],     :handlers=>[:rxml, :erb, :rjs, :builder, :rhtml]} in view paths

For other controllers, I added format.mobile and created mobile views, but for sign in and register I am having trouble sorting them out.

Any ideas on how to get my jQTouch mobile views working with Devise for sign in and register?

Body:
You need to do 2 things.

1) in config/initializers/devise.rb you need to add :mobile as an accepted type.
To do this find the line that says:

config.navigational_formats = [:html]

And add :mobile to it so it should now read:

config.navigational_formats = [:html, :mobile]

2) You need to create another initializer file and add the following code to it:

ActionController::Responder.class_eval do
  alias :to_mobile :to_html
end

This will make it so that all devise redirects work.

If you need more information check out the devise wiki

https://github.com/plataformatec/devise/wiki


问:
R Loop through a group of columns to make several plots

I need to make several scatter plots from some of the columns on my data frame, so I decided to make a loop, but I don't Know how to set it to iterate just on my columns of interest.
  my code looks like this:

```<code>col_xVScol_y<-ggplot(data=df, aes(x=col_x, y=col_y)) +
geom_point(aes(color= col_z))
</code>```

col_y and col_z would always be the same, I just need to iterate over a group of columns that would take the place of col_x

I´ve seen that you can iterate over the columns with colnames(), like:

```<code>for(i in colnames(df)){
    col_xVScol_y<-ggplot(data=df, aes(x=col_x, y=col_y)) +
    geom_point(aes(color= col_z))]
}
</code>```

But this way is not suitable for my data frame, because it iterates over all columns and I´m interesed in just a group.

答:
Instead of iterating using i, you can iterate using the colnames, as shown below. The call to grid.arrange() from gridExtra is just to plot all the plots in one graphic - you can plot these however you like (storing them in a list is convenient, I find).

The below code iterates over only some columns of mtcars. You could customise this however you like (by constructing the appropriate vector of column names or indices).

```<code>plot_list <- list()

for(col in colnames(mtcars)[c(9:11)]){

  col_xVScol_y <- ggplot(data=mtcars, aes(x=wt, y=mpg)) +
                  geom_point(aes_string(color = col))

  plot_list[[col]] <- col_xVScol_y
}

print(plot_list)

# library(gridExtra)
# grid.arrange(grobs = plot_list)
</code>```

Output of above code

Body:
I need to make several scatter plots from some of the columns on my data frame, so I decided to make a loop, but I don't Know how to set it to iterate just on my columns of interest.
  my code looks like this:

col_xVScol_y<-ggplot(data=df, aes(x=col_x, y=col_y)) +
geom_point(aes(color= col_z))

col_y and col_z would always be the same, I just need to iterate over a group of columns that would take the place of col_x

I´ve seen that you can iterate over the columns with colnames(), like:

for(i in colnames(df)){
    col_xVScol_y<-ggplot(data=df, aes(x=col_x, y=col_y)) +
    geom_point(aes(color= col_z))]
}

But this way is not suitable for my data frame, because it iterates over all columns and I´m interesed in just a group.

Body:
Instead of iterating using i, you can iterate using the colnames, as shown below. The call to grid.arrange() from gridExtra is just to plot all the plots in one graphic - you can plot these however you like (storing them in a list is convenient, I find).

The below code iterates over only some columns of mtcars. You could customise this however you like (by constructing the appropriate vector of column names or indices).

plot_list <- list()

for(col in colnames(mtcars)[c(9:11)]){

  col_xVScol_y <- ggplot(data=mtcars, aes(x=wt, y=mpg)) +
                  geom_point(aes_string(color = col))

  plot_list[[col]] <- col_xVScol_y
}

print(plot_list)

# library(gridExtra)
# grid.arrange(grobs = plot_list)

Output of above code


问:
How to augment all the images in a folder using TensorFlow
To upload a folder to colab and augment the images</p>

答:
If doing in colab, first upload the folder containing all the images,then make a new empty folder to which the augmented images are to be saved

```<code>import keras
import cv2
import os
import glob
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
datagen = ImageDataGenerator(rotation_range =15,
                         width_shift_range = 0.2,
                         height_shift_range = 0.2,
                         rescale=1./255,
                         shear_range=0.2,
                         zoom_range=0.2,
                         horizontal_flip = True,
                         fill_mode = 'nearest',
                         data_format='channels_last',
                         brightness_range=[0.5, 1.5])

img_dir = "folder-name" # Enter Directory of all images
data_path = os.path.join(img_dir,'*g')
files = glob.glob(data_path)
data = []
for f1 in files:
    img = cv2.imread(f1)
    data.append(img)

x = img_to_array(img)
x = x.reshape((1,) + x.shape)

i = 0
path, dirs, files = next(os.walk("folder-name"))
file_count = len(files) #to find number of files in folder

for batch in datagen.flow (x, batch_size=1, save_to_dir =r'new-folder-name',save_prefix="a",save_format='jpg'):
    i+=1
    if i==file_count:
      break
</code>```

The augmented images can be downloaded from the new folder

Body:
If doing in colab, first upload the folder containing all the images,then make a new empty folder to which the augmented images are to be saved

import keras
import cv2
import os
import glob
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
datagen = ImageDataGenerator(rotation_range =15,
                         width_shift_range = 0.2,
                         height_shift_range = 0.2,
                         rescale=1./255,
                         shear_range=0.2,
                         zoom_range=0.2,
                         horizontal_flip = True,
                         fill_mode = 'nearest',
                         data_format='channels_last',
                         brightness_range=[0.5, 1.5])

img_dir = "folder-name" # Enter Directory of all images
data_path = os.path.join(img_dir,'*g')
files = glob.glob(data_path)
data = []
for f1 in files:
    img = cv2.imread(f1)
    data.append(img)

x = img_to_array(img)
x = x.reshape((1,) + x.shape)

i = 0
path, dirs, files = next(os.walk("folder-name"))
file_count = len(files) #to find number of files in folder

for batch in datagen.flow (x, batch_size=1, save_to_dir =r'new-folder-name',save_prefix="a",save_format='jpg'):
    i+=1
    if i==file_count:
      break

The augmented images can be downloaded from the new folder


答:
I believe this is what you want. Your data is structured a little strangely though, so I would like to know on a grander scale what you want this code to do.

const findStudentAttendance = (att, studentName) => {
  return att.find(obj => Object.keys(obj)[0] === studentName)
}

names.forEach(name => {
  console.log(
    findStudentAttendance(attendance, name)
  )
}) /* =>
{ student1: [ 'On Time', 'Late' ] }
{ student2: [ 'Late', 'Late' ] }
{ student3: [ 'On Time', 'Excused' ] }
*/
```

Title: Find Object in Array of Objects based off key using Array.find()


问:
How to compress GIF image before uploading to server in android?
how to compress GIF image before upload it to the server ?, i tried some android libraries to compress gif image but it convert it to png image. is there any way to compress gif image ?</p>

答:
GIF is a lossless image compression format: it is set up to reproduce the image exactly.
 As a consequence, there is no "image quality" slider (as in JPEG encoders); although a GIF will likely be much smaller than an uncompressed format (such as many camera RAW or common TIFF options), there is a limit to how far it can go.

Also, you should know that GIF is limited to 8 bits per pixel (so it is most appropriate for line art, not photo-like images).  If your source image is a full 24 bits, it must be dithered to fit into a 256-entry color palette.  So, although the GIF format itself is lossless, the image processing required to use it in the first place may be lossy.

There are a number of things you can do to reduce the size of your image file:

You can choose a lossy format (such as JPEG), which will allow much greater compression.  Note that JPEG works well on photo-like images, but not so well on line art.  Also, (although your question explicitly rejects it) PNG may be a reasonable option, as it (losslessly) supports 24-bpp images.

As mentioned in a comment, you can try reducing the resolution of your image, and shipping the reduced version.  If you can't generate a smaller image to start with, image resizing typically works well on photo-like images, and there are nonlinear resizing filters available that are specifically intended to handle line art.

If a full-resolution GIF is mandatory for your application, you may be able to generate an image that is more compressible by the GIF format.  GIF compresses solid blocks of color extremely well -- but does less well on dithered or noisy images (such as you might get from converting a 24-bpp image to GIF format).

Since you have not given any information on your requirements (what kind of image you have, where you got it, and what you need it for), it is hard to come up with specific advice.

However, there is a good chance that your GIF has far more resolution than you need for your particular application (leading to option #2).


问:
Values must match the following regular expression: '\d+' error
I'm trying to build a small Google App Script with Google Analytics API management to copy Google Analytics filters from one view to another.

I've the following python snippet which I'd like to translate into Google App Script:

```<code># This request creates a new profile filter link.
try:
  analytics.management().profileFilterLinks().insert(
      accountId='123456',
      webPropertyId='UA-123456-1',
      profileId='7654321',
      body={
          'filterRef': {
              'id': '1223334444'
          }
      }
  ).execute()
</code>```

I'm able to get a list of profile filter link like this:

```<code>var filterLinks = Analytics.Management.ProfileFilterLinks.list(
      '12345678','UA-98765432-1','111111111')
</code>```

I tried to replicate something similar with for the insert method but It doesn't work:

```<code>var body = JSON.stringify({
         'filterRef': {
             'id': '84029058'
}});

var up = Analytics.Management.ProfileFilterLinks.insert('12345678','UA-98765432-1','111111111',body)
</code>```

any idea?

答:
How about this answer?

Modification points:

At Advanced Google services, the arguments of Analytics.Management.ProfileFilterLinks.insert() are resource, accountId, webPropertyId, profileId.

In your python script, you are using the following values as the arguments of analytics.management().profileFilterLinks().insert().

```<code>accountId='123456',
webPropertyId='UA-123456-1',
profileId='7654321',
body={'filterRef': {'id': '1223334444'}}
</code>```

In this case, resource, accountId, webPropertyId, profileId are body, accountId, webPropertyId, profileId, respectively.

So how about the following modification?

Modified script:

```<code>var resource = {filterRef: {id: '1223334444'}};
var accountId = '123456';
var webPropertyId = 'UA-123456-1';
var profileId = '7654321';
var up = Analytics.Management.ProfileFilterLinks.insert(resource, accountId, webPropertyId, profileId);
</code>```

Note:

Please confirm whether the values of resource, accountId, webPropertyId, profileId are correct, again.

Reference:

Profile Filter Links: insert

Body:
I'm trying to build a small Google App Script with Google Analytics API management to copy Google Analytics filters from one view to another.

I've the following python snippet which I'd like to translate into Google App Script:

# This request creates a new profile filter link.
try:
  analytics.management().profileFilterLinks().insert(
      accountId='123456',
      webPropertyId='UA-123456-1',
      profileId='7654321',
      body={
          'filterRef': {
              'id': '1223334444'
          }
      }
  ).execute()

I'm able to get a list of profile filter link like this:

var filterLinks = Analytics.Management.ProfileFilterLinks.list(
      '12345678','UA-98765432-1','111111111')

I tried to replicate something similar with for the insert method but It doesn't work:

var body = JSON.stringify({
         'filterRef': {
             'id': '84029058'
}});

var up = Analytics.Management.ProfileFilterLinks.insert('12345678','UA-98765432-1','111111111',body)

any idea?

Body:
How about this answer?

Modification points:

At Advanced Google services, the arguments of Analytics.Management.ProfileFilterLinks.insert() are resource, accountId, webPropertyId, profileId.

In your python script, you are using the following values as the arguments of analytics.management().profileFilterLinks().insert().

accountId='123456',
webPropertyId='UA-123456-1',
profileId='7654321',
body={'filterRef': {'id': '1223334444'}}

In this case, resource, accountId, webPropertyId, profileId are body, accountId, webPropertyId, profileId, respectively.

So how about the following modification?

Modified script:

var resource = {filterRef: {id: '1223334444'}};
var accountId = '123456';
var webPropertyId = 'UA-123456-1';
var profileId = '7654321';
var up = Analytics.Management.ProfileFilterLinks.insert(resource, accountId, webPropertyId, profileId);

Note:

Please confirm whether the values of resource, accountId, webPropertyId, profileId are correct, again.

Reference:

Profile Filter Links: insert


问:
Get a list of all available languages in flutter
I need all available languages (with variants, like "English (United Kingdom)" )  in a DropdownButton, i couldn't find in the flutter SDK or dart builtins, so i ended scraping this site, and creating a filelang_list.dart with the following content

const LANGLIST = ["Afrikaans","Afrikaans (South Africa)","Arabic","Arabic (U.A.E.)","Arabic (Bahrain)","Arabic (Algeria)","Arabic (Egypt)","Arabic (Iraq)","Arabic (Jordan)","Arabic (Kuwait)","Arabic (Lebanon)","Arabic (Libya)","Arabic (Morocco)","Arabic (Oman)","Arabic (Qatar)","Arabic (Saudi Arabia)","Arabic (Syria)","Arabic (Tunisia)","Arabic (Yemen)","Azeri (Latin)","Azeri (Latin) (Azerbaijan)","Azeri (Cyrillic) (Azerbaijan)","Belarusian","Belarusian (Belarus)","Bulgarian","Bulgarian (Bulgaria)","Bosnian (Bosnia and Herzegovina)","Catalan","Catalan (Spain)","Czech","Czech (Czech Republic)","Welsh","Welsh (United Kingdom)","Danish","Danish (Denmark)","German","German (Austria)","German (Switzerland)","German (Germany)","German (Liechtenstein)","German (Luxembourg)","Divehi","Divehi (Maldives)","Greek","Greek (Greece)","English","English (Australia)","English (Belize)","English (Canada)","English (Caribbean)","English (United Kingdom)","English (Ireland)","English (Jamaica)","English (New Zealand)","English (Republic of the Philippines)","English (Trinidad and Tobago)","English (United States)","English (South Africa)","English (Zimbabwe)","Esperanto","Spanish","Spanish (Argentina)","Spanish (Bolivia)","Spanish (Chile)","Spanish (Colombia)","Spanish (Costa Rica)","Spanish (Dominican Republic)","Spanish (Ecuador)","Spanish (Castilian)","Spanish (Spain)","Spanish (Guatemala)","Spanish (Honduras)","Spanish (Mexico)","Spanish (Nicaragua)","Spanish (Panama)","Spanish (Peru)","Spanish (Puerto Rico)","Spanish (Paraguay)","Spanish (El Salvador)","Spanish (Uruguay)","Spanish (Venezuela)","Estonian","Estonian (Estonia)","Basque","Basque (Spain)","Farsi","Farsi (Iran)","Finnish","Finnish (Finland)","Faroese","Faroese (Faroe Islands)","French","French (Belgium)","French (Canada)","French (Switzerland)","French (France)","French (Luxembourg)","French (Principality of Monaco)","Galician","Galician (Spain)","Gujarati","Gujarati (India)","Hebrew","Hebrew (Israel)","Hindi","Hindi (India)","Croatian","Croatian (Bosnia and Herzegovina)","Croatian (Croatia)","Hungarian","Hungarian (Hungary)","Armenian","Armenian (Armenia)","Indonesian","Indonesian (Indonesia)","Icelandic","Icelandic (Iceland)","Italian","Italian (Switzerland)","Italian (Italy)","Japanese","Japanese (Japan)","Georgian","Georgian (Georgia)","Kazakh","Kazakh (Kazakhstan)","Kannada","Kannada (India)","Korean","Korean (Korea)","Konkani","Konkani (India)","Kyrgyz","Kyrgyz (Kyrgyzstan)","Lithuanian","Lithuanian (Lithuania)","Latvian","Latvian (Latvia)","Maori","Maori (New Zealand)","FYRO Macedonian","FYRO Macedonian (Former Yugoslav Republic of Macedonia)","Mongolian","Mongolian (Mongolia)","Marathi","Marathi (India)","Malay","Malay (Brunei Darussalam)","Malay (Malaysia)","Maltese","Maltese (Malta)","Norwegian (Bokm?l)","Norwegian (Bokm?l) (Norway)","Dutch","Dutch (Belgium)","Dutch (Netherlands)","Norwegian (Nynorsk) (Norway)","Northern Sotho","Northern Sotho (South Africa)","Punjabi","Punjabi (India)","Polish","Polish (Poland)","Pashto","Pashto (Afghanistan)","Portuguese","Portuguese (Brazil)","Portuguese (Portugal)","Quechua","Quechua (Bolivia)","Quechua (Ecuador)","Quechua (Peru)","Romanian","Romanian (Romania)","Russian","Russian (Russia)","Sanskrit","Sanskrit (India)","Sami (Northern)","Sami (Northern) (Finland)","Sami (Skolt) (Finland)","Sami (Inari) (Finland)","Sami (Northern) (Norway)","Sami (Lule) (Norway)","Sami (Southern) (Norway)","Sami (Northern) (Sweden)","Sami (Lule) (Sweden)","Sami (Southern) (Sweden)","Slovak","Slovak (Slovakia)","Slovenian","Slovenian (Slovenia)","Albanian","Albanian (Albania)","Serbian (Latin) (Bosnia and Herzegovina)","Serbian (Cyrillic) (Bosnia and Herzegovina)","Serbian (Latin) (Serbia and Montenegro)","Serbian (Cyrillic) (Serbia and Montenegro)","Swedish","Swedish (Finland)","Swedish (Sweden)","Swahili","Swahili (Kenya)","Syriac","Syriac (Syria)","Tamil","Tamil (India)","Telugu","Telugu (India)","Thai","Thai (Thailand)","Tagalog","Tagalog (Philippines)","Tswana","Tswana (South Africa)","Turkish","Turkish (Turkey)","Tatar","Tatar (Russia)","Tsonga","Ukrainian","Ukrainian (Ukraine)","Urdu","Urdu (Islamic Republic of Pakistan)","Uzbek (Latin)","Uzbek (Latin) (Uzbekistan)","Uzbek (Cyrillic) (Uzbekistan)","Vietnamese","Vietnamese (Viet Nam)","Xhosa","Xhosa (South Africa)","Chinese","Chinese (S)","Chinese (Hong Kong)","Chinese (Macau)","Chinese (Singapore)","Chinese (T)","Zulu","Zulu (South Africa)"];
```

so i can import in other files and uses this list.

Is this implementation ok? is there a method from flutter that does the same thing?

答:
Use the "language_pickers" Package.

https://pub.dev/packages/language_pickers

Body:
I need all available languages (with variants, like "English (United Kingdom)" )  in a DropdownButton, i couldn't find in the flutter SDK or dart builtins, so i ended scraping this site, and creating a filelang_list.dart with the following content

const LANGLIST = ["Afrikaans","Afrikaans (South Africa)","Arabic","Arabic (U.A.E.)","Arabic (Bahrain)","Arabic (Algeria)","Arabic (Egypt)","Arabic (Iraq)","Arabic (Jordan)","Arabic (Kuwait)","Arabic (Lebanon)","Arabic (Libya)","Arabic (Morocco)","Arabic (Oman)","Arabic (Qatar)","Arabic (Saudi Arabia)","Arabic (Syria)","Arabic (Tunisia)","Arabic (Yemen)","Azeri (Latin)","Azeri (Latin) (Azerbaijan)","Azeri (Cyrillic) (Azerbaijan)","Belarusian","Belarusian (Belarus)","Bulgarian","Bulgarian (Bulgaria)","Bosnian (Bosnia and Herzegovina)","Catalan","Catalan (Spain)","Czech","Czech (Czech Republic)","Welsh","Welsh (United Kingdom)","Danish","Danish (Denmark)","German","German (Austria)","German (Switzerland)","German (Germany)","German (Liechtenstein)","German (Luxembourg)","Divehi","Divehi (Maldives)","Greek","Greek (Greece)","English","English (Australia)","English (Belize)","English (Canada)","English (Caribbean)","English (United Kingdom)","English (Ireland)","English (Jamaica)","English (New Zealand)","English (Republic of the Philippines)","English (Trinidad and Tobago)","English (United States)","English (South Africa)","English (Zimbabwe)","Esperanto","Spanish","Spanish (Argentina)","Spanish (Bolivia)","Spanish (Chile)","Spanish (Colombia)","Spanish (Costa Rica)","Spanish (Dominican Republic)","Spanish (Ecuador)","Spanish (Castilian)","Spanish (Spain)","Spanish (Guatemala)","Spanish (Honduras)","Spanish (Mexico)","Spanish (Nicaragua)","Spanish (Panama)","Spanish (Peru)","Spanish (Puerto Rico)","Spanish (Paraguay)","Spanish (El Salvador)","Spanish (Uruguay)","Spanish (Venezuela)","Estonian","Estonian (Estonia)","Basque","Basque (Spain)","Farsi","Farsi (Iran)","Finnish","Finnish (Finland)","Faroese","Faroese (Faroe Islands)","French","French (Belgium)","French (Canada)","French (Switzerland)","French (France)","French (Luxembourg)","French (Principality of Monaco)","Galician","Galician (Spain)","Gujarati","Gujarati (India)","Hebrew","Hebrew (Israel)","Hindi","Hindi (India)","Croatian","Croatian (Bosnia and Herzegovina)","Croatian (Croatia)","Hungarian","Hungarian (Hungary)","Armenian","Armenian (Armenia)","Indonesian","Indonesian (Indonesia)","Icelandic","Icelandic (Iceland)","Italian","Italian (Switzerland)","Italian (Italy)","Japanese","Japanese (Japan)","Georgian","Georgian (Georgia)","Kazakh","Kazakh (Kazakhstan)","Kannada","Kannada (India)","Korean","Korean (Korea)","Konkani","Konkani (India)","Kyrgyz","Kyrgyz (Kyrgyzstan)","Lithuanian","Lithuanian (Lithuania)","Latvian","Latvian (Latvia)","Maori","Maori (New Zealand)","FYRO Macedonian","FYRO Macedonian (Former Yugoslav Republic of Macedonia)","Mongolian","Mongolian (Mongolia)","Marathi","Marathi (India)","Malay","Malay (Brunei Darussalam)","Malay (Malaysia)","Maltese","Maltese (Malta)","Norwegian (Bokm?l)","Norwegian (Bokm?l) (Norway)","Dutch","Dutch (Belgium)","Dutch (Netherlands)","Norwegian (Nynorsk) (Norway)","Northern Sotho","Northern Sotho (South Africa)","Punjabi","Punjabi (India)","Polish","Polish (Poland)","Pashto","Pashto (Afghanistan)","Portuguese","Portuguese (Brazil)","Portuguese (Portugal)","Quechua","Quechua (Bolivia)","Quechua (Ecuador)","Quechua (Peru)","Romanian","Romanian (Romania)","Russian","Russian (Russia)","Sanskrit","Sanskrit (India)","Sami (Northern)","Sami (Northern) (Finland)","Sami (Skolt) (Finland)","Sami (Inari) (Finland)","Sami (Northern) (Norway)","Sami (Lule) (Norway)","Sami (Southern) (Norway)","Sami (Northern) (Sweden)","Sami (Lule) (Sweden)","Sami (Southern) (Sweden)","Slovak","Slovak (Slovakia)","Slovenian","Slovenian (Slovenia)","Albanian","Albanian (Albania)","Serbian (Latin) (Bosnia and Herzegovina)","Serbian (Cyrillic) (Bosnia and Herzegovina)","Serbian (Latin) (Serbia and Montenegro)","Serbian (Cyrillic) (Serbia and Montenegro)","Swedish","Swedish (Finland)","Swedish (Sweden)","Swahili","Swahili (Kenya)","Syriac","Syriac (Syria)","Tamil","Tamil (India)","Telugu","Telugu (India)","Thai","Thai (Thailand)","Tagalog","Tagalog (Philippines)","Tswana","Tswana (South Africa)","Turkish","Turkish (Turkey)","Tatar","Tatar (Russia)","Tsonga","Ukrainian","Ukrainian (Ukraine)","Urdu","Urdu (Islamic Republic of Pakistan)","Uzbek (Latin)","Uzbek (Latin) (Uzbekistan)","Uzbek (Cyrillic) (Uzbekistan)","Vietnamese","Vietnamese (Viet Nam)","Xhosa","Xhosa (South Africa)","Chinese","Chinese (S)","Chinese (Hong Kong)","Chinese (Macau)","Chinese (Singapore)","Chinese (T)","Zulu","Zulu (South Africa)"];

so i can import in other files and uses this list.

Is this implementation ok? is there a method from flutter that does the same thing?


问:
error while trying to call a python function through js
I'm trying to call a python function through my js program, and i'm experiencing error:

```<code>eel.say_hello_py is not a function
</code>```

I just tried step by step of their docs and its not working, dont know why, what i'm missing?

my python program contains:

```<code>import eel

eel.init('web')
eel.start('index.html', mode='chrome-app')

@eel.expose                         # Expose this function to Javascript
def say_hello_py(x):
    print('Hello from %s' % x)
</code>```

my html contains:

```<code><!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="index.css">
<title>Document</title> </head>
<body>
<script type="text/javascript" src="/eel.js"></script>
<script src="index.js" type="text/javascript"></script> </body>
</html>
</code>```

my index.js file contains:

```<code>eel.say_hello_py("Javascript World!"); // Call a Python function
</code>```

my files construction:

```<code>web(folder)
   -> index.html
   -> index.js
python.py
</code>```

what i'm missing?

答:
find fast solution, moved the

eel.start('index.html', mode='chrome-app')

line, after the expose command.

```<code>import eel

eel.init('web')

@eel.expose                         # Expose this function to Javascript
def say_hello_py(x):
    print('Hello from %s' % x)

eel.start('index.html', mode='chrome-app')
</code>```

Body:
I'm trying to call a python function through my js program, and i'm experiencing error:

eel.say_hello_py is not a function

I just tried step by step of their docs and its not working, dont know why, what i'm missing?

my python program contains:

import eel

eel.init('web')
eel.start('index.html', mode='chrome-app')

@eel.expose                         # Expose this function to Javascript
def say_hello_py(x):
    print('Hello from %s' % x)

my html contains:

<!DOCTYPE html>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="index.css">
<title>Document</title>

my index.js file contains:

eel.say_hello_py("Javascript World!"); // Call a Python function

my files construction:

web(folder)
   -> index.html
   -> index.js
python.py

what i'm missing?

Body:
find fast solution, moved the

eel.start('index.html', mode='chrome-app')

line, after the expose command.

import eel

eel.init('web')

@eel.expose                         # Expose this function to Javascript
def say_hello_py(x):
    print('Hello from %s' % x)

eel.start('index.html', mode='chrome-app')