问:
How to overlap the JLabel onto a gif image?
I'm trying to make a game where numbers would fall from the top and if the player hits the number with the correct equation(math game), it will disappear.

The thing is, whenever I draw my background, the Jlabel keeps on displaying at the back of the giF background. Any ideas why??

This is like my core class.

```<code>package GAME;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

public class GameFrame extends JPanel implements ActionListener{

Image background = Toolkit.getDefaultToolkit().createImage("D:\\SHIPMATH TEXTURES\\simple-water-animation-597-x-800.gif");

Timer mainTimer;

shipPlayer player;
enemyShips enemy;

int level = 5;
int enemyCount = 5;
int numCount = 10;

// arraylists are arrays that has no capacity limit
static ArrayList<Numbers> number = new ArrayList<Numbers>();
static ArrayList<enemyShips> enemies = new ArrayList<enemyShips>();
static ArrayList<Cannons> cannon_balls = new ArrayList<Cannons>();

JLabel numbers;

Random rn = new Random();

public GameFrame() {
    // calls the actionPerformed method every 10 milliseconds
    mainTimer = new Timer(10, this);

    mainTimer.start();
    setLayout(null);

    numbers = new JLabel("TEST");
    numbers.setBounds(200, 200, 100, 100);
    add(numbers);

    setFocusable(true);

    player = new shipPlayer(0, 500);
    addKeyListener(new KeyAdapt(player));

    startGame();

}

public void paint(Graphics g) {
    super.paint(g);

    Graphics2D g2d = (Graphics2D) g;

//      g2d.drawImage(background, 0, 0, this);

    player.draw(g2d);

    repaint();

    for(int i=0; i<enemies.size(); i++) {

        // the value of 'i' is the location/index used to find the value stored in the ArrayList
        enemyShips enemy = enemies.get(i);
        enemy.draw(g2d);

    }

    for(int i=0; i<cannon_balls.size(); i++) {
        Cannons cannon = cannon_balls.get(i);
        cannon.draw(g2d);
    }

    }

    public void actionPerformed(ActionEvent e) {
    player.update();

    // where movement of the enemy happens
    for(int i=0; i<enemies.size(); i++) {
        enemyShips enemy = enemies.get(i);
        enemy.update();
    }

 //     Later...
    for(int i=0; i<cannon_balls.size(); i++) {
        Cannons cannon = cannon_balls.get(i);
        cannon.update();

    }

    repaint();

}

public static void addEnemy(enemyShips e) {

    enemies.add(e);
    // stores what the user puts in the enemyShips' object into the ArrayList "enemies"
}

public static void removeEnemy(enemyShips e) {
    enemies.remove(e);
    // removes what the user inputs from the ArrayList
}

public static ArrayList<enemyShips> getEnemyList() {
    return enemies;
}

public static void addNumbers(Numbers n) {
    number.add(n);
}

public static void addCannons(Cannons c) {

    cannon_balls.add(c);
    // stores what the user puts in the Cannons' object into the ArrayList "cannon_balls"
}

public static void removeCannons(Cannons c) {
    cannon_balls.remove(c);
    // removes what the user inputs from the ArrayList
}

public static ArrayList<Cannons> getCannonsList() {
    return cannon_balls;
}

public void startGame() {

//      enemyCount = level * 5;

    // runs 5 times
    for(int x=0; x<enemyCount; x++) {

        addEnemy(new enemyShips(rn.nextInt(500), -rn.nextInt(800)));

    }

}

}
</code>```

答:
The fix for your issue is to rename your paint method to paintComponent. Here's what you are doing right now:

```<code>public void paint(Graphics g) {
    super.paint(g); //this paints all of your JPanel's child components, including your JPanel

    Graphics2D g2d = (Graphics2D) g;

//      g2d.drawImage(background, 0, 0, this); // this is painting your background image over your JPanel.

    player.draw(g2d);

    ...
</code>```

If you use paintComponent instead, you won't have this problem with the child components being painted over

Body:
I'm trying to make a game where numbers would fall from the top and if the player hits the number with the correct equation(math game), it will disappear.

The thing is, whenever I draw my background, the Jlabel keeps on displaying at the back of the giF background. Any ideas why??

This is like my core class.

package GAME;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Random;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

public class GameFrame extends JPanel implements ActionListener{

Image background = Toolkit.getDefaultToolkit().createImage("D:\\SHIPMATH TEXTURES\\simple-water-animation-597-x-800.gif");

Timer mainTimer;

shipPlayer player;
enemyShips enemy;

int level = 5;
int enemyCount = 5;
int numCount = 10;

// arraylists are arrays that has no capacity limit
static ArrayList<Numbers> number = new ArrayList<Numbers>();
static ArrayList<enemyShips> enemies = new ArrayList<enemyShips>();
static ArrayList<Cannons> cannon_balls = new ArrayList<Cannons>();

JLabel numbers;

Random rn = new Random();

public GameFrame() {
    // calls the actionPerformed method every 10 milliseconds
    mainTimer = new Timer(10, this);

    mainTimer.start();
    setLayout(null);

    numbers = new JLabel("TEST");
    numbers.setBounds(200, 200, 100, 100);
    add(numbers);

    setFocusable(true);

    player = new shipPlayer(0, 500);
    addKeyListener(new KeyAdapt(player));

    startGame();

}

public void paint(Graphics g) {
    super.paint(g);

    Graphics2D g2d = (Graphics2D) g;

//      g2d.drawImage(background, 0, 0, this);

    player.draw(g2d);

    repaint();

    for(int i=0; i<enemies.size(); i++) {

        // the value of 'i' is the location/index used to find the value stored in the ArrayList
        enemyShips enemy = enemies.get(i);
        enemy.draw(g2d);

    }

    for(int i=0; i<cannon_balls.size(); i++) {
        Cannons cannon = cannon_balls.get(i);
        cannon.draw(g2d);
    }

    }

    public void actionPerformed(ActionEvent e) {
    player.update();

    // where movement of the enemy happens
    for(int i=0; i<enemies.size(); i++) {
        enemyShips enemy = enemies.get(i);
        enemy.update();
    }

 //     Later...
    for(int i=0; i<cannon_balls.size(); i++) {
        Cannons cannon = cannon_balls.get(i);
        cannon.update();

    }

    repaint();

}

public static void addEnemy(enemyShips e) {

    enemies.add(e);
    // stores what the user puts in the enemyShips' object into the ArrayList "enemies"
}

public static void removeEnemy(enemyShips e) {
    enemies.remove(e);
    // removes what the user inputs from the ArrayList
}

public static ArrayList<enemyShips> getEnemyList() {
    return enemies;
}

public static void addNumbers(Numbers n) {
    number.add(n);
}

public static void addCannons(Cannons c) {

    cannon_balls.add(c);
    // stores what the user puts in the Cannons' object into the ArrayList "cannon_balls"
}

public static void removeCannons(Cannons c) {
    cannon_balls.remove(c);
    // removes what the user inputs from the ArrayList
}

public static ArrayList<Cannons> getCannonsList() {
    return cannon_balls;
}

public void startGame() {

//      enemyCount = level * 5;

    // runs 5 times
    for(int x=0; x<enemyCount; x++) {

        addEnemy(new enemyShips(rn.nextInt(500), -rn.nextInt(800)));

    }

}

}

Body:
The fix for your issue is to rename your paint method to paintComponent. Here's what you are doing right now:

public void paint(Graphics g) {
    super.paint(g); //this paints all of your JPanel's child components, including your JPanel

    Graphics2D g2d = (Graphics2D) g;

//      g2d.drawImage(background, 0, 0, this); // this is painting your background image over your JPanel.

    player.draw(g2d);

    ...

If you use paintComponent instead, you won't have this problem with the child components being painted over


来源: stackexchange

问:
Cancel goroutine on new function call
I need to cancel any previous goroutine on every function call.  How would that be handled in Go?  I've seen channels used but I can't quite wrap my head around the examples and whether a select statement is necessary.

The desired result would be that only the last request subtasks are ran.

```<code>package main

import (
    "fmt"
    "time"
)

func main() {
    for i := 0; i < 5; i++ {
        go handleRequest(i)
        time.Sleep(1 * time.Second) // Time between requests
    }
}

func handleRequest(incr int) {
    fmt.Println("New request registered: ", incr + 1)
    for i := 0; i <= 3; i++ {
        fmt.Println("Request: ", incr + 1, " | Sub-task: ", i + 1)
        time.Sleep(2 * time.Second) // Time processing
    }
    return
}
</code>```

答:
Goroutine cancellation can be done using a context. If you need to cancel a previous goroutine, start it with a context and cancel it when a new one starts. You have to write the goroutine to periodically check for the context:

```<code>   var ctx context.Context
   var cancel context.CancelFunc
   for i := 0; i < 5; i++ {
        if cancel!=nil {
             // cancel previous goroutine
             cancel()
        }
        ctx,cancel=context.WithCancel(context.Background())
        // start goroutine with a new context
        go handleRequest(ctx,i)
        time.Sleep(1 * time.Second) // Time between requests
    }
    if cancel!=nil {
       cancel()
    }
</code>```

In your goroutine, you have to check for cancellation:

```<code>func handleRequest(ctx context.Context,incr int) {
    fmt.Println("New request registered: ", incr + 1)
    for i := 0; i <= 3; i++ {
        fmt.Println("Request: ", incr + 1, " | Sub-task: ", i + 1)
        time.Sleep(2 * time.Second) // Time processing
        select {
           case <-ctx.Done():
             // canceled
             return
           default:
             // not canceled
        }
    }
    return
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Cancel goroutine on new function call

Body:
I need to cancel any previous goroutine on every function call.  How would that be handled in Go?  I've seen channels used but I can't quite wrap my head around the examples and whether a select statement is necessary.

The desired result would be that only the last request subtasks are ran.

package main

import (
    "fmt"
    "time"
)

func main() {
    for i := 0; i < 5; i++ {
        go handleRequest(i)
        time.Sleep(1 * time.Second) // Time between requests
    }
}

func handleRequest(incr int) {
    fmt.Println("New request registered: ", incr + 1)
    for i := 0; i <= 3; i++ {
        fmt.Println("Request: ", incr + 1, " | Sub-task: ", i + 1)
        time.Sleep(2 * time.Second) // Time processing
    }
    return
}

Body:
Goroutine cancellation can be done using a context. If you need to cancel a previous goroutine, start it with a context and cancel it when a new one starts. You have to write the goroutine to periodically check for the context:

   var ctx context.Context
   var cancel context.CancelFunc
   for i := 0; i < 5; i++ {
        if cancel!=nil {
             // cancel previous goroutine
             cancel()
        }
        ctx,cancel=context.WithCancel(context.Background())
        // start goroutine with a new context
        go handleRequest(ctx,i)
        time.Sleep(1 * time.Second) // Time between requests
    }
    if cancel!=nil {
       cancel()
    }

In your goroutine, you have to check for cancellation:

func handleRequest(ctx context.Context,incr int) {
    fmt.Println("New request registered: ", incr + 1)
    for i := 0; i <= 3; i++ {
        fmt.Println("Request: ", incr + 1, " | Sub-task: ", i + 1)
        time.Sleep(2 * time.Second) // Time processing
        select {
           case <-ctx.Done():
             // canceled
             return
           default:
             // not canceled
        }
    }
    return
}


问:
Extension method on number in TypeScript
I have read that it's possible to add Extension Methods to types in TypeScript, however having a little trouble applying this to built-in type Number.

Here's some code:

File A: NumberExtensions.ts

```<code>// tslint:disable-next-line:class-name interface-name
export interface Number {
    isBigNumber(value: number): boolean;
}
// @ts-ignore
Number.prototype.isBigNumber = (value: number) => {
    return value > 100000;
};
</code>```

File B: Uses the above

```<code>import { Number } from "./NumberExtensions";

foo() {
    const aBigNumber: number = 1000000000;

    // Errors here TS2339: Property 'isBigNumber' does not exist on type 'number'.
    if (aBigNumber.isBigNumber()) {
        console.log("It's a big number!");
    }
}
</code>```

Is my declaration and usage of TypeScript extension methods correct?

答:
Since you define the augmentation in a file that is a module you will need to add the augmentation declaration in a declare global:

```<code>
export { }
declare global {
    export interface Number {
        isBigNumber(): boolean;
    }
}
Number.prototype.isBigNumber = function (this: number)  {
    return this > 100000;
};

function foo() {
    const aBigNumber: number = 1000000000;

    // Errors here TS2339: Property 'isBigNumber' does not exist on type 'number'.
    if (aBigNumber.isBigNumber()) {
        console.log("It's a big number!");
    }
}

</code>```

Playground Link

Body:
I have read that it's possible to add Extension Methods to types in TypeScript, however having a little trouble applying this to built-in type Number.

Here's some code:

File A: NumberExtensions.ts

// tslint:disable-next-line:class-name interface-name
export interface Number {
    isBigNumber(value: number): boolean;
}
// @ts-ignore
Number.prototype.isBigNumber = (value: number) => {
    return value > 100000;
};

File B: Uses the above

import { Number } from "./NumberExtensions";

foo() {
    const aBigNumber: number = 1000000000;

    // Errors here TS2339: Property 'isBigNumber' does not exist on type 'number'.
    if (aBigNumber.isBigNumber()) {
        console.log("It's a big number!");
    }
}

Is my declaration and usage of TypeScript extension methods correct?

Body:
Since you define the augmentation in a file that is a module you will need to add the augmentation declaration in a declare global:

export { }
declare global {
    export interface Number {
        isBigNumber(): boolean;
    }
}
Number.prototype.isBigNumber = function (this: number)  {
    return this > 100000;
};

function foo() {
    const aBigNumber: number = 1000000000;

    // Errors here TS2339: Property 'isBigNumber' does not exist on type 'number'.
    if (aBigNumber.isBigNumber()) {
        console.log("It's a big number!");
    }
}

Playground Link


问:
I need to change the colour of a button in an android widget
I have a widget with a button that users must press within a given interval. The button works fine and resets the interval but I want the button to change colour green -> amber -> red depending on time left. I have no problem changing the text on the button using remote views with code like this:

```<code>RemoteViews views =new RemoteViews(context.getPackageName(), R.layout.example_widget);
views.setCharSequence(R.id.example_widget_button, "setText", buttonText);
</code>```

But I can not make any sort of code change the button colour. I've tried several things along the lines of:

```<code>views.setCharSequence(R.id.example_widget_button, "setBackgroundTint", "#039be5");
</code>```

I have also tried using a drawable background and changing that. I'm missing something really obvious -it must be possible- I just can't find an example that works in my context.

Can anyone point me?

答:
You can either use Handler or CountDownTimer.

If you want to use Handler, here is the example:

long totalTime = 10000;
long warningTime = 6000;
long alertTime = 30000;

Runnable warningColorChangeRunnable = new Runnable() {
    @Override
    public void run() {
        button.setBackgroundColor(getResources().getColor(R.color.colorWarning));
    }
};

Runnable alertColorChangeRunnable = new Runnable() {
    @Override
    public void run() {
        button.setBackgroundColor(getResources().getColor(R.color.colorAlert));
    }
};

final Handler handler = new Handler();
handler.postDelayed(warningColorChangeRunnable, totalTime - warningTime);
handler.postDelayed(alertColorChangeRunnable, totalTime - alertTime);

button.setOnClickListener(new OnClickListener() {
    @Override public void onClick(View view) {
        handler.removeCallbacks(warningColorChangeRunnable);
        handler.removeCallbacks(alertColorChangeRunnable);
    }
});
```

<p>If you want to use <code>CountDownTimer</code>, here is the example:</p>

<pre class="lang-java prettyprint-override"><code>long totalTime = 10000;
long warningTime = 6000;
long alertTime = 30000;
long interval = 1000;

CountDownTimer timer = new CountDownTimer(totalTime, 1000) {

    public void onTick(long millisUntilFinished) {
        if (millisUntilFinished <= warningTime && millisUntilFinished > warningTime - interval) {
            button.setBackgroundColor(getResources().getColor(R.color.colorWarning));
        }
        if (millisUntilFinished <= alertTime && millisUntilFinished > alertTime - interval) {
            button.setBackgroundColor(getResources().getColor(R.color.colorAlert));
        }
    }

    public void onFinish() {
        // Maybe show a failure dialog
    }
}.start();

button.setOnClickListener(new OnClickListener() {
    @Override public void onClick(View view) {
        timer.cancel();
    }
});
</code>```

Body:
I have a widget with a button that users must press within a given interval. The button works fine and resets the interval but I want the button to change colour green -> amber -> red depending on time left. I have no problem changing the text on the button using remote views with code like this:

RemoteViews views =new RemoteViews(context.getPackageName(), R.layout.example_widget);
views.setCharSequence(R.id.example_widget_button, "setText", buttonText);

But I can not make any sort of code change the button colour. I've tried several things along the lines of:

views.setCharSequence(R.id.example_widget_button, "setBackgroundTint", "#039be5");

I have also tried using a drawable background and changing that. I'm missing something really obvious -it must be possible- I just can't find an example that works in my context.

Can anyone point me?

Body:
You can either use Handler or CountDownTimer.

If you want to use Handler, here is the example:

long totalTime = 10000;
long warningTime = 6000;
long alertTime = 30000;

Runnable warningColorChangeRunnable = new Runnable() {
    @Override
    public void run() {
        button.setBackgroundColor(getResources().getColor(R.color.colorWarning));
    }
};

Runnable alertColorChangeRunnable = new Runnable() {
    @Override
    public void run() {
        button.setBackgroundColor(getResources().getColor(R.color.colorAlert));
    }
};

final Handler handler = new Handler();
handler.postDelayed(warningColorChangeRunnable, totalTime - warningTime);
handler.postDelayed(alertColorChangeRunnable, totalTime - alertTime);

button.setOnClickListener(new OnClickListener() {
    @Override public void onClick(View view) {
        handler.removeCallbacks(warningColorChangeRunnable);
        handler.removeCallbacks(alertColorChangeRunnable);
    }
});

If you want to use CountDownTimer, here is the example:

long totalTime = 10000;
long warningTime = 6000;
long alertTime = 30000;
long interval = 1000;

CountDownTimer timer = new CountDownTimer(totalTime, 1000) {

    public void onTick(long millisUntilFinished) {
        if (millisUntilFinished <= warningTime && millisUntilFinished > warningTime - interval) {
            button.setBackgroundColor(getResources().getColor(R.color.colorWarning));
        }
        if (millisUntilFinished <= alertTime && millisUntilFinished > alertTime - interval) {
            button.setBackgroundColor(getResources().getColor(R.color.colorAlert));
        }
    }

    public void onFinish() {
        // Maybe show a failure dialog
    }
}.start();

button.setOnClickListener(new OnClickListener() {
    @Override public void onClick(View view) {
        timer.cancel();
    }
});


问:
Is there a fast and non-fancy C# code/algorithm to compress a string of comma separated digits close to maximum info density?
In a nutshell, I programmed myself into a corner by creating a CLR aggregate that performs row id concatenation, so I say:

```<code>select SumKeys(id), name from SomeTable where name='multiple rows named this'
</code>```

and I get something like:

```<code>SumKeys         name
--------        ---------
1,4,495         multiple rows named this
</code>```

But it dies when SumKeys gets > 8000 chars and I don't think I can do anything about it.

As a quick fix (it's only failing 1% of the time for my application) I thought I might compress the string down and I thought some of you bright people out there might know a slick way to do this.

Something like base64 made for 0-9 and a comma?

答:
You'd be much better of if you figure out more reasonable storage for your data (maybe HashSet)...

But for compression try regular System.IO.Compression.GZipStream ( http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx ) and convert resulting byte array to base64 string if needed... or store as byte array.

ContentLicense: CC BY-SA 3.0

Body:
In a nutshell, I programmed myself into a corner by creating a CLR aggregate that performs row id concatenation, so I say:

select SumKeys(id), name from SomeTable where name='multiple rows named this'

and I get something like:

SumKeys         name
--------        ---------
1,4,495         multiple rows named this

But it dies when SumKeys gets > 8000 chars and I don't think I can do anything about it.

As a quick fix (it's only failing 1% of the time for my application) I thought I might compress the string down and I thought some of you bright people out there might know a slick way to do this.

Something like base64 made for 0-9 and a comma?


问:
Get ConstraintLayout in a Fragment
Good Daay,

I'd like to get a ConstraintLayout in a Fragment, however when debugging it priints
this error
 `

java.lang.NullPointerException: Attempt to invoke virtual method 'int androidx.constraintlayout.widget.ConstraintLayout.getChildCount()' on a null object reference

on this line

constraintSet.clone(constraintLayout);

So here are my activity used for the fragment and below the code of the fragment

fragment_activity:

```<code> <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.something.fragments.Fragment"
    android:id="@+id/this_fragment">

...

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

And here my code:

```<code>public class Fragment extends AppCompatDialogFragment {

View view;

@SuppressLint("InflateParams")
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(Objects.requireNonNull(getActivity()), R.style.Some_Theme_Name);
    LayoutInflater inflater = getActivity().getLayoutInflater();
    view = inflater.inflate(R.layout.fragment_activity, null);

    ConstraintLayout constraintLayout = getActivity().findViewById(R.id.this_fragment);
    ConstraintSet constraintSet = new ConstraintSet();
    constraintSet.clone(constraintLayout);

    return builder.create();
}

}
</code>```

Help would be really appreciated

答:
Try this way:</p>

```<code>    ConstraintLayout constraintLayout = view.findViewById(R.id.this_fragment);
    ConstraintSet constraintSet = new ConstraintSet();
    constraintSet.clone(constraintLayout);
</code>```

Title: Get ConstraintLayout in a Fragment

Body:
Good Daay,

I'd like to get a ConstraintLayout in a Fragment, however when debugging it priints
this error
 `

java.lang.NullPointerException: Attempt to invoke virtual method 'int androidx.constraintlayout.widget.ConstraintLayout.getChildCount()' on a null object reference

on this line

constraintSet.clone(constraintLayout);

So here are my activity used for the fragment and below the code of the fragment

fragment_activity:

 <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.something.fragments.Fragment"
    android:id="@+id/this_fragment">

...

</androidx.constraintlayout.widget.ConstraintLayout>

And here my code:

public class Fragment extends AppCompatDialogFragment {

View view;

@SuppressLint("InflateParams")
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(Objects.requireNonNull(getActivity()), R.style.Some_Theme_Name);
    LayoutInflater inflater = getActivity().getLayoutInflater();
    view = inflater.inflate(R.layout.fragment_activity, null);

    ConstraintLayout constraintLayout = getActivity().findViewById(R.id.this_fragment);
    ConstraintSet constraintSet = new ConstraintSet();
    constraintSet.clone(constraintLayout);

    return builder.create();
}

}

Help would be really appreciated

Body:
Try this way:

    ConstraintLayout constraintLayout = view.findViewById(R.id.this_fragment);
    ConstraintSet constraintSet = new ConstraintSet();
    constraintSet.clone(constraintLayout);


问:
How to pull the key and value of an item with the maximum value out of a python dictionary
The following code creates a dictionary of email addresses and how frequently each email appears.  What is the best way to pull out the key and value for the email with the max frequency?</p>

```<code>fname = input("Enter file:")
try:
    fhand = open(fname)
except:
    print('File cannot be opened:')
    exit()
counts = dict()
for line in fhand:
    if line.startswith('From:'):
         words = line.split(' ', 1)[1]
         words = words.rstrip('\n')

         counts[words] = counts.get(words,0)+1

print(counts)
</code>```

答:
You can invert the key and value in a comprehension and use max() normally:</p>

```<code>count,word = max(c,w for w,c in counts.items())
</code>```

Body:
The following code creates a dictionary of email addresses and how frequently each email appears.  What is the best way to pull out the key and value for the email with the max frequency?

fname = input("Enter file:")
try:
    fhand = open(fname)
except:
    print('File cannot be opened:')
    exit()
counts = dict()
for line in fhand:
    if line.startswith('From:'):
         words = line.split(' ', 1)[1]
         words = words.rstrip('\n')

         counts[words] = counts.get(words,0)+1

print(counts)

Body:
You can invert the key and value in a comprehension and use max() normally:

count,word = max(c,w for w,c in counts.items())


问:
java.lang.NumberFormatException: For input string: "inf" when reading from snowflake with Spark
I've a Snowflake table that has a column with doubles. One of the values are inf and -inf.

When I try to read this table in Spark, the job fails with the following error:

```<code>java.lang.NumberFormatException: For input string: "inf"
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
    at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    at java.lang.Double.parseDouble(Double.java:538)
    at scala.collection.immutable.StringLike$class.toDouble(StringLike.scala:285)
    at scala.collection.immutable.StringOps.toDouble(StringOps.scala:29)
    at net.snowflake.spark.snowflake.Conversions$$anonfun$1.apply(Conversions.scala:156)
    at net.snowflake.spark.snowflake.Conversions$$anonfun$1.apply(Conversions.scala:144)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
    at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
    at scala.collection.mutable.ArrayOps$ofRef.foreach(ArrayOps.scala:186)
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:234)
    at scala.collection.mutable.ArrayOps$ofRef.map(ArrayOps.scala:186)
    at net.snowflake.spark.snowflake.Conversions$.net$snowflake$spark$snowflake$Conversions$$convertRow(Conversions.scala:144)
    at net.snowflake.spark.snowflake.Conversions$$anonfun$createRowConverter$1.apply(Conversions.scala:132)
    at net.snowflake.spark.snowflake.Conversions$$anonfun$createRowConverter$1.apply(Conversions.scala:132)
    at net.snowflake.spark.snowflake.CSVConverter$$anonfun$convert$1.apply(CSVConverter.scala:73)
    at net.snowflake.spark.snowflake.CSVConverter$$anonfun$convert$1.apply(CSVConverter.scala:34)
    at scala.collection.Iterator$$anon$11.next(Iterator.scala:410)
    at scala.collection.Iterator$$anon$11.next(Iterator.scala:410)
    at org.apache.spark.sql.execution.columnar.CachedRDDBuilder$$anonfun$1$$anon$1.next(InMemoryRelation.scala:100)
    at org.apache.spark.sql.execution.columnar.CachedRDDBuilder$$anonfun$1$$anon$1.next(InMemoryRelation.scala:90)
    at org.apache.spark.storage.memory.MemoryStore.putIterator(MemoryStore.scala:221)
    at org.apache.spark.storage.memory.MemoryStore.putIteratorAsValues(MemoryStore.scala:298)
    at org.apache.spark.storage.BlockManager$$anonfun$doPutIterator$1.apply(BlockManager.scala:1165)
    at org.apache.spark.storage.BlockManager$$anonfun$doPutIterator$1.apply(BlockManager.scala:1156)
    at org.apache.spark.storage.BlockManager.doPut(BlockManager.scala:1091)
    at org.apache.spark.storage.BlockManager.doPutIterator(BlockManager.scala:1156)
    at org.apache.spark.storage.BlockManager.getOrElseUpdate(BlockManager.scala:882)
    at org.apache.spark.rdd.RDD.getOrCompute(RDD.scala:335)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:286)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:402)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:408)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
</code>```

When looking at where the error happens, it seems to be in the row conversion in Conversions.scala with data.toDouble

```<code>at net.snowflake.spark.snowflake.Conversions$$anonfun$1.apply(Conversions.scala:156)
</code>```

data.toDouble will not work if the input is inf. In scala the value should be Infinity instead. (which comes from Double.PositiveInfinity.toString)

What should be the workaround to avoid crashing in similar cases?

答: This is fixed as of v 2.6.0 of the spark connector, here is the PR.</p>

Body:
I've a Snowflake table that has a column with doubles. One of the values are inf and -inf.

When I try to read this table in Spark, the job fails with the following error:

java.lang.NumberFormatException: For input string: "inf"
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)
    at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    at java.lang.Double.parseDouble(Double.java:538)
    at scala.collection.immutable.StringLike$class.toDouble(StringLike.scala:285)
    at scala.collection.immutable.StringOps.toDouble(StringOps.scala:29)
    at net.snowflake.spark.snowflake.Conversions$$anonfun$1.apply(Conversions.scala:156)
    at net.snowflake.spark.snowflake.Conversions$$anonfun$1.apply(Conversions.scala:144)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
    at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
    at scala.collection.mutable.ArrayOps$ofRef.foreach(ArrayOps.scala:186)
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:234)
    at scala.collection.mutable.ArrayOps$ofRef.map(ArrayOps.scala:186)
    at net.snowflake.spark.snowflake.Conversions$.net$snowflake$spark$snowflake$Conversions$$convertRow(Conversions.scala:144)
    at net.snowflake.spark.snowflake.Conversions$$anonfun$createRowConverter$1.apply(Conversions.scala:132)
    at net.snowflake.spark.snowflake.Conversions$$anonfun$createRowConverter$1.apply(Conversions.scala:132)
    at net.snowflake.spark.snowflake.CSVConverter$$anonfun$convert$1.apply(CSVConverter.scala:73)
    at net.snowflake.spark.snowflake.CSVConverter$$anonfun$convert$1.apply(CSVConverter.scala:34)
    at scala.collection.Iterator$$anon$11.next(Iterator.scala:410)
    at scala.collection.Iterator$$anon$11.next(Iterator.scala:410)
    at org.apache.spark.sql.execution.columnar.CachedRDDBuilder$$anonfun$1$$anon$1.next(InMemoryRelation.scala:100)
    at org.apache.spark.sql.execution.columnar.CachedRDDBuilder$$anonfun$1$$anon$1.next(InMemoryRelation.scala:90)
    at org.apache.spark.storage.memory.MemoryStore.putIterator(MemoryStore.scala:221)
    at org.apache.spark.storage.memory.MemoryStore.putIteratorAsValues(MemoryStore.scala:298)
    at org.apache.spark.storage.BlockManager$$anonfun$doPutIterator$1.apply(BlockManager.scala:1165)
    at org.apache.spark.storage.BlockManager$$anonfun$doPutIterator$1.apply(BlockManager.scala:1156)
    at org.apache.spark.storage.BlockManager.doPut(BlockManager.scala:1091)
    at org.apache.spark.storage.BlockManager.doPutIterator(BlockManager.scala:1156)
    at org.apache.spark.storage.BlockManager.getOrElseUpdate(BlockManager.scala:882)
    at org.apache.spark.rdd.RDD.getOrCompute(RDD.scala:335)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:286)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
    at org.apache.spark.scheduler.Task.run(Task.scala:121)
    at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:402)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:408)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

When looking at where the error happens, it seems to be in the row conversion in Conversions.scala with data.toDouble

at net.snowflake.spark.snowflake.Conversions$$anonfun$1.apply(Conversions.scala:156)

data.toDouble will not work if the input is inf. In scala the value should be Infinity instead. (which comes from Double.PositiveInfinity.toString)

What should be the workaround to avoid crashing in similar cases?


问:
No pop animation in iOS 13
I have an old app that I'm trying to update to fix a bug that appeared in iOS 13. Unfortunately, updating to the iOS 13 SDK triggered several other bugs. I've fixed them all, mostly through tweaks to the info.plist file, except this one thing.

I'm using a standard UINavigationController to display a series of table views. When I click a table row, that triggers pushViewController:animated: to go to the next view. This looks fine and animates correctly, but the console shows the message "Unbalanced calls to begin/end appearance transitions" for the view that I'm leaving.

When I click the back button, or swipe from left to right on the view, the previous view appears immediately, with no animation. The console again shows the warning "Unbalanced calls to begin/end appearance transitions" for the outgoing view. The navigation bar animates correctly, fading from the old view to the new view, but the view doesn't animate. I get the same behavior if I navigate back by swiping. In fact, if I swipe back very slowly, the view pops immediately when the swipe begins, rather than slowly dragging the old view into place as I move my finger.

I've found many posts where this happens when placing a navigation controller inside a tab bar controller, which I'm not doing, or when programmatically pushing views, which I'm not doing. I've checked that every override of viewWillAppear or viewDidAppear calls its superclass, and I have no mismatched calls (calling super viewDidAppear from viewWillAppear or vice versa).

I'm not using storyboards, just plain old objective C code with the pushViewController method. I do set up and place the navigation controller programmatically in a container view controller, like this:

```<code>MainMenu *rootViewController = [[MainMenu alloc] initWithNibName:@"MainMenu" bundle:nil];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController];
self.navigationController.delegate = self;
[self addChildViewController:self.navigationController];
[self.navigationController didMoveToParentViewController:self];
[self.view addSubview:self.navigationController.view];
</code>```

The app works perfectly when I run it on an iOS 12 device. The problem only occurs on an iOS 13 device. I have another app that uses the same structure and was originally built around the same time, but regularly updated for iOS releases, and it doesn't have the problem. I've compared every file and setting I can think of and can't find a relevant difference between the two apps.

Has anyone else seen this when updating for iOS 13?

UPDATE

To eliminate any issues from the container view, I temporarily changed the app to place the navigation controller directly into the window. So I now have this in application:DidFinishLaunchingWithOptions::

```<code>MainMenu *mainMenu = [[MainMenu alloc] initWithNibName:@"MainMenu" bundle:nil];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:mainMenu];
[self.window addSubview:self.navigationController.view];
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
</code>```

Then to eliminate any issues with the view controller I'm navigating to, I made a new nib containing only an empty view, and in MainMenu, when clicking a table row, I run this code:

```<code>UIViewController *viewController = [[UIViewController alloc] initWithNibName:@"Empty" bundle:nil];
[self.appDelegate.navigationController pushViewController:viewController animated:YES];
</code>```

Then I click the system-provided back button in the top left corner, and the MainMenu reappears, but without the animation and with the same console message. I feel like this has something to do with my project settings, since the code is so simple and straightforward. I ran a diff between the project.pbxproj file from this project and a different project that doesn't have the problem, and there were differences for things like compiler settings or bitcode, but nothing seemed relevant to this issue.

答:
There is more going on here than you are telling us about. I tried what you have described, using a navigation controller as a manually embedded view controller, and it works fine. As you can see, we animate Back in good order (I have turned on Slow Animations for clarity):

The "unbalanced transition" calls sound important, but you have provided no information for discovering what might be causing them.

Title: No pop animation in iOS 13

Body:
I have an old app that I'm trying to update to fix a bug that appeared in iOS 13. Unfortunately, updating to the iOS 13 SDK triggered several other bugs. I've fixed them all, mostly through tweaks to the info.plist file, except this one thing.

I'm using a standard UINavigationController to display a series of table views. When I click a table row, that triggers pushViewController:animated: to go to the next view. This looks fine and animates correctly, but the console shows the message "Unbalanced calls to begin/end appearance transitions" for the view that I'm leaving.

When I click the back button, or swipe from left to right on the view, the previous view appears immediately, with no animation. The console again shows the warning "Unbalanced calls to begin/end appearance transitions" for the outgoing view. The navigation bar animates correctly, fading from the old view to the new view, but the view doesn't animate. I get the same behavior if I navigate back by swiping. In fact, if I swipe back very slowly, the view pops immediately when the swipe begins, rather than slowly dragging the old view into place as I move my finger.

I've found many posts where this happens when placing a navigation controller inside a tab bar controller, which I'm not doing, or when programmatically pushing views, which I'm not doing. I've checked that every override of viewWillAppear or viewDidAppear calls its superclass, and I have no mismatched calls (calling super viewDidAppear from viewWillAppear or vice versa).

I'm not using storyboards, just plain old objective C code with the pushViewController method. I do set up and place the navigation controller programmatically in a container view controller, like this:

MainMenu *rootViewController = [[MainMenu alloc] initWithNibName:@"MainMenu" bundle:nil];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:rootViewController];
self.navigationController.delegate = self;
[self addChildViewController:self.navigationController];
[self.navigationController didMoveToParentViewController:self];
[self.view addSubview:self.navigationController.view];

The app works perfectly when I run it on an iOS 12 device. The problem only occurs on an iOS 13 device. I have another app that uses the same structure and was originally built around the same time, but regularly updated for iOS releases, and it doesn't have the problem. I've compared every file and setting I can think of and can't find a relevant difference between the two apps.

Has anyone else seen this when updating for iOS 13?

UPDATE

To eliminate any issues from the container view, I temporarily changed the app to place the navigation controller directly into the window. So I now have this in application:DidFinishLaunchingWithOptions::

MainMenu *mainMenu = [[MainMenu alloc] initWithNibName:@"MainMenu" bundle:nil];
self.navigationController = [[UINavigationController alloc] initWithRootViewController:mainMenu];
[self.window addSubview:self.navigationController.view];
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];

Then to eliminate any issues with the view controller I'm navigating to, I made a new nib containing only an empty view, and in MainMenu, when clicking a table row, I run this code:

UIViewController *viewController = [[UIViewController alloc] initWithNibName:@"Empty" bundle:nil];
[self.appDelegate.navigationController pushViewController:viewController animated:YES];

Then I click the system-provided back button in the top left corner, and the MainMenu reappears, but without the animation and with the same console message. I feel like this has something to do with my project settings, since the code is so simple and straightforward. I ran a diff between the project.pbxproj file from this project and a different project that doesn't have the problem, and there were differences for things like compiler settings or bitcode, but nothing seemed relevant to this issue.


问:
ModuleNotFoundError: No module named 'pandas.plotting._timeseries'
not very proficient yet in python and i'm trying to run :

import pyfolio as pf
pf.create_full_tear_sheet(portfolio.mean(axis=1))
```

(reference in the end of: https://blog.quantinsti.com/xgboost-python/)

in Anaconda/Spyder but get the

ModuleNotFoundError: No module named 'pandas.plotting._timeseries'

checked that pyfolio is installed and googled the error but didn't come across any solutions.

Would really appreciate some help.
tx!

答:
It seems the pandas.plotting._timeseries module is only available for pandas versions before 0.25.x.

You can see the _timeseries module is present in 0.24.x
 and is removed in 0.25.x (looks like the API changed to pandas.plotting._matplotlib.timeseries).

If you install an older version of pandas (anything before 0.25.x), it should work. Here's an example for last 0.24.x release:

```<code>pip install pandas==0.24.2
</code>```

Body:
not very proficient yet in python and i'm trying to run :

import pyfolio as pf
pf.create_full_tear_sheet(portfolio.mean(axis=1))

(reference in the end of: https://blog.quantinsti.com/xgboost-python/)

in Anaconda/Spyder but get the

ModuleNotFoundError: No module named 'pandas.plotting._timeseries'

checked that pyfolio is installed and googled the error but didn't come across any solutions.

Would really appreciate some help.
tx!

Body:
It seems the pandas.plotting._timeseries module is only available for pandas versions before 0.25.x.

You can see the _timeseries module is present in 0.24.x
 and is removed in 0.25.x (looks like the API changed to pandas.plotting._matplotlib.timeseries).

If you install an older version of pandas (anything before 0.25.x), it should work. Here's an example for last 0.24.x release:

pip install pandas==0.24.2


问:
Question about why "Set cannot change my json file value"
This is my feature file:

 * def Json = read ('1.json')
    * print Json.Id
    * set Json.Id = Product_Num
    * print Json.Id
```

I want to replace my Id with new Product number.  After run Karate, I see the result is correct, new Product_num is put out (by the second print out result)

But id value doesn't update in 1.json file.

How to update 1.json file values? I need to replace id values in 1.json file

答:
You are trying to write to a file. This is normally never needed when you use Karate, and hence is not supported directly. Do you want your test data changing all the time because your tests are updating the files from which test data is being read ? I don't think so.

Please read this answer for details: https://stackoverflow.com/a/54593057/143475

Body:
This is my feature file:

 * def Json = read ('1.json')
    * print Json.Id
    * set Json.Id = Product_Num
    * print Json.Id

I want to replace my Id with new Product number.  After run Karate, I see the result is correct, new Product_num is put out (by the second print out result)

But id value doesn't update in 1.json file.

How to update 1.json file values? I need to replace id values in 1.json file


问:
Sorting an array of tables
This may be easier than I'm making it on myself.  I am relatively new to Lua, but experienced in other languages.

I have a table that looks like this:

```<code>local state = {}
state[1] = {
   show = true,
   changed = true,
   progressType = "static",
   value = 0,
   total = 9,
   name = "nine",
}

state[2] = {
   show = true,
   changed = true,
   progressType = "static",
   value = 0,
   total = 7,
   name = "seven",
}

state[3] = {
   show = true,
   changed = true,
   progressType = "static",
   value = 0,
   total = 8,
   name = "eight",
}

state[4] = {
   show = true,
   changed = true,
   progressType = "static",
   value = 0,
   total = 6,
   name = "six",
}
</code>```

What I need to do is sort each table[] entry based on the value of table.value5.  I can't find any functions in the docs that expressely say they do more than just a basic table.sort so I find myself a bit stuck.  Do I need to manually sort by iterating through and creating a new table with the sorted data?

答:
I can't find any functions in the docs that expressely say they do more than just a basic table.sort so I find myself a bit stuck.

I might be misunderstanding your issue, but table.sort is exactly what you need in this case:

local state = {}
state[1] = {
   total = 9,
   name = "nine",
}

state[2] = {
   total = 7,
   name = "seven",
}

state[3] = {
   total = 8,
   name = "eight",
}

state[4] = {
   total = 6,
   name = "six",
}

-- Use table.sort with a custom anonymous function
-- to specify how to compare the nested tables.
table.sort(state, function (a, b)
    return a.total < b.total
end)

for i=1, #state do
  print(i, state[i].name)
end
```

With table.sort you can provide an optional custom function, which can be as easy or complicated as you want it to be. In this case (as per your question) it is enough to simply compare the total values of your table.

Title: Sorting an array of tables

Body:
This may be easier than I'm making it on myself.  I am relatively new to Lua, but experienced in other languages.

I have a table that looks like this:

local state = {}
state[1] = {
   show = true,
   changed = true,
   progressType = "static",
   value = 0,
   total = 9,
   name = "nine",
}

state[2] = {
   show = true,
   changed = true,
   progressType = "static",
   value = 0,
   total = 7,
   name = "seven",
}

state[3] = {
   show = true,
   changed = true,
   progressType = "static",
   value = 0,
   total = 8,
   name = "eight",
}

state[4] = {
   show = true,
   changed = true,
   progressType = "static",
   value = 0,
   total = 6,
   name = "six",
}

What I need to do is sort each table[] entry based on the value of table.value5.  I can't find any functions in the docs that expressely say they do more than just a basic table.sort so I find myself a bit stuck.  Do I need to manually sort by iterating through and creating a new table with the sorted data?

Body:
I can't find any functions in the docs that expressely say they do more than just a basic table.sort so I find myself a bit stuck.

I might be misunderstanding your issue, but table.sort is exactly what you need in this case:

local state = {}
state[1] = {
   total = 9,
   name = "nine",
}

state[2] = {
   total = 7,
   name = "seven",
}

state[3] = {
   total = 8,
   name = "eight",
}

state[4] = {
   total = 6,
   name = "six",
}

-- Use table.sort with a custom anonymous function
-- to specify how to compare the nested tables.
table.sort(state, function (a, b)
    return a.total < b.total
end)

for i=1, #state do
  print(i, state[i].name)
end

With table.sort you can provide an optional custom function, which can be as easy or complicated as you want it to be. In this case (as per your question) it is enough to simply compare the total values of your table.


问:
Find count of each consecutive characters
Need to find the count of each consecutive characters in a row.
Ex: aaaabbccaa
output: 4a2b2c2a

Character may repeat but need to count only consecutive ones. I also need to maintain original sequence.

I tried following but it groups all characters so was not useful.

```<code>str.GroupBy(c => c).Select(g => new { g.Key, Count = g.Count() }).ToList().ForEach(x => str+= x.Count + "" + x.Key)
</code>```

答: You could have a character var and a counter var outside your Linq scope to keep track of the previous character and the current count and then use linq foreach, but I am just as curious as the rest to why you insist on doing this. Even if you do, the Solution may not be as easy to read as an iterative version and readability and maintenance overhead is very import if anyone else is ever going to read it.</p>

Body:
Need to find the count of each consecutive characters in a row.
Ex: aaaabbccaa
output: 4a2b2c2a

Character may repeat but need to count only consecutive ones. I also need to maintain original sequence.

I tried following but it groups all characters so was not useful.

str.GroupBy(c => c).Select(g => new { g.Key, Count = g.Count() }).ToList().ForEach(x => str+= x.Count + "" + x.Key)


问:
avoid call CommandLineRunner in junit4
I'm working on a project using spring boot 2.1.1.RELEASE with junit 4.

This is a command line application, that relies on a CommandLineRunner as "main".

The problem is I need to write a unit test that use some @Autowired stuff

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = ExcludeCommandLineRunner.class)
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,
                                                      value = CommandLineRunner.class))
@ContextConfiguration(classes = ExcludeCommandLineRunner.class)
public class MyTest {
    @Autowired
    MyService myService;

    @Test
    public void foo() {
        assertEquals(3, this.myService.sum(1, 2));
    }
}
</code>```

```<code>@Configuration
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,
                                                      value = CommandLineRunner.class))
@EnableAutoConfiguration
public class ExcludeCommandLineRunner {
}
</code>```

but there is no way for me to avoid the fact that the CommandLineRunner is called... how can I do it?

答:
Within @ContextConfiguration you defined your test context configuration to be loaded from ExcludeCommandLineRunner by Spring TestContext, therefore it will be executed.

```<code>@ContextConfiguration(classes = ExcludeCommandLineRunner.class)
</code>```

Also @SpringBootTest annotation will search for a main configuration class (one with @SpringBootApplication (because it is in turn meta-annotated with @SpringBootConfiguration)) and use that to start a Spring application context. In your example, you explicitly defined which class to use for application context bootstrap.

```<code>@SpringBootTest(classes = ExcludeCommandLineRunner.class)
</code>```

You should use one of the above annotations.

Solution : a) Specify other class(es) in @ContextConfiguration  or b) include inner static class annotated with @Configuration within MyTest class, which then will be used to load test context. In any case you need to remove @SpringBootTest annotation.

```<code>@RunWith(SpringRunner.class)
public class MyTest {
    @Autowired
    MyService myService;

    @Test
    public void foo() {
        assertEquals(3, this.myService.sum(1, 2));
    }

    @Configuration
    public static class TestContextConfiguration {
      // define beans (for example MyService) here
    }

}
</code>```

Title: avoid call CommandLineRunner in junit4

Body:
I'm working on a project using spring boot 2.1.1.RELEASE with junit 4.

This is a command line application, that relies on a CommandLineRunner as "main".

The problem is I need to write a unit test that use some @Autowired stuff

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ExcludeCommandLineRunner.class)
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,
                                                      value = CommandLineRunner.class))
@ContextConfiguration(classes = ExcludeCommandLineRunner.class)
public class MyTest {
    @Autowired
    MyService myService;

    @Test
    public void foo() {
        assertEquals(3, this.myService.sum(1, 2));
    }
}

@Configuration
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,
                                                      value = CommandLineRunner.class))
@EnableAutoConfiguration
public class ExcludeCommandLineRunner {
}

but there is no way for me to avoid the fact that the CommandLineRunner is called... how can I do it?

Body:
Within @ContextConfiguration you defined your test context configuration to be loaded from ExcludeCommandLineRunner by Spring TestContext, therefore it will be executed.

@ContextConfiguration(classes = ExcludeCommandLineRunner.class)

Also @SpringBootTest annotation will search for a main configuration class (one with @SpringBootApplication (because it is in turn meta-annotated with @SpringBootConfiguration)) and use that to start a Spring application context. In your example, you explicitly defined which class to use for application context bootstrap.

@SpringBootTest(classes = ExcludeCommandLineRunner.class)

You should use one of the above annotations.

Solution : a) Specify other class(es) in @ContextConfiguration  or b) include inner static class annotated with @Configuration within MyTest class, which then will be used to load test context. In any case you need to remove @SpringBootTest annotation.

@RunWith(SpringRunner.class)
public class MyTest {
    @Autowired
    MyService myService;

    @Test
    public void foo() {
        assertEquals(3, this.myService.sum(1, 2));
    }

    @Configuration
    public static class TestContextConfiguration {
      // define beans (for example MyService) here
    }

}


问:
MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 message lis teners added. Use emitter.setMaxListeners() to increase limit
I know this might flag as a duplicate solution but the solution on stack overflow is not working for me.

Problem

```<code>(node:5716) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 message lis
teners added. Use emitter.setMaxListeners() to increase limit.
</code>```

My codebase is huge and I facing this error sometimes I don't know why it is happening. I tried to increase the listeners limit but unfortunately, it is not working.

```<code>const EventEmitter = require('events');
const emitter = new EventEmitter()
emitter.setMaxListeners(50)
</code>```

UPDATE

After Some browsing, I run this command to trace warning

```<code>node --trace-warnings index.babel.js
</code>```

Turns out be my socket.io code is the problem I am using socket.io with Redis. This is the error

```<code>node:14212) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 message li
steners added. Use emitter.setMaxListeners() to increase limit
    at _addListener (events.js:281:19)
    at RedisClient.addListener (events.js:298:10)
    at Namespace.<anonymous> (D:/newProject/services/socket.js:21:17)
    at emitOne (events.js:115:13)
    at Namespace.emit (events.js:210:7)
    at Namespace.emit (D:\newProject\node_modules\socket.io\lib\namespace.js:213:10)
    at D:\newProject\node_modules\socket.io\lib\namespace.js:181:14
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)
</code>```

this is the code (But this code is for more specific tasks it will not execute all the time).

```<code>const redis = require('redis');
const config = require('../config');
const sub = redis.createClient(config.REDIS.port, config.REDIS.host);
const pub = redis.createClient(config.REDIS.port, config.REDIS.host);

sub.subscribe('spread');

module.exports = io => {
  io.on('connection', socket => {
    /* To find the User Login  */
    let passport = socket.handshake.session.passport;

    if (typeof passport !== 'undefined') {
      socket.on('typing:send', data => {
        pub.publish('spread', JSON.stringify(data));
      });

      sub.on('message', (ch, msg) => {
        // This is the Exact line where I am getting this error
        io.emit(`${JSON.parse(msg).commonID}:receive`, { ...JSON.parse(msg) });
      });
    }
  });
};
</code>```

答:
MaxListenersExceededWarning: Possible EventEmitter memory leak
  detected. 11 message lis teners added. Use
  emitter.setMaxListeners() to increase limit

By default, a maximum of 10 listeners can be registered for any single event, and we got 11 Ohno

```<code>// Change to 80 or 150 whatever and see what happens
require('events').EventEmitter.prototype._maxListeners = 70;
require('events').defaultMaxListeners = 70;

  process.on('warning', function (err) {
    if ( 'MaxListenersExceededWarning' == err.name ) {
      console.log('o kurwa');
      // write to log function
      process.exit(1); // its up to you what then in my case script was hang

    }
  });
</code>```

Body:
I know this might flag as a duplicate solution but the solution on stack overflow is not working for me.

Problem

(node:5716) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 message lis
teners added. Use emitter.setMaxListeners() to increase limit.

My codebase is huge and I facing this error sometimes I don't know why it is happening. I tried to increase the listeners limit but unfortunately, it is not working.

const EventEmitter = require('events');
const emitter = new EventEmitter()
emitter.setMaxListeners(50)

UPDATE

After Some browsing, I run this command to trace warning

node --trace-warnings index.babel.js

Turns out be my socket.io code is the problem I am using socket.io with Redis. This is the error

node:14212) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 message li
steners added. Use emitter.setMaxListeners() to increase limit
    at _addListener (events.js:281:19)
    at RedisClient.addListener (events.js:298:10)
    at Namespace.<anonymous> (D:/newProject/services/socket.js:21:17)
    at emitOne (events.js:115:13)
    at Namespace.emit (events.js:210:7)
    at Namespace.emit (D:\newProject\node_modules\socket.io\lib\namespace.js:213:10)
    at D:\newProject\node_modules\socket.io\lib\namespace.js:181:14
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)

this is the code (But this code is for more specific tasks it will not execute all the time).

const redis = require('redis');
const config = require('../config');
const sub = redis.createClient(config.REDIS.port, config.REDIS.host);
const pub = redis.createClient(config.REDIS.port, config.REDIS.host);

sub.subscribe('spread');

module.exports = io => {
  io.on('connection', socket => {
    /* To find the User Login  */
    let passport = socket.handshake.session.passport;

    if (typeof passport !== 'undefined') {
      socket.on('typing:send', data => {
        pub.publish('spread', JSON.stringify(data));
      });

      sub.on('message', (ch, msg) => {
        // This is the Exact line where I am getting this error
        io.emit(`${JSON.parse(msg).commonID}:receive`, { ...JSON.parse(msg) });
      });
    }
  });
};

Body:
MaxListenersExceededWarning: Possible EventEmitter memory leak
  detected. 11 message lis teners added. Use
  emitter.setMaxListeners() to increase limit

By default, a maximum of 10 listeners can be registered for any single event, and we got 11 Ohno

// Change to 80 or 150 whatever and see what happens
require('events').EventEmitter.prototype._maxListeners = 70;
require('events').defaultMaxListeners = 70;

  process.on('warning', function (err) {
    if ( 'MaxListenersExceededWarning' == err.name ) {
      console.log('o kurwa');
      // write to log function
      process.exit(1); // its up to you what then in my case script was hang

    }
  });


问:
Generating XLS files with SheetJS in browser vs. nodeJS server: pros and cons
I want to let users export some pieces of data in XLS files. I have a front-end application on Angular 9 and back-end on ExpressJS. Now I consider 2 ways to implement this with SheetJS: either create some ExportService to do it directly in the browser or implement this on the server-side and provide an API endpoint for exporting. To be more objective, I'd like to know what the community thinks: what are the pros and cons of the both ways?

My special concern is whether there are any functional limitations on what can be generated in browser vs. server. Aren't there some special features that are only available with server-side implementation?

答:
Here's what I can think of. Please feel free to supplement or correct this list to build a full picture.

Client-side implementation

Pros:

no need for an extra HTTP request (unless I need to fetch some extra data; in my case, I don't)

less load on the server: everything happens on the user's machine

it can be faster than server-side implementation when server is over-loaded or internet is slow

Cons:

significantly increased bundle size: the whole SheetJS library has to be bundled

it can be slower than server-side implementation when user's machine is slow

What am I missing?


问:
How to tokenize a Roman numeral term in ElasticSearch?
When creating tokenizer by registering token chars as below, Roman 'X' cannot be registered.(Test ES Version : ES6.7, ES5.6)

```<code>      "tokenizer": {
        "autocomplete": {
          "type": "edge_ngram",
          "min_gram": 1,
          "max_gram": 14,
          "token_chars": [
            "Ⅹ"
          ]
        }
    }
</code>```

error log is like this

{"error":{"root_cause":[{"type":"remote_transport_exception","reason":"[node02][192.168.115.x:9300][indices:admin/create]"}],"type":"illegal_argument_exception","reason":"Unknown
  token type: 'ⅹ', must be one of [symbol, private_use,
  paragraph_separator, start_punctuation, unassigned, enclosing_mark,
  connector_punctuation, letter_number, other_number, math_symbol,
  lowercase_letter, space_separator, surrogate,
  initial_quote_punctuation, decimal_digit_number, digit,
  other_punctuation, dash_punctuation, currency_symbol,
  non_spacing_mark, format, modifier_letter, control, uppercase_letter,
  other_symbol, end_punctuation, modifier_symbol, other_letter,
  line_separator, titlecase_letter, letter, punctuation,
  combining_spacing_mark, final_quote_punctuation,
  whitespace]"},"status":400}

How can I tokenize Roman numerals into terms?

答:
The error message clearly specifying that your Roman X isn't a valid token type. The error message also listing the valid options for token type, as shown below:

must be one of [symbol, private_use, paragraph_separator,
  start_punctuation, unassigned, enclosing_mark, connector_punctuation,
  letter_number, other_number, math_symbol, lowercase_letter,
  space_separator, surrogate, initial_quote_punctuation,
  decimal_digit_number, digit, other_punctuation, dash_punctuation,
  currency_symbol, non_spacing_mark, format, modifier_letter, control,
  uppercase_letter, other_symbol, end_punctuation, modifier_symbol,
  other_letter, line_separator, titlecase_letter, letter, punctuation,
  combining_spacing_mark, final_quote_punctuation, whitespace]

The issue is in your syntax if you refer the official ES doc https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-edgengram-tokenizer.html for token chars, then you can understand what it means as explained below:

Character classes that should be included in a token. Elasticsearch
  will split on characters that don’t belong to the classes specified.
  Defaults to [] (keep all characters).

And below it again specifies the valid values as digit, letter also the same link has some examples where they used token_chars with valid values.

Your issue would be resolved if you replace X with letter in your analyzer setting.

Body:
When creating tokenizer by registering token chars as below, Roman 'X' cannot be registered.(Test ES Version : ES6.7, ES5.6)

      "tokenizer": {
        "autocomplete": {
          "type": "edge_ngram",
          "min_gram": 1,
          "max_gram": 14,
          "token_chars": [
            "Ⅹ"
          ]
        }
    }

error log is like this

{"error":{"root_cause":[{"type":"remote_transport_exception","reason":"[node02][192.168.115.x:9300][indices:admin/create]"}],"type":"illegal_argument_exception","reason":"Unknown
  token type: 'ⅹ', must be one of [symbol, private_use,
  paragraph_separator, start_punctuation, unassigned, enclosing_mark,
  connector_punctuation, letter_number, other_number, math_symbol,
  lowercase_letter, space_separator, surrogate,
  initial_quote_punctuation, decimal_digit_number, digit,
  other_punctuation, dash_punctuation, currency_symbol,
  non_spacing_mark, format, modifier_letter, control, uppercase_letter,
  other_symbol, end_punctuation, modifier_symbol, other_letter,
  line_separator, titlecase_letter, letter, punctuation,
  combining_spacing_mark, final_quote_punctuation,
  whitespace]"},"status":400}

How can I tokenize Roman numerals into terms?


问:
Programmatically get all targets in a CMake project
I'd like to have one specific target be dependent on all the other added targets in my project. To say it in a different way - I'd like this target (say lint) to run after all the libraries and applications were built.

Is there a way in the top CMakeLists.txt file, where the project is specified, to get the list of all targets added by other CMakeLists.txt files in the directories added using add_subdirectory? Then I can use the add_dependencies to specify the order. There is a BUILDSYSTEM_TARGETS property, but it only works on a directory level.

If there is some other way to achieve this, please let me know. I use CMake 3.14.

答:
For the future reference, I've ended up writing my own function instead of a macro. But the concept is the same as the accepted answer by @thomas_f.

Here is the code:

```<code># Collect all currently added targets in all subdirectories
#
# Parameters:
# - _result the list containing all found targets
# - _dir root directory to start looking from
function(get_all_targets _result _dir)
    get_property(_subdirs DIRECTORY "${_dir}" PROPERTY SUBDIRECTORIES)
    foreach(_subdir IN LISTS _subdirs)
        get_all_targets(${_result} "${_subdir}")
    endforeach()

    get_directory_property(_sub_targets DIRECTORY "${_dir}" BUILDSYSTEM_TARGETS)
    set(${_result} ${${_result}} ${_sub_targets} PARENT_SCOPE)
endfunction()
</code>```

Body:
For the future reference, I've ended up writing my own function instead of a macro. But the concept is the same as the accepted answer by @thomas_f.

Here is the code:

# Collect all currently added targets in all subdirectories
#
# Parameters:
# - _result the list containing all found targets
# - _dir root directory to start looking from
function(get_all_targets _result _dir)
    get_property(_subdirs DIRECTORY "${_dir}" PROPERTY SUBDIRECTORIES)
    foreach(_subdir IN LISTS _subdirs)
        get_all_targets(${_result} "${_subdir}")
    endforeach()

    get_directory_property(_sub_targets DIRECTORY "${_dir}" BUILDSYSTEM_TARGETS)
    set(${_result} ${${_result}} ${_sub_targets} PARENT_SCOPE)
endfunction()


答:
try:</p>

```<code>SELECT name, GROUP_CONCAT(id) FROM SomeTable GROUP BY name WHERE name = 'multiple rows named this'
</code>```

Title: Is there a fast and non-fancy C# code/algorithm to compress a string of comma separated digits close to maximum info density?

Body:
In a nutshell, I programmed myself into a corner by creating a CLR aggregate that performs row id concatenation, so I say:

select SumKeys(id), name from SomeTable where name='multiple rows named this'

and I get something like:

SumKeys         name
--------        ---------
1,4,495         multiple rows named this

But it dies when SumKeys gets > 8000 chars and I don't think I can do anything about it.

As a quick fix (it's only failing 1% of the time for my application) I thought I might compress the string down and I thought some of you bright people out there might know a slick way to do this.

Something like base64 made for 0-9 and a comma?

Body:
try:

SELECT name, GROUP_CONCAT(id) FROM SomeTable GROUP BY name WHERE name = 'multiple rows named this'


问:
how to add different font sizes in tooltip content?
I have function that calculates the remaining days between 2 dates then have it as a tooltip.
How do I make the number of days (Difference_In_Days, Difference_In_DaysRev) bigger than the other text? I tried adding a  in the mess variable but it gives error. I am using xsl to render the page but I don't think it matters.

```<code>//TOOLTIP MESSAGE: REMAINING DAYS
  $('tr[startDateToCal]').each(function(index, el){
  //format "2019-10-31"
  var startdate = el.getAttribute('startDateToCal');
  var enddate = el.getAttribute('endDateToCal');
  var startDateRevToCal = el.getAttribute('startDateRevToCal');
  var endDateRevToCal = el.getAttribute('endDateRevToCal');

  var newstartdate =  startdate.substring(5,7) + "/" + startdate.substring(8,10) + "/" + startdate.substring(0,4);
  var newstartdaterev =  startDateRevToCal.substring(5,7) + "/" + startDateRevToCal.substring(8,10) + "/" + startDateRevToCal.substring(0,4);

  var newenddate = enddate.substring(5,7) + "/" + enddate.substring(8,10) + "/" + enddate.substring(0,4);
  var newenddaterev = endDateRevToCal.substring(5,7) + "/" + endDateRevToCal.substring(8,10) + "/" + endDateRevToCal.substring(0,4);

  //format "06/30/2019"
  var dateapp1 = new Date(newstartdate);
  var dateapp2 = new Date(newenddate);
  var daterev1 = new Date(newstartdaterev);
  var daterev2 = new Date(newenddaterev);

  // To calculate the time difference of two dates
  var Difference_In_Time = dateapp2.getTime() - dateapp1.getTime();
  var Difference_In_TimeRev = daterev2.getTime() - daterev1.getTime();

  // To calculate the no. of days between two dates
  var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
  Difference_In_Days = Math.round(Difference_In_Days);

  var Difference_In_DaysRev = Difference_In_TimeRev / (1000 * 3600 * 24);
  Difference_In_DaysRev = Math.round(Difference_In_DaysRev);

   var flg_nom = el.getAttribute('flg_nom');
   var flg_rev = el.getAttribute('flg_rev');

  var remainingDays = "Days Reminaining: 0";
  var remainingDaysRev = "Days Reminaining: 0";
  var mess;

  if(flg_nom=='Y' ){
    if(Difference_In_Days  >= 0){
      mess = "Submissions Open<br/><br/>" + Difference_In_Days + "<br/>Days Reminaining";
    }
  }

  if(flg_rev=='Y' && flg_nom=='N' ){
    if(Difference_In_DaysRev  >= 0){
      mess = "Reviews Open<br/><br/>" + Difference_In_DaysRev + "<br/>Days Reminaining";
    }
  }

  if(flg_nom=='N' && flg_rev=='N'){
    mess = el.getAttribute('currentYear') + " cycle setup.\n\nPlease contact RhythmQ for archiving and new cycle set up."  ;
  }

   $(this).attr('title',mess);

  });

  $('tr[data-toggle="tooltip"]').tooltip({
  html: "true"
  });
</code>```

tooltip image

Please advise.

答:
I used the header tag  and overwritten it in css.</p>

```<code>mess = "Reviews Open<br/><br/><h6>" + Difference_In_DaysRev + "</h6><br/>Days Reminaining";
h6{ font-size: 30px; }
</code>```

Body:
I have function that calculates the remaining days between 2 dates then have it as a tooltip.
How do I make the number of days (Difference_In_Days, Difference_In_DaysRev) bigger than the other text? I tried adding a  in the mess variable but it gives error. I am using xsl to render the page but I don't think it matters.

//TOOLTIP MESSAGE: REMAINING DAYS
  $('tr[startDateToCal]').each(function(index, el){
  //format "2019-10-31"
  var startdate = el.getAttribute('startDateToCal');
  var enddate = el.getAttribute('endDateToCal');
  var startDateRevToCal = el.getAttribute('startDateRevToCal');
  var endDateRevToCal = el.getAttribute('endDateRevToCal');

  var newstartdate =  startdate.substring(5,7) + "/" + startdate.substring(8,10) + "/" + startdate.substring(0,4);
  var newstartdaterev =  startDateRevToCal.substring(5,7) + "/" + startDateRevToCal.substring(8,10) + "/" + startDateRevToCal.substring(0,4);

  var newenddate = enddate.substring(5,7) + "/" + enddate.substring(8,10) + "/" + enddate.substring(0,4);
  var newenddaterev = endDateRevToCal.substring(5,7) + "/" + endDateRevToCal.substring(8,10) + "/" + endDateRevToCal.substring(0,4);

  //format "06/30/2019"
  var dateapp1 = new Date(newstartdate);
  var dateapp2 = new Date(newenddate);
  var daterev1 = new Date(newstartdaterev);
  var daterev2 = new Date(newenddaterev);

  // To calculate the time difference of two dates
  var Difference_In_Time = dateapp2.getTime() - dateapp1.getTime();
  var Difference_In_TimeRev = daterev2.getTime() - daterev1.getTime();

  // To calculate the no. of days between two dates
  var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
  Difference_In_Days = Math.round(Difference_In_Days);

  var Difference_In_DaysRev = Difference_In_TimeRev / (1000 * 3600 * 24);
  Difference_In_DaysRev = Math.round(Difference_In_DaysRev);

   var flg_nom = el.getAttribute('flg_nom');
   var flg_rev = el.getAttribute('flg_rev');

  var remainingDays = "Days Reminaining: 0";
  var remainingDaysRev = "Days Reminaining: 0";
  var mess;

  if(flg_nom=='Y' ){
    if(Difference_In_Days  >= 0){
      mess = "Submissions Open

" + Difference_In_Days + "
Days Reminaining";
    }
  }

  if(flg_rev=='Y' && flg_nom=='N' ){
    if(Difference_In_DaysRev  >= 0){
      mess = "Reviews Open

" + Difference_In_DaysRev + "
Days Reminaining";
    }
  }

  if(flg_nom=='N' && flg_rev=='N'){
    mess = el.getAttribute('currentYear') + " cycle setup.\n\nPlease contact RhythmQ for archiving and new cycle set up."  ;
  }

   $(this).attr('title',mess);

  });

  $('tr[data-toggle="tooltip"]').tooltip({
  html: "true"
  });

tooltip image

Please advise.

Body:
I used the header tag  and overwritten it in css.

mess = "Reviews Open<br/><br/><h6>" + Difference_In_DaysRev + "</h6><br/>Days Reminaining";
h6{ font-size: 30px; }


问:
Add dependency between 2 Dofn in Apache Beam
Is there any way I can create dependency between 2 Dofn, so that it will wait for 1st Dofn method to complete then second Dofn method will run.
Just wondering how we can achieve this use-case.</p>

答:
There may be a cleaner way to do this, but I've noticed that doing the following will acheive the effect you desire:

Route the output of the first DoFn to also go to a counter, and then have the output of that counter be passed into the ParDo of the second DoFn as a side input

```<code>class DoFn2(apache_beam.DoFn):
    def process(self, element, count_do_fn_1_output, *args, **kwargs):
        # ...

do_fn_1_output = do_fn_1_input | 'do fn 1' >> apache_beam.ParDo(DoFn1())

count_do_fn_1_output = (
    do_fn_1_output
    | 'count do_fn_1_output' >> apache_beam.combiners.Count.Globally())

do_fn_2_output = (
    do_fn_1_output
    | 'do fn 2' >> apache_beam.ParDo(DoFn2(), count_do_fn_1_output=apache_beam.pvalue.AsSingleton(count_do_fn_1_output)))
</code>```

Body:
There may be a cleaner way to do this, but I've noticed that doing the following will acheive the effect you desire:

Route the output of the first DoFn to also go to a counter, and then have the output of that counter be passed into the ParDo of the second DoFn as a side input

class DoFn2(apache_beam.DoFn):
    def process(self, element, count_do_fn_1_output, *args, **kwargs):
        # ...

do_fn_1_output = do_fn_1_input | 'do fn 1' >> apache_beam.ParDo(DoFn1())

count_do_fn_1_output = (
    do_fn_1_output
    | 'count do_fn_1_output' >> apache_beam.combiners.Count.Globally())

do_fn_2_output = (
    do_fn_1_output
    | 'do fn 2' >> apache_beam.ParDo(DoFn2(), count_do_fn_1_output=apache_beam.pvalue.AsSingleton(count_do_fn_1_output)))


问:
How to construct a model instance from multiple column with JPA
I have this scenario, where there is three entities, each having like around 20 columns, assume all are unique names, 20*3 is 60 unique column names. Then I need to fetch some particular fields like 30 fields from them by joining all 3. So I have the mappings in place in each Entity. Then to select only this 30 fields I understand I should only select them, using multi select. But is there an efficient way to do this? Like instead of writing 30 column names in my code, can I have a model which defines all these fields and then pass this model in select clause, so it selects the fields, or something similar.

Then Entity 1 :-

```<code>public class CourseEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
long id;

String name;

String descr;

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "univ_id")
UniversityEntity university;
</code>```

Entity 2 :-

```<code>public class StudentEntity {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

@Column(name = "grad_year")
private int gradYear;

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "course_id")
CourseEntity courses;
</code>```

Entity 3 :-

```<code>public class UniversityEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
long id;

String name;

String desrc;

@OneToOne(mappedBy = "university")
CourseEntity courses;
}
</code>```

The model object I want :-

```<code>public class StudentModel {

private int disbursementId;
private String payeeId;
private String courseName;
private String offeredBy;

}
</code>```

But the place I am concerned about is,
Select Query :-

```<code>    CriteriaQuery<StudentModel> criteriaQuery = cb.createQuery(StudentModel.class);

    Root<StudentEntity> root = criteriaQuery.from(StudentEntity.class);
    Join<StudentEntity, CourseEntity> student_course = root.join("courses");
    Join<CourseEntity, UniversityEntity> university_course = student_course.join("university");
    criteriaQuery.multiselect(
            root.get("id").alias("disbursement_id")
            , root.get("firstName").alias("payee_id")
            , student_course.get("name").alias("course_name")
            , university_course.get("name").alias("offered_by")
            )
            .where(cb.equal(root.get("gradYear"), 2015));

    TypedQuery<StudentModel> query = em.createQuery(criteriaQuery);
    List<StudentModel> results = query.getResultList();
</code>```

Can we actually pass like,

```<code>    CriteriaQuery<StudentModel> criteriaQuery = cb.createQuery(StudentModel.class);

    Root<StudentEntity> root = criteriaQuery.from(StudentEntity.class);
    Join<StudentEntity, CourseEntity> student_course = root.join("courses");
    Join<CourseEntity, UniversityEntity> university_course = student_course.join("university");
    criteriaQuery.multiselect(
            **StudentModel**
            )
            .where(cb.equal(root.get("gradYear"), 2015));

    TypedQuery<StudentModel> query = em.createQuery(criteriaQuery);
    List<StudentModel> results = query.getResultList();
</code>```

答:
You can contruct a model instance by using CriteriaBuild#construct rather than multiselect.

Your model class must have a constructor taking all fields as parameters:

```<code>public StudentModel(int disbursementId, String payeeId /**...**/) {/**...**/}
</code>```

then you can use like this:

```<code>criteriaQuery.select(cb.construct(StudentModel.class, root.get("id"), root.get("firstName") /**...**/));
</code>```

Body:
I have this scenario, where there is three entities, each having like around 20 columns, assume all are unique names, 20*3 is 60 unique column names. Then I need to fetch some particular fields like 30 fields from them by joining all 3. So I have the mappings in place in each Entity. Then to select only this 30 fields I understand I should only select them, using multi select. But is there an efficient way to do this? Like instead of writing 30 column names in my code, can I have a model which defines all these fields and then pass this model in select clause, so it selects the fields, or something similar.

Then Entity 1 :-

public class CourseEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
long id;

String name;

String descr;

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "univ_id")
UniversityEntity university;

Entity 2 :-

public class StudentEntity {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

@Column(name = "grad_year")
private int gradYear;

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "course_id")
CourseEntity courses;

Entity 3 :-

public class UniversityEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
long id;

String name;

String desrc;

@OneToOne(mappedBy = "university")
CourseEntity courses;
}

The model object I want :-

public class StudentModel {

private int disbursementId;
private String payeeId;
private String courseName;
private String offeredBy;

}

But the place I am concerned about is,
Select Query :-

    CriteriaQuery<StudentModel> criteriaQuery = cb.createQuery(StudentModel.class);

    Root<StudentEntity> root = criteriaQuery.from(StudentEntity.class);
    Join<StudentEntity, CourseEntity> student_course = root.join("courses");
    Join<CourseEntity, UniversityEntity> university_course = student_course.join("university");
    criteriaQuery.multiselect(
            root.get("id").alias("disbursement_id")
            , root.get("firstName").alias("payee_id")
            , student_course.get("name").alias("course_name")
            , university_course.get("name").alias("offered_by")
            )
            .where(cb.equal(root.get("gradYear"), 2015));

    TypedQuery<StudentModel> query = em.createQuery(criteriaQuery);
    List<StudentModel> results = query.getResultList();

Can we actually pass like,

    CriteriaQuery<StudentModel> criteriaQuery = cb.createQuery(StudentModel.class);

    Root<StudentEntity> root = criteriaQuery.from(StudentEntity.class);
    Join<StudentEntity, CourseEntity> student_course = root.join("courses");
    Join<CourseEntity, UniversityEntity> university_course = student_course.join("university");
    criteriaQuery.multiselect(
            **StudentModel**
            )
            .where(cb.equal(root.get("gradYear"), 2015));

    TypedQuery<StudentModel> query = em.createQuery(criteriaQuery);
    List<StudentModel> results = query.getResultList();

Body:
You can contruct a model instance by using CriteriaBuild#construct rather than multiselect.

Your model class must have a constructor taking all fields as parameters:

public StudentModel(int disbursementId, String payeeId /**...**/) {/**...**/}

then you can use like this:

criteriaQuery.select(cb.construct(StudentModel.class, root.get("id"), root.get("firstName") /**...**/));


问:
Excel VBA MACBOOK - Delimited Row Values to stacked 2-Column
I've been looking for an answer to this all over and found multiple solutions that don't work for my version of Excel for Mac (v16.33 2020)

 1. Using Power Query which is not compatible

 2. I followed this link here: LINK which uses Scripting.Dictionary
 but when using it, I keep getting the error:

"Runtime Error '429'
Active X can't create object

3. I downloaded the updated Dictionary.cls and KeyValuePair.cls from http://www.sysmod.com/Dictionary.zip

 4. After updating the code to:
 Set dAttributes = New Dictionary

    Set dValues = New Dictionary
I get an error as k is blank for: For Each k In dic

Issue:
I have a 2-column list of delimited values, and I have to put them into a stacked column on excel. The identifier to be kept on the left column. The reason for doing it is the program we're using needs the item ID title, and one row for each pertaining product URL.

For example:

Column A| Column B

Item 1 | a.jpg, b.jpg, c.jpg

Item 2 | a.jpg, b.jpg, c.jpg

Needs to be:

Column A| Column B

Item 1 |a.jpg

Item 1| b.jpg

Item 2| a.jpg

Item 2| b.jpg

The values for the items and images are all different. There are hundreds of rows and values, so copy paste to transpose manually isn't a viable option.

Currently the code I have is here:  I'm stuck.  Please comment with steps to fix this.  I've tried the suggested links and nothing is working.

```<code>Sub ttt()
 Dim dic As Object:
 Set dAttributes = New Dictionary
    Set dValues = New Dictionary
    Dim x&, cl As Range, rng As Range, k, s
    Set rng = Range([C1], Cells(Rows.Count, "C").End(xlUp))
    x = 1 'used as a key for dictionary and as row number for output
    For Each cl In rng
        For Each s In Split(cl.Value2, ",")
            dic.Add x, Cells(cl.Row, "A").Value2 & "|" & _
                        Cells(cl.Row, "B").Value2 & "|" & LTrim(s)
            x = x + 1
    Next s, cl
    For Each k In dic
        Range(Cells(k, "A"), Cells(k, "C")).Value2 = Split(dic(k), "|")
    Next k
End Sub
</code>```

答:
You don't need a dictionary for this - split the value from ColB and loop over the array: for each element write out the value from ColA and the element value to a new row.</p>

```<code>Dim rw As Range
Dim ws As Worksheet, arr, e, c As Range
Set ws = ActiveSheet
Set c = ws.Range("H1") '<< start of output

'loop over input rows
For Each rw In ws.Range("A1").CurrentRegion.Rows
    arr = Split(rw.Cells(2).Value, ",")
    For Each e In arr
        c.Resize(1, 2).Value = Array(rw.Cells(1).Value, Trim(e))
        Set c = c.Offset(1, 0) 'next output row
    Next e
Next rw
</code>```

Body:
I've been looking for an answer to this all over and found multiple solutions that don't work for my version of Excel for Mac (v16.33 2020)

 1. Using Power Query which is not compatible

 2. I followed this link here: LINK which uses Scripting.Dictionary
 but when using it, I keep getting the error:

"Runtime Error '429'
Active X can't create object

3. I downloaded the updated Dictionary.cls and KeyValuePair.cls from http://www.sysmod.com/Dictionary.zip

 4. After updating the code to:
 Set dAttributes = New Dictionary

    Set dValues = New Dictionary
I get an error as k is blank for: For Each k In dic

Issue:
I have a 2-column list of delimited values, and I have to put them into a stacked column on excel. The identifier to be kept on the left column. The reason for doing it is the program we're using needs the item ID title, and one row for each pertaining product URL.

For example:

Column A| Column B

Item 1 | a.jpg, b.jpg, c.jpg

Item 2 | a.jpg, b.jpg, c.jpg

Needs to be:

Column A| Column B

Item 1 |a.jpg

Item 1| b.jpg

Item 2| a.jpg

Item 2| b.jpg

The values for the items and images are all different. There are hundreds of rows and values, so copy paste to transpose manually isn't a viable option.

Currently the code I have is here:  I'm stuck.  Please comment with steps to fix this.  I've tried the suggested links and nothing is working.

Sub ttt()
 Dim dic As Object:
 Set dAttributes = New Dictionary
    Set dValues = New Dictionary
    Dim x&, cl As Range, rng As Range, k, s
    Set rng = Range([C1], Cells(Rows.Count, "C").End(xlUp))
    x = 1 'used as a key for dictionary and as row number for output
    For Each cl In rng
        For Each s In Split(cl.Value2, ",")
            dic.Add x, Cells(cl.Row, "A").Value2 & "|" & _
                        Cells(cl.Row, "B").Value2 & "|" & LTrim(s)
            x = x + 1
    Next s, cl
    For Each k In dic
        Range(Cells(k, "A"), Cells(k, "C")).Value2 = Split(dic(k), "|")
    Next k
End Sub

Body:
You don't need a dictionary for this - split the value from ColB and loop over the array: for each element write out the value from ColA and the element value to a new row.

Dim rw As Range
Dim ws As Worksheet, arr, e, c As Range
Set ws = ActiveSheet
Set c = ws.Range("H1") '<< start of output

'loop over input rows
For Each rw In ws.Range("A1").CurrentRegion.Rows
    arr = Split(rw.Cells(2).Value, ",")
    For Each e In arr
        c.Resize(1, 2).Value = Array(rw.Cells(1).Value, Trim(e))
        Set c = c.Offset(1, 0) 'next output row
    Next e
Next rw


问:
Why is Input.dispatchMouseEvent not dispatching an event?
I'm trying to dispatch an IsTrusted event that simulates the user clicking a certain place on the screen. I'm trying this out through a Chrome Extension, although I'm not having much luck. There are no errors in the console, and my giant screen-wide button isn't being clicked. Here is my background.js:

```<code>chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        var activeTab = tabs[0];
        chrome.runtime.onMessage.addListener(
            function(request, sender, sendResponse) {
              if( request.message === "clickElement" ) {
                chrome.debugger.attach({tabId:tab.id}, "1.2", function(debugg) {
                    chrome.debugger.sendCommand(
                        {tabId:tab.id}, "Debugger.enable", {},
                        function() {
                            chrome.debugger.sendCommand({tabId:tab.id}, "Input.dispatchMouseEvent",
                            {
                                type:"mousePressed",
                                x:parseFloat(request.x),
                                y:parseFloat(request.y)
                            })
                        })
                })
              }
            }
        );
        chrome.tabs.sendMessage(activeTab.id, {"message": "runbot"});
    });
});
</code>```

And my content.js just sends the clickElement message with the coordinates of the button.

Any ideas?

答:
What you need to do is remove this nonsense:

chrome.debugger.sendCommand(
                        {tabId:tab.id}, "Debugger.enable", {},
```
<p>And add <code>button: "left"</code> prop to the parameters object:</p>
<pre class="lang-js prettyprint-override"><code>chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        var activeTab = tabs[0];
        chrome.runtime.onMessage.addListener(
            function(request, sender, sendResponse) {
              if( request.message === "clickElement" ) {
                chrome.debugger.attach({tabId:tab.id}, "1.2", function(debugg) {

                            chrome.debugger.sendCommand({tabId:tab.id}, "Input.dispatchMouseEvent",
                            {
                                type:"mousePressed",
                                button: "left",
                                x:parseFloat(request.x),
                                y:parseFloat(request.y)
                            })

                })
              }
            }
        );
        chrome.tabs.sendMessage(activeTab.id, {"message": "runbot"});
    });
});
</code>```

Also make sure you have the "debugger" permission in you manifest.json.

ps. When debugger attaches you should see this bar appear just below the address bar saying smth like '${extn. name} is executing browser debug':

Body:
I'm trying to dispatch an IsTrusted event that simulates the user clicking a certain place on the screen. I'm trying this out through a Chrome Extension, although I'm not having much luck. There are no errors in the console, and my giant screen-wide button isn't being clicked. Here is my background.js:

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        var activeTab = tabs[0];
        chrome.runtime.onMessage.addListener(
            function(request, sender, sendResponse) {
              if( request.message === "clickElement" ) {
                chrome.debugger.attach({tabId:tab.id}, "1.2", function(debugg) {
                    chrome.debugger.sendCommand(
                        {tabId:tab.id}, "Debugger.enable", {},
                        function() {
                            chrome.debugger.sendCommand({tabId:tab.id}, "Input.dispatchMouseEvent",
                            {
                                type:"mousePressed",
                                x:parseFloat(request.x),
                                y:parseFloat(request.y)
                            })
                        })
                })
              }
            }
        );
        chrome.tabs.sendMessage(activeTab.id, {"message": "runbot"});
    });
});

And my content.js just sends the clickElement message with the coordinates of the button.

Any ideas?

Body:
What you need to do is remove this nonsense:

chrome.debugger.sendCommand(
                        {tabId:tab.id}, "Debugger.enable", {},

And add button: "left" prop to the parameters object:

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        var activeTab = tabs[0];
        chrome.runtime.onMessage.addListener(
            function(request, sender, sendResponse) {
              if( request.message === "clickElement" ) {
                chrome.debugger.attach({tabId:tab.id}, "1.2", function(debugg) {

                            chrome.debugger.sendCommand({tabId:tab.id}, "Input.dispatchMouseEvent",
                            {
                                type:"mousePressed",
                                button: "left",
                                x:parseFloat(request.x),
                                y:parseFloat(request.y)
                            })

                })
              }
            }
        );
        chrome.tabs.sendMessage(activeTab.id, {"message": "runbot"});
    });
});

Also make sure you have the "debugger" permission in you manifest.json.

ps. When debugger attaches you should see this bar appear just below the address bar saying smth like '${extn. name} is executing browser debug':