问:
Ensure first and last characters of text box are numbers c#
Im currently creating a windows form that must only allow a password through when it matches certain criteria. Im close to finishing however im a bit stuck with one element. "the first and last characters of the password HAVE to be numbers".

looking at my current code how would i go about this because i have ZERO idea. so baby steps and patience would be appreciated.

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace password_test
{
    public partial class Form1 : Form
    {

        bool Finished = false;

        private bool TestPassword(string passwordText, int minimumLength =     5, int maximumLength = 12, int minimumNumbers = 1, int minimumLetters = 1)
    {

        int letters = 0;
        int digits = 0;
        int minLetters = 0;

        if (passwordText.Length < minimumLength)
        {
            MessageBox.Show("You must have at least " + minimumLength + " characters in your password.");
            return false;
        }

        if (passwordText.Length > maximumLength)
        {
            MessageBox.Show("You must have no more than " + maximumLength + " characters in your password.");
            return false;
        }

        foreach (var ch in passwordText)
        {
            if (char.IsLetter(ch)) letters++;
            if (char.IsDigit(ch)) digits++;

            if (ch > 96 && ch < 123)
            {
                minLetters++;
            }
        }

        if (digits < minimumNumbers)
        {
            MessageBox.Show("You must have at least " + minimumNumbers + " numbers in your password.");
            return false;
        }

        if (minLetters < minimumLetters)
        {
            MessageBox.Show("You must have at least " + minimumLetters + " letter in your password");
            return false;
        }
        Finished = true;
        return true;

    }

    public Form1()
    {
        InitializeComponent();
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void butConfirm_Click(object sender, EventArgs e)
    {

        if (txtPassword.Text == txtRetypePassword.Text)
        {
                bool temp = TestPassword(txtPassword.Text, 10, 100, 1, 1);

            if (Finished == true)
            {
                MessageBox.Show("Password Accepted");
                Application.Exit();
                //this.Hide();
                //Form2 f2 = new Form2();
                //f2.ShowDialog();

            }
        }

        else
        {
            MessageBox.Show("Please ensure the passwords you have typed match");
            return;
        }

    }

    private void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsControl(e.KeyChar) && !char.IsLetterOrDigit(e.KeyChar))
        {
            e.Handled = true;
        }
        else
        {
            return;
        }
    }

    private void txtRetypePassword_TextChanged(object sender, EventArgs e)
    {

    }

}
}
</code>```

答:
Or you can use Regex  Test Pattern

```<code>  //  ^\d = start with digit
  //  \d$ end with digit
  //  .{3,10}  including start and ending, min 5 max 12
  if (!Regex.IsMatch(str, @"\d.{3,10}\d$")
  {
       // Invalid
  }
</code>```

Use \D to reverse.

Body:
Im currently creating a windows form that must only allow a password through when it matches certain criteria. Im close to finishing however im a bit stuck with one element. "the first and last characters of the password HAVE to be numbers".

looking at my current code how would i go about this because i have ZERO idea. so baby steps and patience would be appreciated.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace password_test
{
    public partial class Form1 : Form
    {

        bool Finished = false;

        private bool TestPassword(string passwordText, int minimumLength =     5, int maximumLength = 12, int minimumNumbers = 1, int minimumLetters = 1)
    {

        int letters = 0;
        int digits = 0;
        int minLetters = 0;

        if (passwordText.Length < minimumLength)
        {
            MessageBox.Show("You must have at least " + minimumLength + " characters in your password.");
            return false;
        }

        if (passwordText.Length > maximumLength)
        {
            MessageBox.Show("You must have no more than " + maximumLength + " characters in your password.");
            return false;
        }

        foreach (var ch in passwordText)
        {
            if (char.IsLetter(ch)) letters++;
            if (char.IsDigit(ch)) digits++;

            if (ch > 96 && ch < 123)
            {
                minLetters++;
            }
        }

        if (digits < minimumNumbers)
        {
            MessageBox.Show("You must have at least " + minimumNumbers + " numbers in your password.");
            return false;
        }

        if (minLetters < minimumLetters)
        {
            MessageBox.Show("You must have at least " + minimumLetters + " letter in your password");
            return false;
        }
        Finished = true;
        return true;

    }

    public Form1()
    {
        InitializeComponent();
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void butConfirm_Click(object sender, EventArgs e)
    {

        if (txtPassword.Text == txtRetypePassword.Text)
        {
                bool temp = TestPassword(txtPassword.Text, 10, 100, 1, 1);

            if (Finished == true)
            {
                MessageBox.Show("Password Accepted");
                Application.Exit();
                //this.Hide();
                //Form2 f2 = new Form2();
                //f2.ShowDialog();

            }
        }

        else
        {
            MessageBox.Show("Please ensure the passwords you have typed match");
            return;
        }

    }

    private void txtPassword_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsControl(e.KeyChar) && !char.IsLetterOrDigit(e.KeyChar))
        {
            e.Handled = true;
        }
        else
        {
            return;
        }
    }

    private void txtRetypePassword_TextChanged(object sender, EventArgs e)
    {

    }

}
}

Body:
Or you can use Regex  Test Pattern

  //  ^\d = start with digit
  //  \d$ end with digit
  //  .{3,10}  including start and ending, min 5 max 12
  if (!Regex.IsMatch(str, @"\d.{3,10}\d$")
  {
       // Invalid
  }

Use \D to reverse.


来源: stackexchange

问:
How to perform an SQL query from a table based on values in other tables?
This is a pretty basic problem, but I'm new to SQL so it's giving me trouble.

Say I have three tables: X, Y, and Z.

X contains foreign keys for Y, and Y contains foreign keys for Z.  How can I select all rows in X which have foreign keys for Y, which in turn have foreign keys for Z, which in turn match some specified value?

For example lets say that these are the columns for each table:

X = "x_ids", "x_values", "y_foreign_keys"

Y = "y_ids", "y_values", "z_foreign_keys"

Z = "z_ids", "z_values"

I need to find out how to select all rows of X which I can trace down to z_values which equal the string "test".

答:
Can you try this:

Tables

X = "x_ids", "x_values", "y_foreign_keys"

Y = "y_ids", "y_values", "z_foreign_keys"

Z = "z_ids", "z_values"

SQL

```<code>SELECT * FROM Z
INNER JOIN Y ON z_ids = z_foreign_keys
INNER JOIN X ON y_ids = y_foreign_keys WHERE X.x_values= 'HELLO WORLD';
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Can you try this:

Tables

X = "x_ids", "x_values", "y_foreign_keys"

Y = "y_ids", "y_values", "z_foreign_keys"

Z = "z_ids", "z_values"

SQL

SELECT * FROM Z
INNER JOIN Y ON z_ids = z_foreign_keys
INNER JOIN X ON y_ids = y_foreign_keys WHERE X.x_values= 'HELLO WORLD';


问:
Animate image list by group Java Swing
Currently my code animates an image from the list from initial size to final size and continues with the next one until it completes animating all images and all have their final size.

```<code>package ui;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.Timer;

import utils.SudokuGen;

// TODO: Auto-generated Javadoc
/**
 * The Class ButtonPanel.
 */
public class ButtonPanel extends JPanel implements ActionListener{

    /** The Constant serialVersionUID. */
    private static final long serialVersionUID = 1L;

    /** The buttons. */
    private JButton[] buttons;

    private int[] imgsize;
    private int index,count;
    private Timer timer;
    private ImageButton images;
    private static final int COUNT = 10;
    private static final int INITSIZE = 32;
    private static final int COLUMNS = 1;
    private static final int ROWS = 9;

    /**
     * Instantiates a new button panel.
     *
     * @param puzzle The Sudoku matrix object
     * @param images The images object
     * @param sPanel The Sudoku JPanel
     */
    public ButtonPanel(SudokuGen puzzle, ImageButton images, SudokuPanel sPanel){

        //Create an array of JButton with 9 elements
        this.buttons = new JButton[puzzle.getMyboard().getNewnumbers().size()];

        this.images = images;
        this.imgsize = new int[COUNT];
        for (int i=0;i<COUNT;i++){
            imgsize[i] = INITSIZE;
        }
        //Sets the layout to a 9*1 GridLayout with padding 5
        this.setLayout(new GridLayout(ROWS,COLUMNS,5,5));

        //Load an image, create the MouseListener and add it at index i
        for (int i=1;i<this.images.getImagelist().size();i++){
            ImageIcon image = new ImageIcon(this.images.getImagelist()
                    .get(i).getImage().getScaledInstance(32, 32, Image.SCALE_SMOOTH));
            buttons[i] = createMouseListener(image, i, puzzle, sPanel);
            buttons[i].setPreferredSize(new Dimension(100, 100));
            this.add(buttons[i]);
        }

        index = 1; //first button
        count = 0; //times to resize the button

        timer = new Timer(5,this);
        timer.start();
    }

    public void set(int X){
        this.imgsize[index] = X;
    }

    /**
     * Creates the mouse listener.
     *
     * @param image The image at index i
     * @param i The index for the button i
     * @param puzzle The Sudoku matrix object
     * @param sPanel The Sudoku JPanel
     * @return the JButton to add at index i
     */
    private JButton createMouseListener(ImageIcon image, int i, SudokuGen puzzle, SudokuPanel sPanel){
        JButton button = new JButton();
        button.setIcon(image);
        button.setActionCommand(Integer.toString(puzzle.getMyboard().getNewnumbers().get(i)));
        button.addActionListener(sPanel.new ButtonActionListener());
        return button;
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        count++;
        set(this.imgsize[index]+1); //increase the size of the image

        if (this.imgsize[index] < 64){

            ImageIcon image = new ImageIcon(this.images.getImagelist()
                .get(index).getImage().getScaledInstance(this.imgsize[index], this.imgsize[index], Image.SCALE_SMOOTH));
            buttons[index].setIcon(image);
            if (count > 24){ //reached final size
                count = 0; //start counting again
                index++; //move to the next image
            }
        };
        if (index == 10) timer.stop();
        repaint();

    }

}
</code>```

I'm not able to provide an SSCCE given the amount of resources needed for it to work so apologizes for that.

My goal is to start animating the next image when the first animation finished half its process. So when the second image reaches its half animation the first one completes its full animation. Kind of a wave effect.

If there something else I could improve, I'm glad to hear suggestions.

Update: Updated method used to achieve the effect:

```<code>public void actionPerformed(ActionEvent e) {

    count++;
    this.imgsize[index]++;

        ImageIcon image = new ImageIcon(this.images.getImagelist()
            .get(index).getImage().getScaledInstance(this.imgsize[index], this.imgsize[index], Image.SCALE_SMOOTH));
        buttons[index].setIcon(image);
        if (count > 24){
            count = 0;
            index++;
        }
    if (count > 12 && index < 9)
    {
        this.imgsize[index+1]++;
        image = new ImageIcon(this.images.getImagelist()
                .get(index+1).getImage().getScaledInstance(this.imgsize[index+1], this.imgsize[index+1], Image.SCALE_SMOOTH));
            buttons[index+1].setIcon(image);
    }
    if (index == 10) timer.stop();
    repaint();

}
</code>```

答:
This is a somewhat overly simplified idea...

Basically, it sets up a normalised timeline (0-1) where events can occur along it, starting and ending at specified points.  During these "periods" some "action" can occur.

In your case, these actions are image scaling actions, the scale of which is a proportion of the amount of time that a given event has been running, which is a proportion of the overall time line.

This all sounds wonderfully confusing, but the benefit of which is, you can change the duration of the timeline and the rest of the code will scale automatically

For example, you could take...

```<code>timeline = new Timeline(events, 10000);
</code>```

which generates a timeline to run over 10 seconds and change it to

```<code>timeline = new Timeline(events, 5000);
</code>```

which will generate a timeline to run over 5 seconds and you've not had to change a single line of code to make it work.

I've also spend some time working out how to automatically generate timeline events from a series of images, so you can supply n number of images, and it will generate the required events so that they overlap each other accordingly

Now, you're probably thinking that this is all overly complicated, but the point is, it's all variable, the duration over which the images are scaled, the number of images, it's all variable and you don't need to do much to add/remove images or change the duration

Cavert- I've used getScaledInstance for this example, it's neither fast nor does it generate a quality image

```<code>import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    public class TestPane extends JPanel {

        private Timeline timeline;

        private Map<Object, Image> mapImages = new HashMap<>(5);
        private List<Object> imageOrder = new ArrayList<>(5);

        public TestPane() throws IOException {
            BufferedImage[] images = new BufferedImage[]{
                ImageIO.read(new File("...")),
                ImageIO.read(new File("...")),
                ImageIO.read(new File("...")),
                ImageIO.read(new File("..."))
            };
            List<TimelineEvent> events = generateEvents(images, new ImageScaledObserver() {
                @Override
                public void imageScaled(Object id, Image image) {
                    if (!imageOrder.contains(id)) {
                        imageOrder.add(id);
                    }
                    mapImages.put(id, image);
                    repaint();
                }
            });

            timeline = new Timeline(events, 10000);
            Timer timer = new Timer(5, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (timeline.update()) {
                        ((Timer) e.getSource()).stop();
                    }
                }
            });
            timer.setInitialDelay(5000);
            timer.start();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(500, 500);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            for (Object id : imageOrder) {
                Image image = mapImages.get(id);
                int x = (getWidth() - image.getWidth(this)) / 2;
                int y = (getHeight() - image.getHeight(this)) / 2;
                g2d.drawImage(image, x, y, this);
            }
            g2d.dispose();
        }

    }

    protected List<TimelineEvent> generateEvents(BufferedImage[] images, ImageScaledObserver observer) {
        double length = 1.0 / (double) (images.length);
        double overlap = length * 0.5;
        List<TimelineEvent> events = new ArrayList<>(images.length);
        double startAt = 0.0;
        for (BufferedImage image : images) {
            double endAt = Math.min(startAt + length + (overlap / 2.0), 1.0);
            events.add(new ScaleImageTimelineEvent(image, observer, startAt, endAt));
            startAt = Math.min(endAt - (overlap / 2.0), 1.0);
        }
        return events;
    }

    public interface TimelineEvent {

        public double[] range();

        public boolean isWithin(double timelineProgression);

        public void performAction(double timelineProgression);
    }

    public abstract class AbstractTimelineEvent implements TimelineEvent {

        private double from, to;

        public AbstractTimelineEvent(double from, double to) {
            this.from = from;
            this.to = to;
        }

        @Override
        public double[] range() {
            return new double[]{from, to};
        }

        @Override
        public boolean isWithin(double timelineProgression) {
            boolean within = timelineProgression >= from && timelineProgression <= to;
            return within;
        }

        protected double localisedProgression(double timelineProgression) {
            double max = from - to;
            double value = timelineProgression - to;
            double weight = value / max;
            return 1d - weight;
        }

    }

    public interface ImageScaledObserver {

        public void imageScaled(Object id, Image img);
    }

    public class ScaleImageTimelineEvent extends AbstractTimelineEvent {

        private BufferedImage original;
        private ImageScaledObserver observer;
        private UUID id;

        public ScaleImageTimelineEvent(BufferedImage image, ImageScaledObserver observer, double from, double to) {
            super(from, to);
            this.original = image;
            this.observer = observer;
            this.id = UUID.randomUUID();
        }

        @Override
        public void performAction(double timelineProgression) {
            double progress = localisedProgression(timelineProgression);
            Image image = null;
            if (progress < 1.0) {
                int width = (int) (original.getWidth() * progress);
                if (width > 0) {
                    image = original.getScaledInstance((int) (original.getWidth() * progress), -1, Image.SCALE_FAST);
                }
            } else {
                image = original;
            }
            if (image != null) {
                observer.imageScaled(id, image);
            }
        }

    }

    public static class Timeline {

        private List<TimelineEvent> events;

        private Long startTime;
        private long duration;

        public Timeline(List<TimelineEvent> events, long duration) {
            this.events = events;
            this.duration = duration;
        }

        public List<TimelineEvent> getEvents() {
            return events;
        }

        public Long getStartTime() {
            return startTime;
        }

        public long getDuration() {
            return duration;
        }

        public void start() {
            if (startTime == null) {
                startTime = System.nanoTime();
            }
        }

        public void stop() {
            startTime = null;
        }

        public boolean update() {
            if (startTime == null) {
                start();
            }

            boolean completed = false;

            long currentTime = System.nanoTime();
            long diff = currentTime - getStartTime();

            long nanoDuration = TimeUnit.NANOSECONDS.convert(getDuration(), TimeUnit.MILLISECONDS);
            double progress = diff / (double) nanoDuration;
            if (progress > 1.0d) {
                progress = 1.0d;
                completed = true;
                stop();
            }

            for (TimelineEvent evt : getEvents()) {
                if (evt.isWithin(progress)) {
                    evt.performAction(progress);
                }
            }
            return completed;
        }
    }

}
</code>```

I'd also suggest having a look at some of the animation frameworks which are available, which provide additional functionality, like easement. Maybe do a search for "Timing Framework" as a suggestion

The example uses a UUID to generate a unique identifier for the imageScaled event.  I wouldn't be hard to make ScaleImageTimelineEvent take an identifier of your own which is linked back to a specific image, allowing you to determine which image was scaled and perform more accurate updates

Title: Animate image list by group Java Swing

Body:
Currently my code animates an image from the list from initial size to final size and continues with the next one until it completes animating all images and all have their final size.

package ui;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.Timer;

import utils.SudokuGen;

// TODO: Auto-generated Javadoc
/**
 * The Class ButtonPanel.
 */
public class ButtonPanel extends JPanel implements ActionListener{

    /** The Constant serialVersionUID. */
    private static final long serialVersionUID = 1L;

    /** The buttons. */
    private JButton[] buttons;

    private int[] imgsize;
    private int index,count;
    private Timer timer;
    private ImageButton images;
    private static final int COUNT = 10;
    private static final int INITSIZE = 32;
    private static final int COLUMNS = 1;
    private static final int ROWS = 9;

    /**
     * Instantiates a new button panel.
     *
     * @param puzzle The Sudoku matrix object
     * @param images The images object
     * @param sPanel The Sudoku JPanel
     */
    public ButtonPanel(SudokuGen puzzle, ImageButton images, SudokuPanel sPanel){

        //Create an array of JButton with 9 elements
        this.buttons = new JButton[puzzle.getMyboard().getNewnumbers().size()];

        this.images = images;
        this.imgsize = new int[COUNT];
        for (int i=0;i<COUNT;i++){
            imgsize[i] = INITSIZE;
        }
        //Sets the layout to a 9*1 GridLayout with padding 5
        this.setLayout(new GridLayout(ROWS,COLUMNS,5,5));

        //Load an image, create the MouseListener and add it at index i
        for (int i=1;i<this.images.getImagelist().size();i++){
            ImageIcon image = new ImageIcon(this.images.getImagelist()
                    .get(i).getImage().getScaledInstance(32, 32, Image.SCALE_SMOOTH));
            buttons[i] = createMouseListener(image, i, puzzle, sPanel);
            buttons[i].setPreferredSize(new Dimension(100, 100));
            this.add(buttons[i]);
        }

        index = 1; //first button
        count = 0; //times to resize the button

        timer = new Timer(5,this);
        timer.start();
    }

    public void set(int X){
        this.imgsize[index] = X;
    }

    /**
     * Creates the mouse listener.
     *
     * @param image The image at index i
     * @param i The index for the button i
     * @param puzzle The Sudoku matrix object
     * @param sPanel The Sudoku JPanel
     * @return the JButton to add at index i
     */
    private JButton createMouseListener(ImageIcon image, int i, SudokuGen puzzle, SudokuPanel sPanel){
        JButton button = new JButton();
        button.setIcon(image);
        button.setActionCommand(Integer.toString(puzzle.getMyboard().getNewnumbers().get(i)));
        button.addActionListener(sPanel.new ButtonActionListener());
        return button;
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        count++;
        set(this.imgsize[index]+1); //increase the size of the image

        if (this.imgsize[index] < 64){

            ImageIcon image = new ImageIcon(this.images.getImagelist()
                .get(index).getImage().getScaledInstance(this.imgsize[index], this.imgsize[index], Image.SCALE_SMOOTH));
            buttons[index].setIcon(image);
            if (count > 24){ //reached final size
                count = 0; //start counting again
                index++; //move to the next image
            }
        };
        if (index == 10) timer.stop();
        repaint();

    }

}

I'm not able to provide an SSCCE given the amount of resources needed for it to work so apologizes for that.

My goal is to start animating the next image when the first animation finished half its process. So when the second image reaches its half animation the first one completes its full animation. Kind of a wave effect.

If there something else I could improve, I'm glad to hear suggestions.

Update: Updated method used to achieve the effect:

public void actionPerformed(ActionEvent e) {

    count++;
    this.imgsize[index]++;

        ImageIcon image = new ImageIcon(this.images.getImagelist()
            .get(index).getImage().getScaledInstance(this.imgsize[index], this.imgsize[index], Image.SCALE_SMOOTH));
        buttons[index].setIcon(image);
        if (count > 24){
            count = 0;
            index++;
        }
    if (count > 12 && index < 9)
    {
        this.imgsize[index+1]++;
        image = new ImageIcon(this.images.getImagelist()
                .get(index+1).getImage().getScaledInstance(this.imgsize[index+1], this.imgsize[index+1], Image.SCALE_SMOOTH));
            buttons[index+1].setIcon(image);
    }
    if (index == 10) timer.stop();
    repaint();

}

Body:
This is a somewhat overly simplified idea...

Basically, it sets up a normalised timeline (0-1) where events can occur along it, starting and ending at specified points.  During these "periods" some "action" can occur.

In your case, these actions are image scaling actions, the scale of which is a proportion of the amount of time that a given event has been running, which is a proportion of the overall time line.

This all sounds wonderfully confusing, but the benefit of which is, you can change the duration of the timeline and the rest of the code will scale automatically

For example, you could take...

timeline = new Timeline(events, 10000);

which generates a timeline to run over 10 seconds and change it to

timeline = new Timeline(events, 5000);

which will generate a timeline to run over 5 seconds and you've not had to change a single line of code to make it work.

I've also spend some time working out how to automatically generate timeline events from a series of images, so you can supply n number of images, and it will generate the required events so that they overlap each other accordingly

Now, you're probably thinking that this is all overly complicated, but the point is, it's all variable, the duration over which the images are scaled, the number of images, it's all variable and you don't need to do much to add/remove images or change the duration

Cavert- I've used getScaledInstance for this example, it's neither fast nor does it generate a quality image

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    public class TestPane extends JPanel {

        private Timeline timeline;

        private Map<Object, Image> mapImages = new HashMap<>(5);
        private List<Object> imageOrder = new ArrayList<>(5);

        public TestPane() throws IOException {
            BufferedImage[] images = new BufferedImage[]{
                ImageIO.read(new File("...")),
                ImageIO.read(new File("...")),
                ImageIO.read(new File("...")),
                ImageIO.read(new File("..."))
            };
            List<TimelineEvent> events = generateEvents(images, new ImageScaledObserver() {
                @Override
                public void imageScaled(Object id, Image image) {
                    if (!imageOrder.contains(id)) {
                        imageOrder.add(id);
                    }
                    mapImages.put(id, image);
                    repaint();
                }
            });

            timeline = new Timeline(events, 10000);
            Timer timer = new Timer(5, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (timeline.update()) {
                        ((Timer) e.getSource()).stop();
                    }
                }
            });
            timer.setInitialDelay(5000);
            timer.start();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(500, 500);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            for (Object id : imageOrder) {
                Image image = mapImages.get(id);
                int x = (getWidth() - image.getWidth(this)) / 2;
                int y = (getHeight() - image.getHeight(this)) / 2;
                g2d.drawImage(image, x, y, this);
            }
            g2d.dispose();
        }

    }

    protected List<TimelineEvent> generateEvents(BufferedImage[] images, ImageScaledObserver observer) {
        double length = 1.0 / (double) (images.length);
        double overlap = length * 0.5;
        List<TimelineEvent> events = new ArrayList<>(images.length);
        double startAt = 0.0;
        for (BufferedImage image : images) {
            double endAt = Math.min(startAt + length + (overlap / 2.0), 1.0);
            events.add(new ScaleImageTimelineEvent(image, observer, startAt, endAt));
            startAt = Math.min(endAt - (overlap / 2.0), 1.0);
        }
        return events;
    }

    public interface TimelineEvent {

        public double[] range();

        public boolean isWithin(double timelineProgression);

        public void performAction(double timelineProgression);
    }

    public abstract class AbstractTimelineEvent implements TimelineEvent {

        private double from, to;

        public AbstractTimelineEvent(double from, double to) {
            this.from = from;
            this.to = to;
        }

        @Override
        public double[] range() {
            return new double[]{from, to};
        }

        @Override
        public boolean isWithin(double timelineProgression) {
            boolean within = timelineProgression >= from && timelineProgression <= to;
            return within;
        }

        protected double localisedProgression(double timelineProgression) {
            double max = from - to;
            double value = timelineProgression - to;
            double weight = value / max;
            return 1d - weight;
        }

    }

    public interface ImageScaledObserver {

        public void imageScaled(Object id, Image img);
    }

    public class ScaleImageTimelineEvent extends AbstractTimelineEvent {

        private BufferedImage original;
        private ImageScaledObserver observer;
        private UUID id;

        public ScaleImageTimelineEvent(BufferedImage image, ImageScaledObserver observer, double from, double to) {
            super(from, to);
            this.original = image;
            this.observer = observer;
            this.id = UUID.randomUUID();
        }

        @Override
        public void performAction(double timelineProgression) {
            double progress = localisedProgression(timelineProgression);
            Image image = null;
            if (progress < 1.0) {
                int width = (int) (original.getWidth() * progress);
                if (width > 0) {
                    image = original.getScaledInstance((int) (original.getWidth() * progress), -1, Image.SCALE_FAST);
                }
            } else {
                image = original;
            }
            if (image != null) {
                observer.imageScaled(id, image);
            }
        }

    }

    public static class Timeline {

        private List<TimelineEvent> events;

        private Long startTime;
        private long duration;

        public Timeline(List<TimelineEvent> events, long duration) {
            this.events = events;
            this.duration = duration;
        }

        public List<TimelineEvent> getEvents() {
            return events;
        }

        public Long getStartTime() {
            return startTime;
        }

        public long getDuration() {
            return duration;
        }

        public void start() {
            if (startTime == null) {
                startTime = System.nanoTime();
            }
        }

        public void stop() {
            startTime = null;
        }

        public boolean update() {
            if (startTime == null) {
                start();
            }

            boolean completed = false;

            long currentTime = System.nanoTime();
            long diff = currentTime - getStartTime();

            long nanoDuration = TimeUnit.NANOSECONDS.convert(getDuration(), TimeUnit.MILLISECONDS);
            double progress = diff / (double) nanoDuration;
            if (progress > 1.0d) {
                progress = 1.0d;
                completed = true;
                stop();
            }

            for (TimelineEvent evt : getEvents()) {
                if (evt.isWithin(progress)) {
                    evt.performAction(progress);
                }
            }
            return completed;
        }
    }

}

I'd also suggest having a look at some of the animation frameworks which are available, which provide additional functionality, like easement. Maybe do a search for "Timing Framework" as a suggestion

The example uses a UUID to generate a unique identifier for the imageScaled event.  I wouldn't be hard to make ScaleImageTimelineEvent take an identifier of your own which is linked back to a specific image, allowing you to determine which image was scaled and perform more accurate updates


问:
Detecting when another application is clipping the mouse cursor?
What I am trying to do is to determine when another application is clipping the mouse cursor. I am using SetWindowsHookEx(WH_MOUSE_LL,...) to detect mouse movement. I could test the mouse position against its previous position every time my WH_MOUSE_LL callback is called, but this wont work if any of the sides of the application's window are touching the edge of the desktop as windows itself is also clipping the cursor.

More specifically, I am writing a program that overrides the default mapping of the virtual desktop when there are multiple monitors. I have everything working except in the case where a fullscreen application is running and constraining the mouse to its window. I cannot distinguish between the cursor actually trying to exit the side of the screen or if the current in-focus application is clipping it.

Is it possible to tell weather the in-focus app is clipping the mouse or maybe to prevent windows itself from constraining the cursor within the desktop, allowing the aforementioned check to work? Is there some other solution that I am missing?

Thank you.

答: Ah, I'm an idiot. GetClipCursor(RECT*) will do the trick.


问:
How to get youtube video data in csv file for a project?
I am doing a mini-project to apply clustering/retrieval ML methods on youtube video data to return some specific videos that I desire from a large dataset of videos.

I am having some trouble figuring out how to get the dataset of youtube videos in the first place. End goal is I want something like:

video_id | video_title | category | likes | dislikes | views | words_comment |

for bunch of videos (maybe ~10000 rows?) in csv format that I could apply Python machine learning algorithms to.

What's the best way of going about this? I've tried the youtube API but I am not familiar how it works I am stuck with errors. Is scraping directly from the youtube website easier?

Thanks!

答:
You can try scraping if you think it is easier but if you are not familiar with api calls you may not find scraping easier. I would research working with api's. They are a little funky at first but they are not very hard to use once you get the hang of them.

There is a channel on youtube called thenewboston and I believe he has some api stuff and general python videos will help as api responses will be formatted in data types similar to python.


问:
Communicating with the web through a C# app?
Although i can grasp the concepts of the .Net framework and windows apps, i want to create an app that will involve me simulating website clicks and getting data/response times from that page. I have not had any experience with web yet as im only a junior, could someone explain to me (in english!!) the basic concepts or with examples, the different ways and classes that could help me communicate with a website?</p>

答:
what do you want to do?

send a request and grab the response in a String so you can process?

HttpWebRequest and HttpWebResponse will work

if you need to connect through TCP/IP, FTP or other than HTTP then you need to use a more generic method

WebRequest and WebResponse

All the 4 methods above are in System.Net Namespace

If you want to build a Service in the web side that you can consume, then today and in .NET please choose and work with WCF (RESTfull style).

hope it helps you finding your way :)

as an example using the HttpWebRequest and HttpWebResponse, maybe some code will help you understand better.

case: send a response to a URL and get the response, it's like clicking in the URL and grab all the HTML code that will be there after the click:

```<code>private void btnSendRequest_Click(object sender, EventArgs e)
{
    textBox1.Text = "";
    try
    {
        String queryString = "user=myUser&pwd=myPassword&tel=+123456798&msg=My message";
        byte[] requestByte = Encoding.Default.GetBytes(queryString);

        // build our request
        WebRequest webRequest = WebRequest.Create("http://www.sendFreeSMS.com/");
        webRequest.Method = "POST";
        webRequest.ContentType = "application/xml";
        webRequest.ContentLength = requestByte.Length;

        // create our stram to send
        Stream webDataStream = webRequest.GetRequestStream();
        webDataStream.Write(requestByte, 0, requestByte.Length);

        // get the response from our stream
        WebResponse webResponse = webRequest.GetResponse();
        webDataStream = webResponse.GetResponseStream();

        // convert the result into a String
        StreamReader webResponseSReader = new StreamReader(webDataStream);
        String responseFromServer = webResponseSReader.ReadToEnd().Replace("\n", "").Replace("\t", "");

        // close everything
        webResponseSReader.Close();
        webResponse.Close();
        webDataStream.Close();

        // You now have the HTML in the responseFromServer variable, use it :)
        textBox1.Text = responseFromServer;
    }
    catch (Exception ex)
    {
        textBox1.Text = ex.Message;
    }
}
</code>```

The code does not work cause the URL is fictitious, but you get the idea. :)

OwnerDisplayName: Grace

ContentLicense: CC BY-SA 2.5

Body:
what do you want to do?

send a request and grab the response in a String so you can process?

HttpWebRequest and HttpWebResponse will work

if you need to connect through TCP/IP, FTP or other than HTTP then you need to use a more generic method

WebRequest and WebResponse

All the 4 methods above are in System.Net Namespace

If you want to build a Service in the web side that you can consume, then today and in .NET please choose and work with WCF (RESTfull style).

hope it helps you finding your way :)

as an example using the HttpWebRequest and HttpWebResponse, maybe some code will help you understand better.

case: send a response to a URL and get the response, it's like clicking in the URL and grab all the HTML code that will be there after the click:

private void btnSendRequest_Click(object sender, EventArgs e)
{
    textBox1.Text = "";
    try
    {
        String queryString = "user=myUser&pwd=myPassword&tel=+123456798&msg=My message";
        byte[] requestByte = Encoding.Default.GetBytes(queryString);

        // build our request
        WebRequest webRequest = WebRequest.Create("http://www.sendFreeSMS.com/");
        webRequest.Method = "POST";
        webRequest.ContentType = "application/xml";
        webRequest.ContentLength = requestByte.Length;

        // create our stram to send
        Stream webDataStream = webRequest.GetRequestStream();
        webDataStream.Write(requestByte, 0, requestByte.Length);

        // get the response from our stream
        WebResponse webResponse = webRequest.GetResponse();
        webDataStream = webResponse.GetResponseStream();

        // convert the result into a String
        StreamReader webResponseSReader = new StreamReader(webDataStream);
        String responseFromServer = webResponseSReader.ReadToEnd().Replace("\n", "").Replace("\t", "");

        // close everything
        webResponseSReader.Close();
        webResponse.Close();
        webDataStream.Close();

        // You now have the HTML in the responseFromServer variable, use it :)
        textBox1.Text = responseFromServer;
    }
    catch (Exception ex)
    {
        textBox1.Text = ex.Message;
    }
}

The code does not work cause the URL is fictitious, but you get the idea. :)

OwnerDisplayName: balexandre


问:
Is it wrong to use the hand cursor for clickable items such as buttons?
I've always thought the hand cursor to be the ideal visual indicator for "you may click here" to the user. We are used to see it in this context daily because of it's usage on hyperlinks and hence all web buttons.

However, most desktop applications seem to keep the defeault pointer arrow for buttons.

I really feel better when buttons, and other clickable items such as checkboxes and radio buttons use the hand cursor. Somehow, I find it personally pleasing to see this cursor when I hover over clickable items, maybe because it's consistent with how webpages and even many games do it.

But as developers, We have to think of the <s>children</s> user and sometimes do things not as we like them but as the user likes them. Problem is, I feel so fuzzy about the hand cursor on buttons that I'm blind to the possibility of it being inappropriate. Many design mistakes are caused by such personal decisions.

What do you think about it?

Edit: Recently I've taken notice of usage of the hand cursor on Photoshop (CS3 on XP), but probably only because I was using it more extensively. Screenshot:

Do note that many of the places where the hand was used are obviously clickable.

EDIT2: Do also note that they've even used a custom cursor, which to be honest I'd never do, especially for something trivial as a hand cursor that's so ubiquitous. And it's not even pretty.

答:
I think also we need to remember that hand generally indicates it's a link to somewhere else.

I don't think there is clear answer, but to me if the platform I'm coding for (Windows) I'll just follow the examples of the underlying OS to keep it consistent which means no Hand icons for buttons in Windows.

As a user I think it feels awkward to see hand icon in a Windows GUI (unless I'm clicking to a link which will take me to a website)


问:
Where is the `sdk` command installed for sdkman
I just installed sdkman for installing grails on my machine (MacOS). When I run which sdk command I don't get any output. But when I run the sdk help command the shell is able to resolve it and give the right output. I checked all the directories mentioned in $PATH environment variable but I could not find any executable sdk. So my question is how is shell able to resolve the sdk command?

Note: I also checked in Ubuntu and I see the same behavior.

答: OK. So I found it out. As @that-other-guy mentioned in the comment above, I used type -a instead of which, which showed me that it was a function defined.

ContentLicense: CC BY-SA 4.0


问:
C# Unity3D Scale using Accelerometer with Clamp
I'm trying to translate the roll(y) of a phone into the scale of an object but with size limits.

I have had success scaling to infinity +- with the following code:

```<code>void Update () {
   float accelY = Input.acceleration.y;
   transform.localScale += new Vector3(0, accelY, 0);
}
</code>```

The problem I am having is with the max and min limits of the scale.

I attempted to use Clamp in the following way but have ended up just limiting the direction of scale where -y (rolling toward myself) equals 0 therefore no shrinking happens and +y (rolling away from self) scales up endlessly assumed at a max rate of 0.045f.

```<code>transform.localScale += new Vector3(0, Mathf.Clamp(accelY, 0f, 0.045f), 0);
</code>```

In an ideal world I'd like to have a min scale of y = 1 and a max scale y = 100 and as you roll the phone back and forth it would tween between the two sizes.

I can find code snippets for Translate and rotate but nothing for scaling.. Please help.

答:
```<code>void Update () {
   float accelY = Input.acceleration.y;
   transform.localScale = new Vector3(0, Mathf.Clamp(transform.localScale.y + accelY, 1f,
   100f), 0)
}
</code>```

You should add Time.deltaTime because Update is frames/sec dependant:

```<code>[SerializeField]
float speed = 10f;
[SerializeField]
float minSize = 1f;
[SerializeField]
float maxSize = 100f;

void Update () {
   float accelY = Input.acceleration.y * Time.deltaTime * speed;
   transform.localScale = new Vector3(0, Mathf.Clamp(transform.localScale.y + accelY, minSize ,
   maxSize ), 0)
}
</code>```

Body:
I'm trying to translate the roll(y) of a phone into the scale of an object but with size limits.

I have had success scaling to infinity +- with the following code:

void Update () {
   float accelY = Input.acceleration.y;
   transform.localScale += new Vector3(0, accelY, 0);
}

The problem I am having is with the max and min limits of the scale.

I attempted to use Clamp in the following way but have ended up just limiting the direction of scale where -y (rolling toward myself) equals 0 therefore no shrinking happens and +y (rolling away from self) scales up endlessly assumed at a max rate of 0.045f.

transform.localScale += new Vector3(0, Mathf.Clamp(accelY, 0f, 0.045f), 0);

In an ideal world I'd like to have a min scale of y = 1 and a max scale y = 100 and as you roll the phone back and forth it would tween between the two sizes.

I can find code snippets for Translate and rotate but nothing for scaling.. Please help.

Body:
void Update () {
   float accelY = Input.acceleration.y;
   transform.localScale = new Vector3(0, Mathf.Clamp(transform.localScale.y + accelY, 1f,
   100f), 0)
}

You should add Time.deltaTime because Update is frames/sec dependant:

[SerializeField]
float speed = 10f;
[SerializeField]
float minSize = 1f;
[SerializeField]
float maxSize = 100f;

void Update () {
   float accelY = Input.acceleration.y * Time.deltaTime * speed;
   transform.localScale = new Vector3(0, Mathf.Clamp(transform.localScale.y + accelY, minSize ,
   maxSize ), 0)
}


问:
SQL Where clause use if value greater than
I try create optional query.I have in sql proc 4 param.

```<code>ALTER PROCEDURE [dbo].[sp_OdevTümBilgiler]
@ogretmenUserId int,

@ogrenciUserId int,
@odevAdi nvarchar(50) = null,
@odevId int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
 SELECT
  s.*,
  o.*,
  ko.*,
  ogretmenUser.UserID AS OgretmenUserId,
  ogrenciUser.UserID AS OgrenciId,
  (ogretmenUser.Name + ' ' + ogretmenUser.Surname) AS OgretmenFullName,
  (ogrenciUser.Name + ' ' + ogrenciUser.Surname) AS OgrenciFullName
FROM KullaniciOdev AS ko
INNER JOIN Odev o
  ON ko.OdevId = o.OdevId
INNER JOIN FrUser ogrenciUser
  ON ogrenciUser.UserID = ko.UserId
INNER JOIN Sinif s
  ON s.SinifId = o.ClassId
INNER JOIN FrUser ogretmenUser
  ON ogretmenUser.UserID = s.OlusturanKullaniciId
WHERE 1=1 and (@ogrenciUserId > 0 and ko.UserId = @ogrenciUserId) and
((@ogretmenUserId > 0) and s.OlusturanKullaniciId = @ogretmenUserId) and
(@odevAdi IS NOT NULL and LEN(@odevAdi) > 0 and o.OdevAdi = @odevAdi) and
(@odevId > 0 and ko.OdevId=@odevId)
  END
</code>```

In my application @ogretmenUserId default value is -1,

@ogrenciUserId default value is -1,

@odevAdi null,

@odevId -1

but nothing is returning with right values  is the query false ?

Example I try :

odevId=1  and ogretmenUserId=1027  but nothing is returning

答:
All your conditions will work only when you pass the right values. When the default values are passed then it will fail. Example consider the first condition

```<code>(@ogrenciUserId > 0 and ko.UserId = @ogrenciUserId)
</code>```

Here the default values is -1 but the code always want it to be greater than 0 hence when -1 is passed it will fail. Same goes with other conditions

You need OR condition with default values for each parameter. So when the condition will be satisfied either with default value or when it is passed with proper value.

```<code>WHERE  ( @ogrenciUserId = -1
          OR ko.userid = @ogrenciUserId )
       AND ( @ogretmenUserId = -1
              OR s.olusturankullaniciid = @ogretmenUserId )
       AND ( @odevAdi IS NULL
              OR o.odevadi = @odevAdi )
       AND ( @odevId = -1
              OR ko.odevid = @odevId )
</code>```

Body:
I try create optional query.I have in sql proc 4 param.

ALTER PROCEDURE [dbo].[sp_OdevTümBilgiler]
@ogretmenUserId int,

@ogrenciUserId int,
@odevAdi nvarchar(50) = null,
@odevId int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
 SELECT
  s.*,
  o.*,
  ko.*,
  ogretmenUser.UserID AS OgretmenUserId,
  ogrenciUser.UserID AS OgrenciId,
  (ogretmenUser.Name + ' ' + ogretmenUser.Surname) AS OgretmenFullName,
  (ogrenciUser.Name + ' ' + ogrenciUser.Surname) AS OgrenciFullName
FROM KullaniciOdev AS ko
INNER JOIN Odev o
  ON ko.OdevId = o.OdevId
INNER JOIN FrUser ogrenciUser
  ON ogrenciUser.UserID = ko.UserId
INNER JOIN Sinif s
  ON s.SinifId = o.ClassId
INNER JOIN FrUser ogretmenUser
  ON ogretmenUser.UserID = s.OlusturanKullaniciId
WHERE 1=1 and (@ogrenciUserId > 0 and ko.UserId = @ogrenciUserId) and
((@ogretmenUserId > 0) and s.OlusturanKullaniciId = @ogretmenUserId) and
(@odevAdi IS NOT NULL and LEN(@odevAdi) > 0 and o.OdevAdi = @odevAdi) and
(@odevId > 0 and ko.OdevId=@odevId)
  END

In my application @ogretmenUserId default value is -1,

@ogrenciUserId default value is -1,

@odevAdi null,

@odevId -1

but nothing is returning with right values  is the query false ?

Example I try :

odevId=1  and ogretmenUserId=1027  but nothing is returning

Body:
All your conditions will work only when you pass the right values. When the default values are passed then it will fail. Example consider the first condition

(@ogrenciUserId > 0 and ko.UserId = @ogrenciUserId)

Here the default values is -1 but the code always want it to be greater than 0 hence when -1 is passed it will fail. Same goes with other conditions

You need OR condition with default values for each parameter. So when the condition will be satisfied either with default value or when it is passed with proper value.

WHERE  ( @ogrenciUserId = -1
          OR ko.userid = @ogrenciUserId )
       AND ( @ogretmenUserId = -1
              OR s.olusturankullaniciid = @ogretmenUserId )
       AND ( @odevAdi IS NULL
              OR o.odevadi = @odevAdi )
       AND ( @odevId = -1
              OR ko.odevid = @odevId )


问:
How to generate a sequence that corresponds for True and False
So what I want to do is a create a sequence in a dataframe that progresses from 1, but whenever it encounters TRUE's based on another column, it matches those up if they are in sequential rows.

For example, in this dataset:

```<code>df <- data.frame(date = c("11","12", "13","14","15","16","17","18","19","20","21", "22", "23"),
    flag = c(FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE))
</code>```

I want this as the output:

```<code>df <- data.frame(date = c("11","12", "13","14","15","16","17","18","19","20","21", "22", "23"),
             flag = c(FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE),
             id = c(1, 2, 3, 4, 4, 5, 6, 7, 7, 7, 8, 9, 10))
</code>```

Keep in mind that the dates being in sequential order is just an example as I am working with a big dataset so they will not coordinate at all. Also, the flag column is just one column in a dataframe with dozens more columns

答:
Here is one option with data.table

```<code>library(data.table)
i1 <- setDT(df)[, grp := rleid(flag)][, .I[flag & (seq_len(.N)==1)], grp]$V1
df[, flag1:= flag][i1, flag1 := FALSE][, id := cumsum(!flag1)][, c('flag1', 'grp') := NULL][]
#    date  flag id
# 1:   11 FALSE  1
# 2:   12 FALSE  2
# 3:   13 FALSE  3
# 4:   14  TRUE  4
# 5:   15  TRUE  4
# 6:   16 FALSE  5
# 7:   17 FALSE  6
# 8:   18  TRUE  7
# 9:   19  TRUE  7
#10:   20  TRUE  7
#11:   21 FALSE  8
#12:   22 FALSE  9
1#3:   23 FALSE 10
</code>```

Body:
So what I want to do is a create a sequence in a dataframe that progresses from 1, but whenever it encounters TRUE's based on another column, it matches those up if they are in sequential rows.

For example, in this dataset:

df <- data.frame(date = c("11","12", "13","14","15","16","17","18","19","20","21", "22", "23"),
    flag = c(FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE))

I want this as the output:

df <- data.frame(date = c("11","12", "13","14","15","16","17","18","19","20","21", "22", "23"),
             flag = c(FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE),
             id = c(1, 2, 3, 4, 4, 5, 6, 7, 7, 7, 8, 9, 10))

Keep in mind that the dates being in sequential order is just an example as I am working with a big dataset so they will not coordinate at all. Also, the flag column is just one column in a dataframe with dozens more columns

Body:
Here is one option with data.table

library(data.table)
i1 <- setDT(df)[, grp := rleid(flag)][, .I[flag & (seq_len(.N)==1)], grp]$V1
df[, flag1:= flag][i1, flag1 := FALSE][, id := cumsum(!flag1)][, c('flag1', 'grp') := NULL][]
#    date  flag id
# 1:   11 FALSE  1
# 2:   12 FALSE  2
# 3:   13 FALSE  3
# 4:   14  TRUE  4
# 5:   15  TRUE  4
# 6:   16 FALSE  5
# 7:   17 FALSE  6
# 8:   18  TRUE  7
# 9:   19  TRUE  7
#10:   20  TRUE  7
#11:   21 FALSE  8
#12:   22 FALSE  9
1#3:   23 FALSE 10


问:
count the number of zero group bits in a number
How do you count the number of zero group bits in a number? group bits
is any consecutive zero or one bits, for example, 2 is represented
as ....0000000000000000010 has two zero bits groups the least
significant bit and the group starts after one.
Also, I am in a bad need for algorithms on bits manipulation if any
one has a reference, please share</p>

答: The simpliest way is to count number of transitions from one to zero in loop using the shift of a bit mask along with bitwise `and' operation. It also necessary to check the first bit and increase obtained quantity by one if it is 0.</p>


问:
How to checkout merge request locally, and create new local branch?
I have GitLab repository there and I need to test every merge request locally, before merging to the target branch.

How can I pull/fetch merge request as a new branch?

答:
Pull merge request to new branch

git fetch origin merge-requests/REQUESTID/head:BRANCHNAME

i.e
git fetch origin merge-requests/10/head:file_upload

Checkout to newly created branch

git checkout BRANCHNAME

i.e (git checkout file_upload)

OR with single command

git fetch origin merge-requests/REQUESTID/head:BRANCHNAME && git checkout BRANCHNAME

i.e
git fetch origin merge-requests/18/head:file_upload && git checkout file_upload


问:
How do I get the source range or cell address of argument of function in VBA?
For a project of mine I need to get the cell address of the cell a user chooses as source for the argument for my function:

```<code>Public Function ItemNumber(AnyValueFromAnyCell) As String
End Sub
</code>```

If the user selects, say, cell F6 as the source for "AnyValueFromAnyCell" when using the function, I need its address to also manipulate that cell.

The idea is that if someone uses my new function, the function changes the fillcolour from the source cell too.

I hope this is clear enough.

答:
Extending a little bit Sorceri's answer above to allow the function to be used either from a cell formula or as a helper in the code, and to display other parts of the code that were asked for in the main question:</p>

```<code>Public Function ItemNumber(arg As Variant) As String
Dim addressOfCell, valueOfCell
Dim rnSource As Range, rnCaller As Range

 On Error Resume Next

 valueOfCell = arg
 set rnSource = IIf(TypeName(arg) = "Range", arg, Nothing)
 addressOfCell = vbNullString
 If Not (rnSource Is Nothing) Then  addressOfCell = rnSource.Address

 Set rnCaller = Application.Caller
 If Not (rnCaller Is Nothing) then
     ' queue task here to change the interior color of the cell calling the function to be executed, as per the following solution:
     ' Source: https://stackoverflow.com/questions/8520732/i-dont-want-my-excel-add-in-to-return-an-array-instead-i-need-a-udf-to-change/8711582#8711582
 End If
End Function
</code>```

Body:
For a project of mine I need to get the cell address of the cell a user chooses as source for the argument for my function:

Public Function ItemNumber(AnyValueFromAnyCell) As String
End Sub

If the user selects, say, cell F6 as the source for "AnyValueFromAnyCell" when using the function, I need its address to also manipulate that cell.

The idea is that if someone uses my new function, the function changes the fillcolour from the source cell too.

I hope this is clear enough.

Body:
Extending a little bit Sorceri's answer above to allow the function to be used either from a cell formula or as a helper in the code, and to display other parts of the code that were asked for in the main question:

Public Function ItemNumber(arg As Variant) As String
Dim addressOfCell, valueOfCell
Dim rnSource As Range, rnCaller As Range

 On Error Resume Next

 valueOfCell = arg
 set rnSource = IIf(TypeName(arg) = "Range", arg, Nothing)
 addressOfCell = vbNullString
 If Not (rnSource Is Nothing) Then  addressOfCell = rnSource.Address

 Set rnCaller = Application.Caller
 If Not (rnCaller Is Nothing) then
     ' queue task here to change the interior color of the cell calling the function to be executed, as per the following solution:
     ' Source: https://stackoverflow.com/questions/8520732/i-dont-want-my-excel-add-in-to-return-an-array-instead-i-need-a-udf-to-change/8711582#8711582
 End If
End Function


问:
C - should I use a variable array of function pointers
This question is about how to solve my problem on the level of how I design my program. For a school project, I'm building a shell, which has several built-in functions. One of these function's purpose (cmd_type) is to check to see if the argument provided is in that list of functions. Here is a partial implementation of it:

```<code>int cmd_type(int argc, char *argv[]) {
    if (argc == 2) {
        for (int i = 0; i < BUILTIN_FUNC_COUNT; i++) {
            if (strcmp(cmds_name[i], argv[1]) == 0) {
                printf("%s is a shell builtin\n", argv[1]);
                return 0; // found it
            }
        }

        // still need to search path, call stat(path/cmd)
        errmsg("not implemented! type", 1);
    } else {
        err_msg("type", 1);
    }
}
</code>```

Defining manual if statements for every function my shell supports sounds like a bad choice because the list might expand over time, and I need to store the list of function names anyway. So originally, I planned to define an array of function names and an array of their pointers, like so:

```<code>char cmds_name[BUILTIN_FUNC_COUNT-1][16];
char (*cmds_ptr)(int,*char[])[BUILTIN_FUNC_COUNT-1];
// make list of built-in funcs
strcpy(cmds_name[0], "exit");
strcpy(cmds_name[1], "cd");
// make list of func pointers
cmds_ptr[0] = &cmd_exit;
cmds_ptr[1] = &cmd_cd;
</code>```

They're accessed like so:

```<code>// try builtin cmds
for (int i = 0; i < BUILTIN_FUNC_COUNT; i++) {
    if (strcmp(cmds_name[i], argv[0]) == 0) {
        last_cmd_err = (*cmds_ptr[i])(argc, argv);
        continue; // we found it, so next loop
    }
}
</code>```

Then they'd each happily take (int argc, char *argv[]) as arguments. But the cmd_path() needs access to the list in addition to those arguments, so I'd have to define it as a global, or define a global pointer to it... In the process of researching this, I found this answer, saying a similar approach was really bad style: https://stackoverflow.com/a/41425477/5537652

So my questions are: Is this a good way to solve this problem, or should I just do if/else statements/is there a better way? Would you recommend a global pointer to the array of function names?

答:
I am going to propose a structure of cmd_name and function pointer like this:

```<code>typedef struct{
  char cmds_name[16];
  char (*cmds_ptr)(int,*char[]);
} cmd_type;
</code>```

Now define a static table of this type for all your cmds:

```<code>static const cmd_type cmd_table[] = {
  {"exit", &cmd_exit},
  {"cd", &cmd_cd},
  .......
  .......
};
</code>```

Finally access it like this:

```<code>for (int i = 0; i < BUILTIN_FUNC_COUNT; i++) {
  if (strcmp(cmd_table[i].cmds_name, argv[0]) == 0) {
    last_cmd_err = (*cmd_table[i].cmds_ptr)(argc, argv);
    continue; // we found it, so next loop
  }
}
</code>```

The decision to choose between if-else vs a global table is a matter of personal taste and coding style. I would prefer the above solution simply because it improves ** code readability** and reduces clutter. There may be other constraints in your environment that can influence your decision - like if the no of table entries is huge and there is a limitation on global memory space - the if-else route would be a better choice..

HTH!

Body:
This question is about how to solve my problem on the level of how I design my program. For a school project, I'm building a shell, which has several built-in functions. One of these function's purpose (cmd_type) is to check to see if the argument provided is in that list of functions. Here is a partial implementation of it:

int cmd_type(int argc, char *argv[]) {
    if (argc == 2) {
        for (int i = 0; i < BUILTIN_FUNC_COUNT; i++) {
            if (strcmp(cmds_name[i], argv[1]) == 0) {
                printf("%s is a shell builtin\n", argv[1]);
                return 0; // found it
            }
        }

        // still need to search path, call stat(path/cmd)
        errmsg("not implemented! type", 1);
    } else {
        err_msg("type", 1);
    }
}

Defining manual if statements for every function my shell supports sounds like a bad choice because the list might expand over time, and I need to store the list of function names anyway. So originally, I planned to define an array of function names and an array of their pointers, like so:

char cmds_name[BUILTIN_FUNC_COUNT-1][16];
char (*cmds_ptr)(int,*char[])[BUILTIN_FUNC_COUNT-1];
// make list of built-in funcs
strcpy(cmds_name[0], "exit");
strcpy(cmds_name[1], "cd");
// make list of func pointers
cmds_ptr[0] = &cmd_exit;
cmds_ptr[1] = &cmd_cd;

They're accessed like so:

// try builtin cmds
for (int i = 0; i < BUILTIN_FUNC_COUNT; i++) {
    if (strcmp(cmds_name[i], argv[0]) == 0) {
        last_cmd_err = (*cmds_ptr[i])(argc, argv);
        continue; // we found it, so next loop
    }
}

Then they'd each happily take (int argc, char *argv[]) as arguments. But the cmd_path() needs access to the list in addition to those arguments, so I'd have to define it as a global, or define a global pointer to it... In the process of researching this, I found this answer, saying a similar approach was really bad style: https://stackoverflow.com/a/41425477/5537652

So my questions are: Is this a good way to solve this problem, or should I just do if/else statements/is there a better way? Would you recommend a global pointer to the array of function names?

Body:
I am going to propose a structure of cmd_name and function pointer like this:

typedef struct{
  char cmds_name[16];
  char (*cmds_ptr)(int,*char[]);
} cmd_type;

Now define a static table of this type for all your cmds:

static const cmd_type cmd_table[] = {
  {"exit", &cmd_exit},
  {"cd", &cmd_cd},
  .......
  .......
};

Finally access it like this:

for (int i = 0; i < BUILTIN_FUNC_COUNT; i++) {
  if (strcmp(cmd_table[i].cmds_name, argv[0]) == 0) {
    last_cmd_err = (*cmd_table[i].cmds_ptr)(argc, argv);
    continue; // we found it, so next loop
  }
}

The decision to choose between if-else vs a global table is a matter of personal taste and coding style. I would prefer the above solution simply because it improves ** code readability** and reduces clutter. There may be other constraints in your environment that can influence your decision - like if the no of table entries is huge and there is a limitation on global memory space - the if-else route would be a better choice..

HTH!


问:
Can i retrieve array value not using loop?
is there a way to retrieve array value not using any loop function?
I have this sort of array</p>

```<code>$at=array(
    array(
        array('Title:','titl','s','c',$titles),
        array('First Name:','name','i','A',2,10 ),
    ),
</code>```

答:
you need to know the key of the value you want to select </p>

```<code>  echo $at[0];
  echo $at[0][0];
  echo $at[0][3];
</code>```

Body:
is there a way to retrieve array value not using any loop function?
I have this sort of array

$at=array(
    array(
        array('Title:','titl','s','c',$titles),
        array('First Name:','name','i','A',2,10 ),
    ),

Body:
you need to know the key of the value you want to select

  echo $at[0];
  echo $at[0][0];
  echo $at[0][3];


问:
Connection reset by peer error while using celery stats()
I'm trying to get stats for my celery Que (rabbitmq). I'm using celery.app.control.Inspect().stats() API. I'm doing this on a web server, I can get the stats only one time. If I refresh the page I'm getting "[Errno 104] Connection reset by peer" Error. how can I deal with this.

/init.py

```<code>celtasks = Celery(app.name,"rabbit mq url")
</code>```

/helpers.py

```<code>get_stats():
     stats = celtasks.control.Inspect().stats()
     return stats
</code>```

whenever there is a request "get_stats" function is hit. It is only working for the first request after this, it says connection reset by peer error.

If I go by connection has been reset and try to create the connection again, I get error

updated /helpers.py

```<code> get_stats():
     celtasks = Celery(app.name,"rabbit mq url")
     stats = celtasks.control.Inspect().stats()
     return stats
</code>```

Rabbitmq logs

```<code>=WARNING REPORT==== 10-Jul-2017::14:11:54 ===
closing AMQP connection <0.29185.6> (10.246.170.70:48618 -> 10.24.83.115:5672):
connection_closed_abruptly

=WARNING REPORT==== 10-Jul-2017::14:11:54 ===
closing AMQP connection <0.29197.6> (10.246.170.70:48620 -> 10.24.83.115:5672):
connection_closed_abruptly
"rabbit@oser000300.log-20170625" 9054L, 361662C
</code>```

答: AT most times , CONNECTION RESET BY PEER is because the server close the connection itself, however the client does not know . When client want to communicate to sever through this broke connection, it receive this ERROR. In your case , maybe the hang time (time interval between two stats()) is too long, and server think this connection is useless and close it .  </p>

Body:
I'm trying to get stats for my celery Que (rabbitmq). I'm using celery.app.control.Inspect().stats() API. I'm doing this on a web server, I can get the stats only one time. If I refresh the page I'm getting "[Errno 104] Connection reset by peer" Error. how can I deal with this.

/init.py

celtasks = Celery(app.name,"rabbit mq url")

/helpers.py

get_stats():
     stats = celtasks.control.Inspect().stats()
     return stats

whenever there is a request "get_stats" function is hit. It is only working for the first request after this, it says connection reset by peer error.

If I go by connection has been reset and try to create the connection again, I get error

updated /helpers.py

 get_stats():
     celtasks = Celery(app.name,"rabbit mq url")
     stats = celtasks.control.Inspect().stats()
     return stats

Rabbitmq logs

=WARNING REPORT==== 10-Jul-2017::14:11:54 ===
closing AMQP connection <0.29185.6> (10.246.170.70:48618 -> 10.24.83.115:5672):
connection_closed_abruptly

=WARNING REPORT==== 10-Jul-2017::14:11:54 ===
closing AMQP connection <0.29197.6> (10.246.170.70:48620 -> 10.24.83.115:5672):
connection_closed_abruptly
"rabbit@oser000300.log-20170625" 9054L, 361662C


问:
Getting maxlength from array
I'm trying to get the longest description from $productDetail array, but it returns empty array elements:

```<code>$desc = array_map(function($a) {
            return (!!$desc && strlen($desc) < strlen($a["desc"])) ?
                $a["desc"] : $desc;
        }, $productDetail);
</code>```

答:
```<code>$cars = array("Volvo", "BMW", "Toyota");
$lengths = array_map('strlen', $cars);
$maxLength = max($lengths);
$index = array_search($maxLength, $lengths);
echo $cars[$index];
</code>```

Title: Getting maxlength from array

Body:
I'm trying to get the longest description from $productDetail array, but it returns empty array elements:

$desc = array_map(function($a) {
            return (!!$desc && strlen($desc) < strlen($a["desc"])) ?
                $a["desc"] : $desc;
        }, $productDetail);


问:
Sending SMS using VB.NET
```<code>Dim message As New MailMessage()
message.To.Add("9999999999@ideacellular.net")
message.From = New MailAddress("xyz@gmail.com")
message.Subject = "Hi"
message.Body = "SMS"
Dim smtp As New SmtpClient("smtp.gmail.com")
smtp.EnableSsl = True
smtp.Credentials = New System.Net.NetworkCredential("xyz@gmail.com", "password")
smtp.Send(message)
</code>```

I have written the above code in order to send SMS from my vb.net application to a Mobile phone.

When i execute this code i am not getting any errors, at the same time i am not receiving any SMS.

What could be the problem ?

答:
Simple Send SMS using VB.NET + AT Command :</p>

```

        Try
            With SerialPort1
                .Write("at+cmgf=1" & vbCrLf)
                Threading.Thread.Sleep(1000)
                .Write("at+cmgs=" & Chr(34) & TextBox1.Text & Chr(34) & vbCrLf)
                .Write(TextBox2.Text & Chr(26))
                Threading.Thread.Sleep(1000)
            End With
        Catch ex As Exception

        End Try
```

Title: Sending SMS using VB.NET

Body:
Dim message As New MailMessage()
message.To.Add("9999999999@ideacellular.net")
message.From = New MailAddress("xyz@gmail.com")
message.Subject = "Hi"
message.Body = "SMS"
Dim smtp As New SmtpClient("smtp.gmail.com")
smtp.EnableSsl = True
smtp.Credentials = New System.Net.NetworkCredential("xyz@gmail.com", "password")
smtp.Send(message)

I have written the above code in order to send SMS from my vb.net application to a Mobile phone.

When i execute this code i am not getting any errors, at the same time i am not receiving any SMS.

What could be the problem ?

Body:
Simple Send SMS using VB.NET + AT Command :

        Try
            With SerialPort1
                .Write("at+cmgf=1" & vbCrLf)
                Threading.Thread.Sleep(1000)
                .Write("at+cmgs=" & Chr(34) & TextBox1.Text & Chr(34) & vbCrLf)
                .Write(TextBox2.Text & Chr(26))
                Threading.Thread.Sleep(1000)
            End With
        Catch ex As Exception

        End Try


问:
Error in Web API Config file c#
I am New to C# and I am developing a web api to perform CRUD Operations on SQL Server.

I am receiving the error in web config file.

I have Created Model Class:

```<code>public class Test_Automation_Data
{
    private String strTest_Automation_Group;
    private String strTest_Automation_Application;
    private String strTest_Automation_Count;

    public string Test_Automation_Group { get => strTest_Automation_Group; set => strTest_Automation_Group = value; }
    public string Test_Automation_Application { get => strTest_Automation_Application; set => strTest_Automation_Application = value; }
    public string Test_Automation_Count { get => strTest_Automation_Count; set => strTest_Automation_Count = value; }
}
public class TestAutomationDataModel
{

    private SqlConnection GetSQLConnection()
    {
        SqlConnection objConnection = null;
        try
        {
            String ConnectionString = "Data Source=**********;Initial Catalog=***********;User ID=************;Password=*********";
            objConnection = new SqlConnection(ConnectionString);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return objConnection;
    }

    public List<Test_Automation_Data> GetTestData()
    {
        List<Test_Automation_Data> Data = new List<Test_Automation_Data>();
        try
        {
            SqlConnection obj_Connection = GetSQLConnection();
            obj_Connection.Open();
            string SQL_Query = "SELECT * FROM Test_Automation_Inventory";
            if (obj_Connection.State == System.Data.ConnectionState.Open)
            {
                SqlCommand objCommand = new SqlCommand(SQL_Query, obj_Connection);
                SqlDataReader DataReader = objCommand.ExecuteReader();
                if (DataReader.HasRows)
                {
                    while (DataReader.Read())
                    {
                        Test_Automation_Data obj_TestData = new Test_Automation_Data();
                        obj_TestData.Test_Automation_Group = DataReader.GetValue(0).ToString();
                        obj_TestData.Test_Automation_Application = DataReader.GetValue(1).ToString();
                        obj_TestData.Test_Automation_Count = DataReader.GetValue(2).ToString();
                        Data.Add(obj_TestData);
                    }
                    DataReader.Close();
                    obj_Connection.Close();
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return Data;

    }

    public int DeleteTest(String Test_Group, String Test_Application)
    {
        int RowCount = 0;
        try
        {
            SqlConnection obj_Connection = GetSQLConnection();
            obj_Connection.Open();
            string SQL_Query = "DELETE FROM Test_Automation_Inventory WHERE Test_Inventory_Group = '" + Test_Group + "' and Test_Inventory_Application = '" + Test_Application + "'";
            if (obj_Connection.State == System.Data.ConnectionState.Open)
            {
                SqlCommand objCommand = new SqlCommand(SQL_Query, obj_Connection);
                RowCount = int.Parse(objCommand.ExecuteNonQuery().ToString());
            }
            obj_Connection.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return RowCount;
    }

    public int CreateTest(String Test_Group, String Test_Application)
    {
        int RowCount = 0;
        try
        {
            SqlConnection obj_Connection = GetSQLConnection();
            obj_Connection.Open();
            if (obj_Connection.State == System.Data.ConnectionState.Open)
            {
                SqlCommand objCommand = new SqlCommand();
                objCommand.CommandType = System.Data.CommandType.Text;
                objCommand.CommandText = "INSERT INTO Test_Automation_Inventory  Values (@Test_Group,@Test_Application,@Test_Count)";
                objCommand.Connection = obj_Connection;

                objCommand.Parameters.AddWithValue("@Test_Group", Test_Group);
                objCommand.Parameters.AddWithValue("@Test_Application", Test_Application);
                objCommand.Parameters.AddWithValue("@Test_Count", 0);
                RowCount = objCommand.ExecuteNonQuery();
            }
            obj_Connection.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return RowCount;
    }
}
</code>```

And here is my Controller Class:

```<code>public class TestController : ApiController
{

    // GET: api/TestAutomationInventory
    public List<Test_Automation_Data> Get()
    {
        TestAutomationDataModel obj = new TestAutomationDataModel();
        return obj.GetTestData();
    }
}
</code>```

Here is my Web Config File :

```<code> <compilers>
  <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
  <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</code>```

I am Receiving the following error when i am trying to run the project :

```<code>Line 39:       <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
</code>```

How to resolve the issue

答:
You are probably using a package which relies on this assembly that assumes you already have it installed.

You can install it using package manager:

And then enter the following command:

```<code>PM> Install-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform
</code>```

It is probably a good idea to install it your Global Assembly Cache so future applications don't get the same problem.

```<code>gacutil -i "C:\*PATH TO YOUR APP CODE*\bin\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll"
</code>```

Title: Error in Web API Config file c#

Body:
I am New to C# and I am developing a web api to perform CRUD Operations on SQL Server.

I am receiving the error in web config file.

I have Created Model Class:

public class Test_Automation_Data
{
    private String strTest_Automation_Group;
    private String strTest_Automation_Application;
    private String strTest_Automation_Count;

    public string Test_Automation_Group { get => strTest_Automation_Group; set => strTest_Automation_Group = value; }
    public string Test_Automation_Application { get => strTest_Automation_Application; set => strTest_Automation_Application = value; }
    public string Test_Automation_Count { get => strTest_Automation_Count; set => strTest_Automation_Count = value; }
}
public class TestAutomationDataModel
{

    private SqlConnection GetSQLConnection()
    {
        SqlConnection objConnection = null;
        try
        {
            String ConnectionString = "Data Source=**********;Initial Catalog=***********;User ID=************;Password=*********";
            objConnection = new SqlConnection(ConnectionString);
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return objConnection;
    }

    public List<Test_Automation_Data> GetTestData()
    {
        List<Test_Automation_Data> Data = new List<Test_Automation_Data>();
        try
        {
            SqlConnection obj_Connection = GetSQLConnection();
            obj_Connection.Open();
            string SQL_Query = "SELECT * FROM Test_Automation_Inventory";
            if (obj_Connection.State == System.Data.ConnectionState.Open)
            {
                SqlCommand objCommand = new SqlCommand(SQL_Query, obj_Connection);
                SqlDataReader DataReader = objCommand.ExecuteReader();
                if (DataReader.HasRows)
                {
                    while (DataReader.Read())
                    {
                        Test_Automation_Data obj_TestData = new Test_Automation_Data();
                        obj_TestData.Test_Automation_Group = DataReader.GetValue(0).ToString();
                        obj_TestData.Test_Automation_Application = DataReader.GetValue(1).ToString();
                        obj_TestData.Test_Automation_Count = DataReader.GetValue(2).ToString();
                        Data.Add(obj_TestData);
                    }
                    DataReader.Close();
                    obj_Connection.Close();
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return Data;

    }

    public int DeleteTest(String Test_Group, String Test_Application)
    {
        int RowCount = 0;
        try
        {
            SqlConnection obj_Connection = GetSQLConnection();
            obj_Connection.Open();
            string SQL_Query = "DELETE FROM Test_Automation_Inventory WHERE Test_Inventory_Group = '" + Test_Group + "' and Test_Inventory_Application = '" + Test_Application + "'";
            if (obj_Connection.State == System.Data.ConnectionState.Open)
            {
                SqlCommand objCommand = new SqlCommand(SQL_Query, obj_Connection);
                RowCount = int.Parse(objCommand.ExecuteNonQuery().ToString());
            }
            obj_Connection.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return RowCount;
    }

    public int CreateTest(String Test_Group, String Test_Application)
    {
        int RowCount = 0;
        try
        {
            SqlConnection obj_Connection = GetSQLConnection();
            obj_Connection.Open();
            if (obj_Connection.State == System.Data.ConnectionState.Open)
            {
                SqlCommand objCommand = new SqlCommand();
                objCommand.CommandType = System.Data.CommandType.Text;
                objCommand.CommandText = "INSERT INTO Test_Automation_Inventory  Values (@Test_Group,@Test_Application,@Test_Count)";
                objCommand.Connection = obj_Connection;

                objCommand.Parameters.AddWithValue("@Test_Group", Test_Group);
                objCommand.Parameters.AddWithValue("@Test_Application", Test_Application);
                objCommand.Parameters.AddWithValue("@Test_Count", 0);
                RowCount = objCommand.ExecuteNonQuery();
            }
            obj_Connection.Close();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return RowCount;
    }
}

And here is my Controller Class:

public class TestController : ApiController
{

    // GET: api/TestAutomationInventory
    public List<Test_Automation_Data> Get()
    {
        TestAutomationDataModel obj = new TestAutomationDataModel();
        return obj.GetTestData();
    }
}

Here is my Web Config File :

 <compilers>
  <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
  <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>

I am Receiving the following error when i am trying to run the project :

Line 39:       <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />

How to resolve the issue

Body:
You are probably using a package which relies on this assembly that assumes you already have it installed.

You can install it using package manager:

And then enter the following command:

PM> Install-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform

It is probably a good idea to install it your Global Assembly Cache so future applications don't get the same problem.

gacutil -i "C:\*PATH TO YOUR APP CODE*\bin\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll"


问:
how to display table view cells whenever we need to click on one cell
i am writing one app in that app i have to display tableview with two cells.while the first cell touched by the user then it have to show some other cells within the view (i cant use navigation here) and also second cell also visible..can any one tell me the suggestion for this.
thank you all.</p>

答:
If you want to insert table view cells when you are clicking on a cell, try the following code.

Lets consider you are going to insert 3 rows in the position 1, 2 and 3 in the section 0. In the didSelectRowAtIndexPath method, do the following. Here the rows will be inserted in section 0, if we select row 0(first row) in section 0(first section).

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

   if (indexPath.row == 0 && indexPath.section == 0) {

       // Create indexPaths for the rows you are going to insert

       NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:1 inSection:0]];
       NSIndexPath *indexPath2 = [NSIndexPath indexPathForRow:2 inSection:0]];
       NSIndexPath *indexPath3 = [NSIndexPath indexPathForRow:3 inSection:0]];

       // Increase the number of rows in section 0 by 3, as we are inserting 3 rows here

       numberOfRowsInSectionZero = numberOfRowsInSectionZero + 3;

       // Insert the rows

       [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath1, indexPath2, indexPath3, nil] withRowAnimation:UITableViewRowAnimationFade];
    }
}
</code>```

In your numberOfRowsInSection method, you should be having something like the following,

```<code>- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section {

    // some code here

    if (section == 0) return numberOfRowsInSectionZero;

    // some code here
}
</code>```

And make sure you are having appropriate code in cellForRowAtIndexPath method to display content in the newly displayed rows.

Note: You have to alter your code in such a way that the rows are not inserted when clicking the row 0 of section 0, when they are already been inserted.

Body:
If you want to insert table view cells when you are clicking on a cell, try the following code.

Lets consider you are going to insert 3 rows in the position 1, 2 and 3 in the section 0. In the didSelectRowAtIndexPath method, do the following. Here the rows will be inserted in section 0, if we select row 0(first row) in section 0(first section).

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

   if (indexPath.row == 0 && indexPath.section == 0) {

       // Create indexPaths for the rows you are going to insert

       NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:1 inSection:0]];
       NSIndexPath *indexPath2 = [NSIndexPath indexPathForRow:2 inSection:0]];
       NSIndexPath *indexPath3 = [NSIndexPath indexPathForRow:3 inSection:0]];

       // Increase the number of rows in section 0 by 3, as we are inserting 3 rows here

       numberOfRowsInSectionZero = numberOfRowsInSectionZero + 3;

       // Insert the rows

       [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath1, indexPath2, indexPath3, nil] withRowAnimation:UITableViewRowAnimationFade];
    }
}

In your numberOfRowsInSection method, you should be having something like the following,

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section {

    // some code here

    if (section == 0) return numberOfRowsInSectionZero;

    // some code here
}

And make sure you are having appropriate code in cellForRowAtIndexPath method to display content in the newly displayed rows.

Note: You have to alter your code in such a way that the rows are not inserted when clicking the row 0 of section 0, when they are already been inserted.


问:
How to detect when browser height is less than device height CSS
I have a page where the CSS of an element needs to be modified for devices like the Nexus 5X (which has the 'Android nav bars' at the top and bottom - these push the elements on the page around)

Currently I use this jQuery to detect and adjust this. But is there a way to do this by CSS media queries instead?

Code below:

```<code>if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
                        is_mobile = true;
                    }
if ($( window ).height()<window.screen.height && is_mobile==true) {
            $('#my_element').css("height","46vh");
        }
</code>```

So in CSS I was thinking something like comparing height < device-height (and another condition to check for mobile which is simple), but apparently device-height is deprecated (and also I don't think I can do such a comparison directly between the 2 heights anyway)?

Thanks a lot

答:
you can use media query:

```<code>@media all and (min-height: yourValue ) {
  selector {
    //Code Css
  }
}
</code>```

read more : https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries

Body:
I have a page where the CSS of an element needs to be modified for devices like the Nexus 5X (which has the 'Android nav bars' at the top and bottom - these push the elements on the page around)

Currently I use this jQuery to detect and adjust this. But is there a way to do this by CSS media queries instead?

Code below:

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
                        is_mobile = true;
                    }
if ($( window ).height()<window.screen.height && is_mobile==true) {
            $('#my_element').css("height","46vh");
        }

So in CSS I was thinking something like comparing height < device-height (and another condition to check for mobile which is simple), but apparently device-height is deprecated (and also I don't think I can do such a comparison directly between the 2 heights anyway)?

Thanks a lot

Body:
you can use media query:

@media all and (min-height: yourValue ) {
  selector {
    //Code Css
  }
}

read more : https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries


问:
Is the abrupt ending of a process using Control + C a trap or an interrupt?
It seems as though the difference between a trap and an interrupt is clear: a trap is a software-invoked call to the kernel (such as through an exception) and an interrupt is pertinent to the hardware (the disk, I/O and peripheral devices such as the mouse and the keyboard...) (learn more about the difference here).

Knowing this, under what category should pressing Control + C to end a process be classified? Is it a software-invoked call and thus a trap since it can be executed from the Shell, etc. or is it an interrupt since it's a signal that the CPU receives from the keyboard? Or are interrupts wholly outside users' domain, meaning that it's the hardware interacting with the CPU at a level that the user cannot reach?

Thank you!

答:
Control-C is not an interrupt... at least not on the PC (and now MAC) hardware. In other words, the keyboard controller doesn't generate a specific interrupt for the key combination "control" and "C".

The keyboard uses only one interrupt vector which is triggered on a key down and a key up. The keyboard is an extremely slow hardware device. With the key repeat rate set to the fastest, holding down a key generate 33 interrupt per second.

If the designer of the operating system believe that control-C is extremely important, they may include the test "is this the key down for "C" AND is the "control" key triggered a keyboard interrupt some billions machine cycle ago? Then, while still processing the keyboard interrupt, they would generate a trap using a software interrupt instruction.

A better operating system would reduce the processing time of the keyboard interrupt to the strict minimum. They would just append to a circular buffer (ring buffer) the key code which include the bit pressed/released and immediately terminate the interrupt.

The operating system would then, whenever it has time, notice the change in ring buffer pointer. It would trigger the code which extract the key code from the ring buffer, verify if that code represent the "ctrl-C" combination and set a flag saying "ctrl-C" detected.

Finally, when the scheduler is ready to run a thread that belong to the current process, it check the flag "ctrl-C' detected. If it is the case, the scheduler set PC to point to the SIGINT routine instead of resuming to the previous execution address.

No matter the detail, "ctrl-C" can not be an interrupt. It is either a trap if called from the keyboard interrupt or it is a synchronization object tested asynchronously by the scheduler.