问:
Selected Filename not showing in Label from one Form to another C#
I am working modifying an application that will be an utility. The application is designed so far to load pictures from any folder and show them in thumbnails, then the user should be able to select those that will want to save in a database. The thumbnails consists of an ImageViewer form that will load each image. Thus, in the ImageViewer form there is a textbox and a checkbox. Each of them will be generated dynamically as many pictures are loaded (see the image below). The problem is that when clicking the checkbox it should show the name listed above the picture (thumbnail textbox) of the file in a label (it can be a label or textbox). Any time when the user clicks the checkbox will see a message saying: 'Added anyImage.jpg' or when deselecting the checkbox will say 'Removed anyImage.jpg'. It is not showing the text in the label. I have the following code.

This code is to load the main form:

```<code>public MainForm()
{
    InitializeComponent();
    Login loginSystem = new Login();

    lbHowMany.Visible = false;
    lbHowMany.Text = "Images";
    lbNumberOfFiles.Visible = false;

    btnEnableViewer.Text = "Disable Viewer";

    this.buttonCancel.Enabled = false;

    //stripSelectedFile.Text = "";

    m_ImageDialog = new ImageDialog();

    m_AddImageDelegate = new DelegateAddImage(this.AddImage);

    m_Controller = new ThumbnailController();
    m_Controller.OnStart += new ThumbnailControllerEventHandler(m_Controller_OnStart);
    m_Controller.OnAdd += new ThumbnailControllerEventHandler(m_Controller_OnAdd);
    m_Controller.OnEnd += new ThumbnailControllerEventHandler(m_Controller_OnEnd);

    if (ImageViewer.sendSelectedFile != null)
    {
        stripSelectedFile.Text = ImageViewer.sendSelectedFile.ToString();
        txInformation.Text = ImageViewer.sendSelectedFile.ToString();
    }
}
</code>```

This other code is from the ImageViewer form checkbox:

```<code>public void cboxToSave_CheckedChanged(object sender, EventArgs e)
        {

            if (cboxToSave.Checked == true)
            {
                sendSelectedFile = "Added: " + txFileName.Text;

            }
            else
            {
                {
                    sendSelectedFile = "Removed: " + txFileName.Text;
                }
            }
        }
</code>```

This is the variable declared in the class that will send the selected file name to the main form: public static string sendSelectedFile;

ImageViewer Code:

```<code>public partial class ImageViewer : UserControl
    {
        private Image m_Image;
        private string m_ImageLocation;

        private bool m_IsThumbnail;
        private bool m_IsActive;

        public static string sendSelectedFile;
        public ImageViewer()
        {
            m_IsThumbnail = false;
            m_IsActive = false;

            InitializeComponent();

        }

        public Image Image
        {
            set
            {
                m_Image = value;
            }
            get
            {
                return m_Image;
            }
        }

        public string ImageLocation
        {
            set
            {
                m_ImageLocation = value;
            }
            get
            {
                return m_ImageLocation;
            }
        }

        public bool IsActive
        {
            set
            {
                m_IsActive = value;
                this.Invalidate();
            }
            get
            {
                return m_IsActive;
            }
        }

        public bool IsThumbnail
        {
            set
            {
                m_IsThumbnail = value;
            }
            get
            {
                return m_IsThumbnail;
            }
        }
        public void ImageSizeChanged(object sender, ThumbnailImageEventArgs e)
        {
            this.Width = e.Size;
            this.Height = e.Size;
            this.Invalidate();
        }

        public void LoadImage(string imageFilename, int width, int height)
        {
            Image tempImage = Image.FromFile(imageFilename);
            m_ImageLocation = imageFilename;

            //gets the name of the file from the location
            txFileName.Text = Path.GetFileNameWithoutExtension(imageFilename);

            int dw = tempImage.Width;
            int dh = tempImage.Height;
            int tw = width;
            int th = height;
            double zw = (tw / (double)dw);
            double zh = (th / (double)dh);
            double z = (zw <= zh) ? zw : zh;
            dw = (int)(dw * z);
            dh = (int)(dh * z);

            m_Image = new Bitmap(dw, dh);

            Graphics g = Graphics.FromImage(m_Image);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(tempImage, 0, 0, dw, dh);
            g.Dispose();

            tempImage.Dispose();
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            if (g == null) return;
            if (m_Image == null) return;

            int dw = m_Image.Width;
            int dh = m_Image.Height;
            int tw = this.Width - 8; // remove border, 4*4
            int th = this.Height - 8; // remove border, 4*4
            double zw = (tw / (double)dw);
            double zh = (th / (double)dh);
            double z = (zw <= zh) ? zw : zh;

            dw = (int)(dw * z);
            dh = (int)(dh * z);
            int dl = 4 + (tw - dw) / 2; // add border 2*2
            int dt = 4 + (th - dh) / 2; // add border 2*2

            g.DrawRectangle(new Pen(Color.Yellow), dl, dt, dw, dh);

            if (m_IsThumbnail)
                for (int j = 0; j < 3; j++)
                {
                    //draws and color the horizontal line in the miniature
                    g.DrawLine(new Pen(Color.LightSalmon),
                        new Point(dl + 3, dt + dh + 1 + j),
                        new Point(dl + dw + 3, dt + dh + 1 + j));
                    //draws and color the vertical right line in the miniature
                    g.DrawLine(new Pen(Color.LightGreen),
                        new Point(dl + dw + 1 + j, dt + 3),
                        new Point(dl + dw + 1 + j, dt + dh + 3));
                }

            g.DrawImage(m_Image, dl, dt, dw, dh);

            if (m_IsActive)
            {
                //draws the rectangle inside and gives it color
                g.DrawRectangle(new Pen(Color.MediumTurquoise, 1), dl, dt, dw, dh);
                //draws the rectangle outside and gives it color
                g.DrawRectangle(new Pen(Color.RosyBrown, 2), dl - 2, dt - 2, dw + 4, dh + 4);

            }
        }

        private void OnResize(object sender, EventArgs e)
        {
            this.Invalidate();
        }

        public void cboxToSave_CheckedChanged(object sender, EventArgs e)
        {

            if (cboxToSave.Checked == true)
            {
                sendSelectedFile = "Added: " + txFileName.Text;

            }
            else
            {
                {
                    sendSelectedFile = "Removed: " + txFileName.Text;
                }
            }
        }
    }
</code>```

Code in the MainForm that adds the images in the flowLayoutPanelMain

```<code>delegate void DelegateAddImage(string imageFilename);
        private DelegateAddImage m_AddImageDelegate;
        private void AddImage(string imageFilename)
        {
            try
            {
                // thread safe
                if (this.InvokeRequired)
                {
                    this.Invoke(m_AddImageDelegate, imageFilename);
                }
                else
                {
                    int size = ImageSize;
                    lbNumberOfFiles.Visible = true;
                    lbHowMany.Visible = true;

                    ImageViewer imageViewer = new ImageViewer();

                    imageViewer.Dock = DockStyle.Bottom;
                    imageViewer.LoadImage(imageFilename, 256, 256);
                    imageViewer.Width = size;
                    imageViewer.Height = size;
                    imageViewer.IsThumbnail = true;

                    imageViewer.MouseClick += new MouseEventHandler(imageViewer_MouseClick);

                    txInformation.Text = imageFilename;
                    SetProgressBar();
                    counter++;
                    lbHowMany.Text = "Images";
                    lbNumberOfFiles.Text = counter.ToString();

                    this.OnImageSizeChanged += new ThumbnailImageEventHandler(imageViewer.ImageSizeChanged);
                    //passes the pictures to the main picture container
                    this.flowLayoutPanelMain.Controls.Add(imageViewer);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("An error has ocurred. Error: " + e, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
</code>```

答:
Here's a quick example of the ImageViewer Form raising a custom event whenever the checkbox is changed:

```<code>public partial class ImageViewer : Form
{
    public ImageViewer()
    {
        InitializeComponent();
    }

    public delegate void dlgImageChecked(ImageViewer sender, string message);
    public event dlgImageChecked ImageChecked;

    private void cboxToSave_CheckedChanged(object sender, EventArgs e)
    {
        if (ImageChecked != null)
        {
            ImageChecked(this, (cboxToSave.Checked ? "Added: " : "Removed: ") + txFileName.Text);
        }
    }
}
</code>```

Now, when you create instances of ImageViewer, you need to wire up that event...something like:

```<code>// ... in your MainForm class ...

private void button1_Click(object sender, EventArgs e)
{
    // when you create your instances of ImageViewer, wire up their ImageChecked() event:
    ImageViewer iv = new ImageViewer();
    iv.ImageChecked += Iv_ImageChecked;

}

private void Iv_ImageChecked(ImageViewer sender, string message)
{
    ImageViewer iv = (ImageViewer)sender; // if you need to reference it for other reasons ...

    stripSelectedFile.Text = message;
    txInformation.Text = message;
}
</code>```

Your original post didn't show the creation of your ImageViewer instances so you'll need to incorporate the above somehow into your code.

Body:
I am working modifying an application that will be an utility. The application is designed so far to load pictures from any folder and show them in thumbnails, then the user should be able to select those that will want to save in a database. The thumbnails consists of an ImageViewer form that will load each image. Thus, in the ImageViewer form there is a textbox and a checkbox. Each of them will be generated dynamically as many pictures are loaded (see the image below). The problem is that when clicking the checkbox it should show the name listed above the picture (thumbnail textbox) of the file in a label (it can be a label or textbox). Any time when the user clicks the checkbox will see a message saying: 'Added anyImage.jpg' or when deselecting the checkbox will say 'Removed anyImage.jpg'. It is not showing the text in the label. I have the following code.

This code is to load the main form:

public MainForm()
{
    InitializeComponent();
    Login loginSystem = new Login();

    lbHowMany.Visible = false;
    lbHowMany.Text = "Images";
    lbNumberOfFiles.Visible = false;

    btnEnableViewer.Text = "Disable Viewer";

    this.buttonCancel.Enabled = false;

    //stripSelectedFile.Text = "";

    m_ImageDialog = new ImageDialog();

    m_AddImageDelegate = new DelegateAddImage(this.AddImage);

    m_Controller = new ThumbnailController();
    m_Controller.OnStart += new ThumbnailControllerEventHandler(m_Controller_OnStart);
    m_Controller.OnAdd += new ThumbnailControllerEventHandler(m_Controller_OnAdd);
    m_Controller.OnEnd += new ThumbnailControllerEventHandler(m_Controller_OnEnd);

    if (ImageViewer.sendSelectedFile != null)
    {
        stripSelectedFile.Text = ImageViewer.sendSelectedFile.ToString();
        txInformation.Text = ImageViewer.sendSelectedFile.ToString();
    }
}

This other code is from the ImageViewer form checkbox:

public void cboxToSave_CheckedChanged(object sender, EventArgs e)
        {

            if (cboxToSave.Checked == true)
            {
                sendSelectedFile = "Added: " + txFileName.Text;

            }
            else
            {
                {
                    sendSelectedFile = "Removed: " + txFileName.Text;
                }
            }
        }

This is the variable declared in the class that will send the selected file name to the main form: public static string sendSelectedFile;

ImageViewer Code:

public partial class ImageViewer : UserControl
    {
        private Image m_Image;
        private string m_ImageLocation;

        private bool m_IsThumbnail;
        private bool m_IsActive;

        public static string sendSelectedFile;
        public ImageViewer()
        {
            m_IsThumbnail = false;
            m_IsActive = false;

            InitializeComponent();

        }

        public Image Image
        {
            set
            {
                m_Image = value;
            }
            get
            {
                return m_Image;
            }
        }

        public string ImageLocation
        {
            set
            {
                m_ImageLocation = value;
            }
            get
            {
                return m_ImageLocation;
            }
        }

        public bool IsActive
        {
            set
            {
                m_IsActive = value;
                this.Invalidate();
            }
            get
            {
                return m_IsActive;
            }
        }

        public bool IsThumbnail
        {
            set
            {
                m_IsThumbnail = value;
            }
            get
            {
                return m_IsThumbnail;
            }
        }
        public void ImageSizeChanged(object sender, ThumbnailImageEventArgs e)
        {
            this.Width = e.Size;
            this.Height = e.Size;
            this.Invalidate();
        }

        public void LoadImage(string imageFilename, int width, int height)
        {
            Image tempImage = Image.FromFile(imageFilename);
            m_ImageLocation = imageFilename;

            //gets the name of the file from the location
            txFileName.Text = Path.GetFileNameWithoutExtension(imageFilename);

            int dw = tempImage.Width;
            int dh = tempImage.Height;
            int tw = width;
            int th = height;
            double zw = (tw / (double)dw);
            double zh = (th / (double)dh);
            double z = (zw <= zh) ? zw : zh;
            dw = (int)(dw * z);
            dh = (int)(dh * z);

            m_Image = new Bitmap(dw, dh);

            Graphics g = Graphics.FromImage(m_Image);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(tempImage, 0, 0, dw, dh);
            g.Dispose();

            tempImage.Dispose();
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            if (g == null) return;
            if (m_Image == null) return;

            int dw = m_Image.Width;
            int dh = m_Image.Height;
            int tw = this.Width - 8; // remove border, 4*4
            int th = this.Height - 8; // remove border, 4*4
            double zw = (tw / (double)dw);
            double zh = (th / (double)dh);
            double z = (zw <= zh) ? zw : zh;

            dw = (int)(dw * z);
            dh = (int)(dh * z);
            int dl = 4 + (tw - dw) / 2; // add border 2*2
            int dt = 4 + (th - dh) / 2; // add border 2*2

            g.DrawRectangle(new Pen(Color.Yellow), dl, dt, dw, dh);

            if (m_IsThumbnail)
                for (int j = 0; j < 3; j++)
                {
                    //draws and color the horizontal line in the miniature
                    g.DrawLine(new Pen(Color.LightSalmon),
                        new Point(dl + 3, dt + dh + 1 + j),
                        new Point(dl + dw + 3, dt + dh + 1 + j));
                    //draws and color the vertical right line in the miniature
                    g.DrawLine(new Pen(Color.LightGreen),
                        new Point(dl + dw + 1 + j, dt + 3),
                        new Point(dl + dw + 1 + j, dt + dh + 3));
                }

            g.DrawImage(m_Image, dl, dt, dw, dh);

            if (m_IsActive)
            {
                //draws the rectangle inside and gives it color
                g.DrawRectangle(new Pen(Color.MediumTurquoise, 1), dl, dt, dw, dh);
                //draws the rectangle outside and gives it color
                g.DrawRectangle(new Pen(Color.RosyBrown, 2), dl - 2, dt - 2, dw + 4, dh + 4);

            }
        }

        private void OnResize(object sender, EventArgs e)
        {
            this.Invalidate();
        }

        public void cboxToSave_CheckedChanged(object sender, EventArgs e)
        {

            if (cboxToSave.Checked == true)
            {
                sendSelectedFile = "Added: " + txFileName.Text;

            }
            else
            {
                {
                    sendSelectedFile = "Removed: " + txFileName.Text;
                }
            }
        }
    }

Code in the MainForm that adds the images in the flowLayoutPanelMain

delegate void DelegateAddImage(string imageFilename);
        private DelegateAddImage m_AddImageDelegate;
        private void AddImage(string imageFilename)
        {
            try
            {
                // thread safe
                if (this.InvokeRequired)
                {
                    this.Invoke(m_AddImageDelegate, imageFilename);
                }
                else
                {
                    int size = ImageSize;
                    lbNumberOfFiles.Visible = true;
                    lbHowMany.Visible = true;

                    ImageViewer imageViewer = new ImageViewer();

                    imageViewer.Dock = DockStyle.Bottom;
                    imageViewer.LoadImage(imageFilename, 256, 256);
                    imageViewer.Width = size;
                    imageViewer.Height = size;
                    imageViewer.IsThumbnail = true;

                    imageViewer.MouseClick += new MouseEventHandler(imageViewer_MouseClick);

                    txInformation.Text = imageFilename;
                    SetProgressBar();
                    counter++;
                    lbHowMany.Text = "Images";
                    lbNumberOfFiles.Text = counter.ToString();

                    this.OnImageSizeChanged += new ThumbnailImageEventHandler(imageViewer.ImageSizeChanged);
                    //passes the pictures to the main picture container
                    this.flowLayoutPanelMain.Controls.Add(imageViewer);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("An error has ocurred. Error: " + e, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

Body:
Here's a quick example of the ImageViewer Form raising a custom event whenever the checkbox is changed:

public partial class ImageViewer : Form
{
    public ImageViewer()
    {
        InitializeComponent();
    }

    public delegate void dlgImageChecked(ImageViewer sender, string message);
    public event dlgImageChecked ImageChecked;

    private void cboxToSave_CheckedChanged(object sender, EventArgs e)
    {
        if (ImageChecked != null)
        {
            ImageChecked(this, (cboxToSave.Checked ? "Added: " : "Removed: ") + txFileName.Text);
        }
    }
}

Now, when you create instances of ImageViewer, you need to wire up that event...something like:

// ... in your MainForm class ...

private void button1_Click(object sender, EventArgs e)
{
    // when you create your instances of ImageViewer, wire up their ImageChecked() event:
    ImageViewer iv = new ImageViewer();
    iv.ImageChecked += Iv_ImageChecked;

}

private void Iv_ImageChecked(ImageViewer sender, string message)
{
    ImageViewer iv = (ImageViewer)sender; // if you need to reference it for other reasons ...

    stripSelectedFile.Text = message;
    txInformation.Text = message;
}

Your original post didn't show the creation of your ImageViewer instances so you'll need to incorporate the above somehow into your code.


来源: stackexchange

问:
Access diagonal elements in a 2D array stored in a 1D array
Suppose my 2D array is:

```<code>int a[4][4] = {
               1,0,0,0,
               0,1,0,0,
               0,0,1,0,
               0,0,0,1
              };
</code>```

Suppose its stored in a 1D array as:

```<code>int b[16]={1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1};
</code>```

In general, assume a is of size m x n and b is of size mn.
Using a single for loop I want to be able to access all the diagonal elements, i.e output should be 1 1 1 1.

I understand A[i][j] = B[i*n+j]; but if I'm only using a single for loop, I don't have a j index.

Any help would be highly appreciated.

Edit:

Note let m=n be for all practical purposes. The interface I'm using expects two separate variables for row and column size. But I'm only working with square matrices.

答:
It's simple to it for a 2-d array.

```<code>for(int i=0; i<4; i++)
   printf("%d", a[i][i]);
</code>```

And for a single dimension array, it is not difficult either.

```<code>for(int i=0; i<16; i=i+5)
   printf("%d", b[i]);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Suppose my 2D array is:

int a[4][4] = {
               1,0,0,0,
               0,1,0,0,
               0,0,1,0,
               0,0,0,1
              };

Suppose its stored in a 1D array as:

int b[16]={1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1};

In general, assume a is of size m x n and b is of size mn.
Using a single for loop I want to be able to access all the diagonal elements, i.e output should be 1 1 1 1.

I understand A[i][j] = B[i*n+j]; but if I'm only using a single for loop, I don't have a j index.

Any help would be highly appreciated.

Edit:

Note let m=n be for all practical purposes. The interface I'm using expects two separate variables for row and column size. But I'm only working with square matrices.

Body:
It's simple to it for a 2-d array.

for(int i=0; i<4; i++)
   printf("%d", a[i][i]);

And for a single dimension array, it is not difficult either.

for(int i=0; i<16; i=i+5)
   printf("%d", b[i]);


问:
Subject for sending email
I'm working on service for sending email to customers.
All settings like host, protocol etc, and also email sender or subject I have stored in application.properties.

In another place I have class:

```<code>@ConfigurationProperties(prefix = "email.properties")
public class EmailProperties {

private String sender;
private String subject;
</code>```

and data from application.properties are copy to this class, and this works very well...

But what is my problem.
I would like set subject e.g:

```<code>email.properties.subject=Hello CUSTOMER, thank you for registered.
</code>```

and bind CUSTOMER for concrete customer name when i send email, like:

```<code>Hello Tom Rich, thank you for registered.
</code>```

So I added to class EmailProperties method:

```<code>String getSubjectWithCustomer(User user){
...}
</code>```

but I have no idea how can i bind CUSTOMER for concrete user. Probably i can do something like this:

```<code>String getSubjectWithCustomer(User user){
  return subject.replaceAll("CUSTOMER", user.getUserName());
}
</code>```

but i feel this is stupid solution. I would like use something better. Maybe do you have some idea? Maybe i can use SpEL for this? But i have no idea how, because everywhere i found only examples how binding XML files but not aplication.properties.

Maybe i can create some parser with using SpEL?

Regards.

答:
You could use Spring MessageSource where you can define parametrized and localized messages.

Something like:

```<code>public String getLocalizedSubject(Object[] params) {
    return getLocalizedSubject(params, Locale.getDefault());
}

public String getLocalizedSubject(Object[] params, Locale locale) {
    return messageSource.getMessage("subject", params, locale);
}
</code>```

Using:

```<code>Object[] params = new Object[] { user.getUserName() };
getLocalizedSubject(params);
</code>```

And define subject in the messages.properties

```<code>subject=Hello {0}, thank you for register.
</code>```

Title: Subject for sending email

Body:
I'm working on service for sending email to customers.
All settings like host, protocol etc, and also email sender or subject I have stored in application.properties.

In another place I have class:

@ConfigurationProperties(prefix = "email.properties")
public class EmailProperties {

private String sender;
private String subject;

and data from application.properties are copy to this class, and this works very well...

But what is my problem.
I would like set subject e.g:

email.properties.subject=Hello CUSTOMER, thank you for registered.

and bind CUSTOMER for concrete customer name when i send email, like:

Hello Tom Rich, thank you for registered.

So I added to class EmailProperties method:

String getSubjectWithCustomer(User user){
...}

but I have no idea how can i bind CUSTOMER for concrete user. Probably i can do something like this:

String getSubjectWithCustomer(User user){
  return subject.replaceAll("CUSTOMER", user.getUserName());
}

but i feel this is stupid solution. I would like use something better. Maybe do you have some idea? Maybe i can use SpEL for this? But i have no idea how, because everywhere i found only examples how binding XML files but not aplication.properties.

Maybe i can create some parser with using SpEL?

Regards.

Body:
You could use Spring MessageSource where you can define parametrized and localized messages.

Something like:

public String getLocalizedSubject(Object[] params) {
    return getLocalizedSubject(params, Locale.getDefault());
}

public String getLocalizedSubject(Object[] params, Locale locale) {
    return messageSource.getMessage("subject", params, locale);
}

Using:

Object[] params = new Object[] { user.getUserName() };
getLocalizedSubject(params);

And define subject in the messages.properties

subject=Hello {0}, thank you for register.


问:
How to set alias for request parameters in Spring-mvc?
When having a bean object for request params in spring: is there a way to define an alias for a bean properties?

```<code>@RestController
public class MyServlet {
   @GetMapping
   public void test(MyReq req) {
   }
}

public class MyReq {
   @RequestParam("different-name") //this is invalid
   private String name;
   private int age;
}
</code>```

Of course @RequestParam does not work, but is there a similar annotation I could use?

答:
You can use setters for that. Given your example:

```<code>@SpringBootApplication
public class So44390404Application {

    public static void main(String[] args) {
        SpringApplication.run(So44390404Application.class, args);
    }

    @RestController
    public static class MyServlet {
        @GetMapping
        public String test(MyReq req) {
            return req.toString();
        }
    }

    public static class MyReq {
        private String name;
        private int age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public void setDifferent_Name(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "{" + name + age + '}';
        }
    }
}
</code>```

And caller might use:

```<code>$so44390404 curl -XGET 'http://localhost:8000?name=adam&age=42'
{adam42}%
$so44390404 curl -XGET 'http://localhost:8000?Different_Name=John&age=23'
{John23}%
</code>```

Update

Well, if you're dealing with hyphen-named parameters things become a little bit trickier.

Basically you can:

Make a filter which will normalize hyphened parameter names, so spring can bind them successfully.

Receive all request params as a raw map in your controller, normalize keys and then populate object with all type conversion stuff by yourself.

An option with filter might look like this:

```<code>@Component
public static class CustomRequestParametersFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {
        filterChain.doFilter(new RequestParameterNormalizerWrapper(request), response);
    }

    public static class RequestParameterNormalizerWrapper extends HttpServletRequestWrapper {
        public static final String HYPHEN = "-";
        private final Map<String, String[]> parameterMap = new HashMap<>();

        public RequestParameterNormalizerWrapper(HttpServletRequest request) {
            super(request);

            for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
                if (entry.getKey().contains(HYPHEN)) {
                    parameterMap.put(normalize(entry.getKey()), entry.getValue());
                }
                else {
                    parameterMap.put(entry.getKey(), entry.getValue());
                }
            }
        }

        private String normalize(final String key) {
            if (key.contains(HYPHEN)) {
                return WordUtils.capitalizeFully(key, HYPHEN.charAt(0)).replaceAll(HYPHEN, "");
            }
            return key;
        }

        @Override
        public Map<String, String[]> getParameterMap() {
            return Collections.unmodifiableMap(this.parameterMap);
        }

        @Override
        public Enumeration<String> getParameterNames() {
            return Collections.enumeration(this.parameterMap.keySet());
        }

        @Override
        public String getParameter(String name) {
            return super.getParameter(normalize(name));
        }

        @Override
        public String[] getParameterValues(String name) {
            return parameterMap.get(normalize(name));
        }
    }
}
</code>```

With that previous example should work as is.

The second option might be:

```<code>@RestController
public static class MyServlet {

    @GetMapping
    public String test(@RequestParam Map<String, String> pvs) {
        final MyReq req = new MyReq();
        final BeanWrapper beanWrapper = new HyphenAwareBeanWrapper(req);
        beanWrapper.setPropertyValues(pvs);
        return req.toString();
    }
}
</code>```

And the wrapper:

```<code>public static class HyphenAwareBeanWrapper extends BeanWrapperImpl {
    public static final String HYPHEN = "-";

    public HyphenAwareBeanWrapper(Object object) {
        super(object);
    }

    @Override
    public void setPropertyValues(Map<?, ?> map) throws BeansException {
        final ArrayList<PropertyValue> propertyValueList = new ArrayList<>(map.size());
        for (Map.Entry<?, ?> entry : map.entrySet()) {
            final String key = entry.getKey().toString().contains(HYPHEN)
                    ? WordUtils.capitalizeFully(entry.getKey().toString(), HYPHEN.charAt(0)).replaceAll(HYPHEN, "")
                    : entry.getKey().toString();
            propertyValueList.add(new PropertyValue(key, entry.getValue()));
        }
        super.setPropertyValues(new MutablePropertyValues(propertyValueList));
    }
}
</code>```

Testing:

```<code>$ curl -XGET 'http://localhost:8000?name=John&age=42'
{John42}%
$ curl -XGET 'http://localhost:8000?different-name=John&age=42'
{John42}%
</code>```

Body:
When having a bean object for request params in spring: is there a way to define an alias for a bean properties?

@RestController
public class MyServlet {
   @GetMapping
   public void test(MyReq req) {
   }
}

public class MyReq {
   @RequestParam("different-name") //this is invalid
   private String name;
   private int age;
}

Of course @RequestParam does not work, but is there a similar annotation I could use?

Body:
You can use setters for that. Given your example:

@SpringBootApplication
public class So44390404Application {

    public static void main(String[] args) {
        SpringApplication.run(So44390404Application.class, args);
    }

    @RestController
    public static class MyServlet {
        @GetMapping
        public String test(MyReq req) {
            return req.toString();
        }
    }

    public static class MyReq {
        private String name;
        private int age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public void setDifferent_Name(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "{" + name + age + '}';
        }
    }
}

And caller might use:

$so44390404 curl -XGET 'http://localhost:8000?name=adam&age=42'
{adam42}%
$so44390404 curl -XGET 'http://localhost:8000?Different_Name=John&age=23'
{John23}%

Update

Well, if you're dealing with hyphen-named parameters things become a little bit trickier.

Basically you can:

Make a filter which will normalize hyphened parameter names, so spring can bind them successfully.

Receive all request params as a raw map in your controller, normalize keys and then populate object with all type conversion stuff by yourself.

An option with filter might look like this:

@Component
public static class CustomRequestParametersFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {
        filterChain.doFilter(new RequestParameterNormalizerWrapper(request), response);
    }

    public static class RequestParameterNormalizerWrapper extends HttpServletRequestWrapper {
        public static final String HYPHEN = "-";
        private final Map<String, String[]> parameterMap = new HashMap<>();

        public RequestParameterNormalizerWrapper(HttpServletRequest request) {
            super(request);

            for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
                if (entry.getKey().contains(HYPHEN)) {
                    parameterMap.put(normalize(entry.getKey()), entry.getValue());
                }
                else {
                    parameterMap.put(entry.getKey(), entry.getValue());
                }
            }
        }

        private String normalize(final String key) {
            if (key.contains(HYPHEN)) {
                return WordUtils.capitalizeFully(key, HYPHEN.charAt(0)).replaceAll(HYPHEN, "");
            }
            return key;
        }

        @Override
        public Map<String, String[]> getParameterMap() {
            return Collections.unmodifiableMap(this.parameterMap);
        }

        @Override
        public Enumeration<String> getParameterNames() {
            return Collections.enumeration(this.parameterMap.keySet());
        }

        @Override
        public String getParameter(String name) {
            return super.getParameter(normalize(name));
        }

        @Override
        public String[] getParameterValues(String name) {
            return parameterMap.get(normalize(name));
        }
    }
}

With that previous example should work as is.

The second option might be:

@RestController
public static class MyServlet {

    @GetMapping
    public String test(@RequestParam Map<String, String> pvs) {
        final MyReq req = new MyReq();
        final BeanWrapper beanWrapper = new HyphenAwareBeanWrapper(req);
        beanWrapper.setPropertyValues(pvs);
        return req.toString();
    }
}

And the wrapper:

public static class HyphenAwareBeanWrapper extends BeanWrapperImpl {
    public static final String HYPHEN = "-";

    public HyphenAwareBeanWrapper(Object object) {
        super(object);
    }

    @Override
    public void setPropertyValues(Map<?, ?> map) throws BeansException {
        final ArrayList<PropertyValue> propertyValueList = new ArrayList<>(map.size());
        for (Map.Entry<?, ?> entry : map.entrySet()) {
            final String key = entry.getKey().toString().contains(HYPHEN)
                    ? WordUtils.capitalizeFully(entry.getKey().toString(), HYPHEN.charAt(0)).replaceAll(HYPHEN, "")
                    : entry.getKey().toString();
            propertyValueList.add(new PropertyValue(key, entry.getValue()));
        }
        super.setPropertyValues(new MutablePropertyValues(propertyValueList));
    }
}

Testing:

$ curl -XGET 'http://localhost:8000?name=John&age=42'
{John42}%
$ curl -XGET 'http://localhost:8000?different-name=John&age=42'
{John42}%


问:
Importing an ipynb file from another ipynb file?
Interactive Python (ipython) is simply amazing, especially as you are piecing things together on the fly... and does it in such a way that it is easy to go back.

However, what seems to be interesting is the use-case of having multiple ipython notebooks (ipynb files).  It apparently seems like a notebook is NOT supposed to have a relationship with other notebooks, which makes sense, except that I would love to import other ipynb files.

The only workaround I see is converting my *.ipynb files into *.py files, which then can be imported into my notebook.  Having one file hold everything in a project is a bit weird, especially if I want to really push for code-reuse (isn't that a core tenet of python?).

Am I missing something? Is this not a supported use case of ipython notebooks? Is there another solution I can be using for this import of an ipynb file into another notebook? I'd love to continue to use ipynb, but it's really messing up my workflow right now :(

答:
Please make sure that you also add a __init__.py file in the package where all your other .ipynb files are located.

This is in addition to the nbviewer link that minrk and syi provided above.

I also had some similar problem and then I wrote the solution as well as a link to my public google drive folder which has a working example :)

My Stackoverflow post with step by step experimentation and Solution:

Jupyter Notebook: Import .ipynb file and access it's method in other .ipynb file giving error

Hope this will help others as well.
Thanks all!

ContentLicense: CC BY-SA 4.0


答:
If you know your 2D array is a perfect square (i.e. exactly as many rows as columns), you don't need a j index:

As a 2D array:

```<code>for(i = 0; i < height; i++)
{
    printf("%d\n", array[i][i];
}
</code>```

As a 1D array:

```<code>for(i = 0; i < height; i++)
{
    printf("%d\n", array[i*height+i]);
}
</code>```

Title: Access diagonal elements in a 2D array stored in a 1D array

Body:
If you know your 2D array is a perfect square (i.e. exactly as many rows as columns), you don't need a j index:

As a 2D array:

for(i = 0; i < height; i++)
{
    printf("%d\n", array[i][i];
}

As a 1D array:

for(i = 0; i < height; i++)
{
    printf("%d\n", array[i*height+i]);
}


问:
unable to get the visible property of the pivotitem class
I have two sets of code. For some reason, in the first one I get an error, and in the second one I don't.

1:

```<code>Dim pi As PivotItem
Dim pf As PivotField

Set pf = Sheets("Afname per school").PivotTables("Draaitabel3").PivotFields("school")

For Each pi In pf.PivotItems
    If pi = "(leeg)" Then
        pi.Visible = False
    Else
        pi.Visible = True 'ERROR HERE
    End If
Next pi
</code>```

2:

```<code>Dim pi As PivotItem
Dim pf As PivotField

Set pf = Sheets("Afname per school").PivotTables("Draaitabel3").PivotFields("naam locatie")

For Each pi In pf.PivotItems
    If InStr(pi, "BSO") Then
        pi.Visible = True
    Else
        pi.Visible = False
    End If
Next pi
</code>```

I get the error: "unable to get the visible property of the pivotitem class"

I read I should solve this the following:

This is due to the Pivot table using the cached pivot items instead of
  the current one. Make sure the table does not retain any old items. To
  do so, right click on your pivot table, click on Data tab and set
  "Number of itesm to retain per field" to "None". The code to do so in
  VBA is:

Dim pt As PivotTable

pt.PivotCache.MissingItemsLimit = xlMissingItemsNone

I tried to add this line of code in two ways:

```<code>Dim pi As PivotItem
Dim pf As PivotField

Set pf = Sheets("Afname per school").PivotTables("Draaitabel3").PivotFields("school")

pt.PivotCache.MissingItemsLimit = xlMissingItemsNone  '1st TRY

For Each pi In pf.PivotItems
    pt.PivotCache.MissingItemsLimit = xlMissingItemsNone   '2nd TRY
    If pi = "(leeg)" Then
        pi.Visible = False
    Else
        pi.Visible = True
    End If
Next pi
</code>```

This doesn't seem to solve my problem.

答:
You may need to set a true at very beginning, for instance

```<code>.PivotItems(1) = true
</code>```

Then you can use a condition loop to set this item to which it should be.

Body:
I have two sets of code. For some reason, in the first one I get an error, and in the second one I don't.

1:

Dim pi As PivotItem
Dim pf As PivotField

Set pf = Sheets("Afname per school").PivotTables("Draaitabel3").PivotFields("school")

For Each pi In pf.PivotItems
    If pi = "(leeg)" Then
        pi.Visible = False
    Else
        pi.Visible = True 'ERROR HERE
    End If
Next pi

2:

Dim pi As PivotItem
Dim pf As PivotField

Set pf = Sheets("Afname per school").PivotTables("Draaitabel3").PivotFields("naam locatie")

For Each pi In pf.PivotItems
    If InStr(pi, "BSO") Then
        pi.Visible = True
    Else
        pi.Visible = False
    End If
Next pi

I get the error: "unable to get the visible property of the pivotitem class"

I read I should solve this the following:

This is due to the Pivot table using the cached pivot items instead of
  the current one. Make sure the table does not retain any old items. To
  do so, right click on your pivot table, click on Data tab and set
  "Number of itesm to retain per field" to "None". The code to do so in
  VBA is:

Dim pt As PivotTable

pt.PivotCache.MissingItemsLimit = xlMissingItemsNone

I tried to add this line of code in two ways:

Dim pi As PivotItem
Dim pf As PivotField

Set pf = Sheets("Afname per school").PivotTables("Draaitabel3").PivotFields("school")

pt.PivotCache.MissingItemsLimit = xlMissingItemsNone  '1st TRY

For Each pi In pf.PivotItems
    pt.PivotCache.MissingItemsLimit = xlMissingItemsNone   '2nd TRY
    If pi = "(leeg)" Then
        pi.Visible = False
    Else
        pi.Visible = True
    End If
Next pi

This doesn't seem to solve my problem.

Body:
You may need to set a true at very beginning, for instance

.PivotItems(1) = true

Then you can use a condition loop to set this item to which it should be.


问:
Pull specific tag in Jenkins pipeline SCM
I am trying to pull a specific tag from two different repos in my Jenkinsfile. The tags are determined by getting the latest successful builds from the relevant pipeline and using these values to decide which tag to checkout. However I am getting issues as SCM is not replacing the withEnv variables I have added. In the code below you can see I am echoing out what should be the tag (and this echo works fine) but when it comes to SCM checking out the tag LAST_SUCCESSFUL_EXTENSIONS_REPO_BUILD and LAST_SUCCESSFUL_SHARED_REPO_BUILD variables are no substituted with their values

```<code>node {

    stage('Checkout') {
        withEnv([
            "LAST_SUCCESSFUL_EXTENSIONS_REPO_BUILD=${ sh ( script: "curl <JENKINS_URL>/job/extensionsrepo/job/${BRANCH_NAME}/lastSuccessfulBuild/buildNumber", returnStdout: true ) }",
            "LAST_SUCCESSFUL_SHARED_REPO_BUILD=${ sh ( script: "curl <JENKINS_URL>/job/sharedrepo/job/${BRANCH_NAME}/lastSuccessfulBuild/buildNumber", returnStdout: true ) }"
        ]) {
            sh 'echo ${BRANCH_NAME}_${LAST_SUCCESSFUL_EXTENSIONS_REPO_BUILD}'
            sh 'echo ${BRANCH_NAME}_${LAST_SUCCESSFUL_SHARED_REPO_BUILD}'
            checkout scm
            checkout([
                $class: 'GitSCM',
                branches: [[name: 'refs/tags/${BRANCH_NAME}_${LAST_SUCCESSFUL_EXTENSIONS_REPO_BUILD}']],
                doGenerateSubmoduleConfigurations: false,
                extensions: [[
                    $class: 'RelativeTargetDirectory',
                    relativeTargetDir: 'app/extensions'
                ]],
                submoduleCfg: [],
                userRemoteConfigs: [[
                    credentialsId: 'ssh-key',
                    url: '<GIT_URL>'
                ]]
            ])
            checkout([
                $class: 'GitSCM',
                branches: [[name: 'refs/tags/${BRANCH_NAME}_${LAST_SUCCESSFUL_SHARED_REPO_BUILD}']],
                doGenerateSubmoduleConfigurations: false,
                extensions: [[
                    $class: 'RelativeTargetDirectory',
                    relativeTargetDir: 'app/shared'
                ]],
                submoduleCfg: [],
                userRemoteConfigs: [[
                    credentialsId: 'ssh-key',
                    url: '<GIT_URL>'
                ]]
            ])
        }
    }

    // test, stage, deploy
}
</code>```

Any pointers on what I am doing wrong here would be much appreciated. No doubt it is something stupid that I am failing to do correctly.

Thanks

答:
Try replacing the single quotes in your checkout call where you have the branch var with double quotes. In general, in Groovy you should use double quotes when including embedded variables (see What's the difference of strings within single or double quotes in groovy?).

Like:

```<code>checkout([
            $class: 'GitSCM',
            branches: [[name: "refs/tags/${BRANCH_NAME}_${LAST_SUCCESSFUL_EXTENSIONS_REPO_BUILD}"]],
            doGenerateSubmoduleConfigurations: false,
            extensions: [[
                $class: 'RelativeTargetDirectory',
                relativeTargetDir: 'app/extensions'
            ]],
            submoduleCfg: [],
            userRemoteConfigs: [[
                credentialsId: 'ssh-key',
                url: '<GIT_URL>'
            ]]
        ])
</code>```

Body:
I am trying to pull a specific tag from two different repos in my Jenkinsfile. The tags are determined by getting the latest successful builds from the relevant pipeline and using these values to decide which tag to checkout. However I am getting issues as SCM is not replacing the withEnv variables I have added. In the code below you can see I am echoing out what should be the tag (and this echo works fine) but when it comes to SCM checking out the tag LAST_SUCCESSFUL_EXTENSIONS_REPO_BUILD and LAST_SUCCESSFUL_SHARED_REPO_BUILD variables are no substituted with their values

node {

    stage('Checkout') {
        withEnv([
            "LAST_SUCCESSFUL_EXTENSIONS_REPO_BUILD=${ sh ( script: "curl <JENKINS_URL>/job/extensionsrepo/job/${BRANCH_NAME}/lastSuccessfulBuild/buildNumber", returnStdout: true ) }",
            "LAST_SUCCESSFUL_SHARED_REPO_BUILD=${ sh ( script: "curl <JENKINS_URL>/job/sharedrepo/job/${BRANCH_NAME}/lastSuccessfulBuild/buildNumber", returnStdout: true ) }"
        ]) {
            sh 'echo ${BRANCH_NAME}_${LAST_SUCCESSFUL_EXTENSIONS_REPO_BUILD}'
            sh 'echo ${BRANCH_NAME}_${LAST_SUCCESSFUL_SHARED_REPO_BUILD}'
            checkout scm
            checkout([
                $class: 'GitSCM',
                branches: [[name: 'refs/tags/${BRANCH_NAME}_${LAST_SUCCESSFUL_EXTENSIONS_REPO_BUILD}']],
                doGenerateSubmoduleConfigurations: false,
                extensions: [[
                    $class: 'RelativeTargetDirectory',
                    relativeTargetDir: 'app/extensions'
                ]],
                submoduleCfg: [],
                userRemoteConfigs: [[
                    credentialsId: 'ssh-key',
                    url: '<GIT_URL>'
                ]]
            ])
            checkout([
                $class: 'GitSCM',
                branches: [[name: 'refs/tags/${BRANCH_NAME}_${LAST_SUCCESSFUL_SHARED_REPO_BUILD}']],
                doGenerateSubmoduleConfigurations: false,
                extensions: [[
                    $class: 'RelativeTargetDirectory',
                    relativeTargetDir: 'app/shared'
                ]],
                submoduleCfg: [],
                userRemoteConfigs: [[
                    credentialsId: 'ssh-key',
                    url: '<GIT_URL>'
                ]]
            ])
        }
    }

    // test, stage, deploy
}

Any pointers on what I am doing wrong here would be much appreciated. No doubt it is something stupid that I am failing to do correctly.

Thanks

Body:
Try replacing the single quotes in your checkout call where you have the branch var with double quotes. In general, in Groovy you should use double quotes when including embedded variables (see What's the difference of strings within single or double quotes in groovy?).

Like:

checkout([
            $class: 'GitSCM',
            branches: [[name: "refs/tags/${BRANCH_NAME}_${LAST_SUCCESSFUL_EXTENSIONS_REPO_BUILD}"]],
            doGenerateSubmoduleConfigurations: false,
            extensions: [[
                $class: 'RelativeTargetDirectory',
                relativeTargetDir: 'app/extensions'
            ]],
            submoduleCfg: [],
            userRemoteConfigs: [[
                credentialsId: 'ssh-key',
                url: '<GIT_URL>'
            ]]
        ])


问:
Using an ID array to perform a single db query
I'm trying to perform a single query to the db, in which I am using an array of IDs to insert in the WHERE clause. So far I've had mixed results, and this is the closest I've gotten to achieve what I am looking for.

```<code>$prodId = array(17754, 17755, 17756);
$ids = implode(",",$prodId);

$qry = "SELECT clean_url AS url FROM xcart_clean_urls WHERE resource_id IN ($ids) ";
$resultTst = db_query($qry);

while ($result_row = db_fetch_array($resultTst)) {
   $urls[] = $result_row;
   if ( $urls ) {
      echo $urls[0]['url'] . '<br>';
      echo $urls[1]['url'] . '<br>';
      echo $urls[2]['url'] . '<br>';
   }
}
</code>```

THE RESULTS I GET (I get the actual urls):

urlforid17754

urlforid17754

urlforid17755

urlforid17754

urlforid17755

urlforid17756

How can I perform the same functionality, but only retrieve the 3 urls once?

Thank you all.

答:
You are trying to echo 3 rows each time through the loop. Move them out of the loop or just echo $result_row. If you don't need the echo then just use $urls after the loop.  The URL seems to be in the url column so echo that:

```<code>while ($result_row = db_fetch_array($resultTst)) {
   echo $result_row['url'];
   $urls[] = $result_row;
}

//to see what $urls contains
print_r($urls);
</code>```

I don't know what you want $urls to contain, but if you only want a single dimension then use this inside the loop instead:

```<code>   $urls[] = $result_row['url'];
</code>```

Body:
I'm trying to perform a single query to the db, in which I am using an array of IDs to insert in the WHERE clause. So far I've had mixed results, and this is the closest I've gotten to achieve what I am looking for.

$prodId = array(17754, 17755, 17756);
$ids = implode(",",$prodId);

$qry = "SELECT clean_url AS url FROM xcart_clean_urls WHERE resource_id IN ($ids) ";
$resultTst = db_query($qry);

while ($result_row = db_fetch_array($resultTst)) {
   $urls[] = $result_row;
   if ( $urls ) {
      echo $urls[0]['url'] . '
';
      echo $urls[1]['url'] . '
';
      echo $urls[2]['url'] . '
';
   }
}

THE RESULTS I GET (I get the actual urls):

urlforid17754

urlforid17754

urlforid17755

urlforid17754

urlforid17755

urlforid17756

How can I perform the same functionality, but only retrieve the 3 urls once?

Thank you all.

Body:
You are trying to echo 3 rows each time through the loop. Move them out of the loop or just echo $result_row. If you don't need the echo then just use $urls after the loop.  The URL seems to be in the url column so echo that:

while ($result_row = db_fetch_array($resultTst)) {
   echo $result_row['url'];
   $urls[] = $result_row;
}

//to see what $urls contains
print_r($urls);

I don't know what you want $urls to contain, but if you only want a single dimension then use this inside the loop instead:

   $urls[] = $result_row['url'];


问:
How to add line breaks to prevent overly long lines?
I just read the best practices of Python scripts. I found recommended length should not exceed 80 characters per line.

So in my script more than  100 characters are exist.

I have break the lines and below are examples.

Example 1

```<code>self.remote_conn_pre.connect("self.hostname, "
    "username=self.username, password=self.password, "
     "look_for_keys=False, allow_agent=False")
</code>```

Example 2

```<code> self.remote_conn.send(""create bigdata\n" "
    " .format(pending.upper(), (total) + 9)")
</code>```

Example 3

```<code> print ("This is the first line of my text {} "
 "which will be joined to a second {}.".format(a,b))
</code>```

Could any one please correct me if I am doing anything wrong and help me determine the best ways to break long lines into small lines.

答:
You can use docstrings and escape the newline character.</p>

```<code>print ("""
This is the first line of my text {} \
which will be joined to a second {}.
""").format(a,b)
</code>```

Body:
I just read the best practices of Python scripts. I found recommended length should not exceed 80 characters per line.

So in my script more than  100 characters are exist.

I have break the lines and below are examples.

Example 1

self.remote_conn_pre.connect("self.hostname, "
    "username=self.username, password=self.password, "
     "look_for_keys=False, allow_agent=False")

Example 2

 self.remote_conn.send(""create bigdata\n" "
    " .format(pending.upper(), (total) + 9)")

Example 3

 print ("This is the first line of my text {} "
 "which will be joined to a second {}.".format(a,b))

Could any one please correct me if I am doing anything wrong and help me determine the best ways to break long lines into small lines.

Body:
You can use docstrings and escape the newline character.

print ("""
This is the first line of my text {} \
which will be joined to a second {}.
""").format(a,b)


问:
knitr: Is there a way to make multiple output of R plotting into each slide?
Suppose I have a R chuck such like:

```<code>\documentclass[xcolor=x11names,compress]{beamer}
    \begin{frame}[fragile]{Visualization}
        <<echo=FALSE, results="asis", fig.keep="all", tidy=TRUE>>=
        library(knitr)
        for (i in 1:100){
            plot(rnorm(100))
        }
        @
   \end{frame}
\end{document}
</code>```

My question is how to make the 100 plots displayed in each following slide rather than keeping in one slide?

答:
Beamer can split slides if you give the "allowframebreaks" option.  There seem to be some limits to how many pages, but this works:</p>

```<code>\documentclass[xcolor=x11names,compress]{beamer}
\begin{document}
\begin{frame}[allowframebreaks]{Visualization}
<<echo=FALSE, fig.height=4>>=
for (i in 1:10){
    plot(rnorm(100))
}
@
\end{frame}
\end{document}
</code>```

Body:
Suppose I have a R chuck such like:

\documentclass[xcolor=x11names,compress]{beamer}
    \begin{frame}[fragile]{Visualization}
        <<echo=FALSE, results="asis", fig.keep="all", tidy=TRUE>>=
        library(knitr)
        for (i in 1:100){
            plot(rnorm(100))
        }
        @
   \end{frame}
\end{document}

My question is how to make the 100 plots displayed in each following slide rather than keeping in one slide?

Body:
Beamer can split slides if you give the "allowframebreaks" option.  There seem to be some limits to how many pages, but this works:

\documentclass[xcolor=x11names,compress]{beamer}
\begin{document}
\begin{frame}[allowframebreaks]{Visualization}
<<echo=FALSE, fig.height=4>>=
for (i in 1:10){
    plot(rnorm(100))
}
@
\end{frame}
\end{document}


问:
Speeding up solving equation with symbolic expression
I am trying to solve an equation using a symbolic (syms) expression, then evaluating it expression using eval. The program is working fine, but it takes a long time. I know using syms decreases the speed, is there any way that I can speed up the process? I was wondering about using a function to put the symbolic expression inside it then calling this function. I do not know if that would help or how to do it though. Any other suggestions are very appreciated.

I used the below code

```<code>clear;
clc;
syms A B C D E ;
R=((4*B*A)/((D-C)^2+(B+A)^2));
R1=((4*B*A)/((D+C)^2+(B+A)^2));
F1 = ellipticK(R);
I1 = ellipticE(R);
F2 = ellipticK(R1);
I2 = ellipticE(R1);
P= ((((A*B)^(1/2))/(2*E*(R^(1/2))))*(((2 - R)*F1) -...
    (2*I1)))-(((((A*B)^(1/2))/(2*E*(R1^(1/2)))))* ...
    (((2 - R1)*F2) - (2*I2)));
P1=feval(symengine,'simplify',P,'IgnoreAnalyticConstraints');

X=(1/B)*(diff(P1,D));
X1=feval(symengine,'simplify',X,'IgnoreAnalyticConstraints');
M(:)=0;
for i=1:10000
    A=L1(i);B=L2(i);C=L3(i);D=L4(i);E=L5(i);
    M(i) = (eval(X1))*0.13;
end
</code>```

答:
You can transform your problem first to a function handle using matlabFunction as follows:

```<code>F = matlabFunction(X1);
M = F(L1, L2, L3, L4, L5)*0.13;
</code>```

This makes your code ~100x faster.

Note that you can also export your function to a script file, using the 'File' argument:

```<code>matlabFunction(f,'File','myFunction.m')
</code>```

Body:
I am trying to solve an equation using a symbolic (syms) expression, then evaluating it expression using eval. The program is working fine, but it takes a long time. I know using syms decreases the speed, is there any way that I can speed up the process? I was wondering about using a function to put the symbolic expression inside it then calling this function. I do not know if that would help or how to do it though. Any other suggestions are very appreciated.

I used the below code

clear;
clc;
syms A B C D E ;
R=((4*B*A)/((D-C)^2+(B+A)^2));
R1=((4*B*A)/((D+C)^2+(B+A)^2));
F1 = ellipticK(R);
I1 = ellipticE(R);
F2 = ellipticK(R1);
I2 = ellipticE(R1);
P= ((((A*B)^(1/2))/(2*E*(R^(1/2))))*(((2 - R)*F1) -...
    (2*I1)))-(((((A*B)^(1/2))/(2*E*(R1^(1/2)))))* ...
    (((2 - R1)*F2) - (2*I2)));
P1=feval(symengine,'simplify',P,'IgnoreAnalyticConstraints');

X=(1/B)*(diff(P1,D));
X1=feval(symengine,'simplify',X,'IgnoreAnalyticConstraints');
M(:)=0;
for i=1:10000
    A=L1(i);B=L2(i);C=L3(i);D=L4(i);E=L5(i);
    M(i) = (eval(X1))*0.13;
end

Body:
You can transform your problem first to a function handle using matlabFunction as follows:

F = matlabFunction(X1);
M = F(L1, L2, L3, L4, L5)*0.13;

This makes your code ~100x faster.

Note that you can also export your function to a script file, using the 'File' argument:

matlabFunction(f,'File','myFunction.m')


问:
assign with $ R
I have several vector describing a trip, in each of them there are indications of latitude and longitude.

The code I am trying to write is the following

```<code>for (i in 1:ntrips){
 for (k in 1:dim(get(paste0("trip",i)))[1]){

 assign(paste0("trip", i)$distance[k],gcd.hf(get(paste0("trip", i))$long.start[k],get(paste0("trip",i))$lat.start[k],get(paste0("trip",i))$end.start[k],get(paste0("trip", i))$lat.end[k]))

 }
}
</code>```

Basically for each vector (trip1, trip2, ...), I want to calculate the value of the distance with the function gcd.hf (defined previously) and paste it in the column named distance.

the error I get is

```<code>Error: $ operator is invalid for atomic vectors
</code>```

Is there anything I am missing?

答:
The very first part of assign is not legitimate

```<code> paste0("trip", i)$distance[k]
</code>```

Try using legitimate names for your variables. E.g.
inside the loop

```<code>ma_trip<-get(paste0("trip",i))
assign(paste0("trip", i,"_distance",ma_trip$distance[k]),...)
</code>```

ADDITION

So let's begin from scratch:

Create the trips along with the coordinates:

```<code>fac<-100
N<-3#number of trips
for(i in 1:N){#create N data.tables
  for(j in round(max(runif(3)*10),0)){#with random number of rows
    #the coordinates are generated
    long.start<-fac*runif(j)
    long.end<-fac*runif(j)
    lat.start<-fac*runif(j)
    lat.end<-fac*runif(j)
  }
assign(paste0("trip",i),data.table(long.start,long.end,lat.start,lat.end))#and are attributed to the data.table
}
</code>```

Each data.table has the following form:

```<code> >trip1

    long.start long.end lat.start  lat.end
 1:   89.18974 98.44804  34.68381 62.55508
 2:   55.95637 95.27552  23.33369 75.74160
 3:   59.32357 73.49386  12.62365 50.18466
 4:   81.72157 20.00639  40.20866 93.14260
 5:   18.08152 52.52404  88.42411 19.10752
 6:   54.50308 91.24726  27.19433 80.65325
 7:   73.17393 19.83704  60.40830 23.68220
 8:   77.57680 87.32211  76.25292 12.22423
 9:   93.60303 55.62256  95.20154 32.75852
</code>```

The dimension of the tripN objects can be given by

```<code> >lapply(lapply(ls(pattern = "^trip"),get),dim)
[[1]]
[1] 9 4

[[2]]
[1] 9 4

[[3]]
[1] 10  4
</code>```

In order to retrieve the coordinates and calculate distances (per row for each data.table):

```<code>ntrips<-length(ls(pattern = "^trip"))#dynamically

for(i in 1:ntrips){
  da_trip<-get(paste0("trip",i))
  distance<-NULL
  for(k in 1:dim(da_trip)[1]){
    distance[k]<-gcd.hf(long1 =as.numeric(da_trip[,.(long.start)][k]),long2=as.numeric(da_trip[,.(long.end)][k]),lat1 = as.numeric(da_trip[,.(lat.start)][k]),lat2=as.numeric(da_trip[,.(lat.end)][k]))
  }
 assign(paste0("trip",i),cbind(da_trip,distance)) # send the distance to the initial data table as column
}
</code>```

resulting in :

```<code>>trip1
   long.start long.end lat.start  lat.end  distance
 1:   89.18974 98.44804  34.68381 62.55508  1413.027
 2:   55.95637 95.27552  23.33369 75.74160 12065.602
 3:   59.32357 73.49386  12.62365 50.18466 10247.026
 4:   81.72157 20.00639  40.20866 93.14260 14830.970
 5:   18.08152 52.52404  88.42411 19.10752 15388.778
 6:   54.50308 91.24726  27.19433 80.65325 17081.717
 7:   73.17393 19.83704  60.40830 23.68220  4668.884
 8:   77.57680 87.32211  76.25292 12.22423 16361.216
 9:   93.60303 55.62256  95.20154 32.75852  2562.363
</code>```

Also the new dimensions of all the trip objects:

```<code> lapply(lapply(ls(pattern = "^trip"),get),dim)
[[1]]
[1] 9 5

[[2]]
[1] 9 5

[[3]]
[1] 10  5
</code>```

DATA TABLE way

In data.table instead of loop you can always perform operations between columns as shown below:

trip1[,distance2:=gcd.hf(long.start,lat.start,long.end,lat.end),by=1:nrow(trip1)]

```<code>> trip1
   long.start long.end lat.start  lat.end  distance distance2
1:   89.18974 98.44804  34.68381 62.55508  1413.027  1413.027
2:   55.95637 95.27552  23.33369 75.74160 12065.602 12065.602
                               [...]
</code>```

Title: assign with $ R

Body:
I have several vector describing a trip, in each of them there are indications of latitude and longitude.

The code I am trying to write is the following

for (i in 1:ntrips){
 for (k in 1:dim(get(paste0("trip",i)))[1]){

 assign(paste0("trip", i)$distance[k],gcd.hf(get(paste0("trip", i))$long.start[k],get(paste0("trip",i))$lat.start[k],get(paste0("trip",i))$end.start[k],get(paste0("trip", i))$lat.end[k]))

 }
}

Basically for each vector (trip1, trip2, ...), I want to calculate the value of the distance with the function gcd.hf (defined previously) and paste it in the column named distance.

the error I get is

Error: $ operator is invalid for atomic vectors

Is there anything I am missing?

Body:
The very first part of assign is not legitimate

 paste0("trip", i)$distance[k]

Try using legitimate names for your variables. E.g.
inside the loop

ma_trip<-get(paste0("trip",i))
assign(paste0("trip", i,"_distance",ma_trip$distance[k]),...)

ADDITION

So let's begin from scratch:

Create the trips along with the coordinates:

fac<-100
N<-3#number of trips
for(i in 1:N){#create N data.tables
  for(j in round(max(runif(3)*10),0)){#with random number of rows
    #the coordinates are generated
    long.start<-fac*runif(j)
    long.end<-fac*runif(j)
    lat.start<-fac*runif(j)
    lat.end<-fac*runif(j)
  }
assign(paste0("trip",i),data.table(long.start,long.end,lat.start,lat.end))#and are attributed to the data.table
}

Each data.table has the following form:

 >trip1

    long.start long.end lat.start  lat.end
 1:   89.18974 98.44804  34.68381 62.55508
 2:   55.95637 95.27552  23.33369 75.74160
 3:   59.32357 73.49386  12.62365 50.18466
 4:   81.72157 20.00639  40.20866 93.14260
 5:   18.08152 52.52404  88.42411 19.10752
 6:   54.50308 91.24726  27.19433 80.65325
 7:   73.17393 19.83704  60.40830 23.68220
 8:   77.57680 87.32211  76.25292 12.22423
 9:   93.60303 55.62256  95.20154 32.75852

The dimension of the tripN objects can be given by

 >lapply(lapply(ls(pattern = "^trip"),get),dim)
[[1]]
[1] 9 4

[[2]]
[1] 9 4

[[3]]
[1] 10  4

In order to retrieve the coordinates and calculate distances (per row for each data.table):

ntrips<-length(ls(pattern = "^trip"))#dynamically

for(i in 1:ntrips){
  da_trip<-get(paste0("trip",i))
  distance<-NULL
  for(k in 1:dim(da_trip)[1]){
    distance[k]<-gcd.hf(long1 =as.numeric(da_trip[,.(long.start)][k]),long2=as.numeric(da_trip[,.(long.end)][k]),lat1 = as.numeric(da_trip[,.(lat.start)][k]),lat2=as.numeric(da_trip[,.(lat.end)][k]))
  }
 assign(paste0("trip",i),cbind(da_trip,distance)) # send the distance to the initial data table as column
}

resulting in :

>trip1
   long.start long.end lat.start  lat.end  distance
 1:   89.18974 98.44804  34.68381 62.55508  1413.027
 2:   55.95637 95.27552  23.33369 75.74160 12065.602
 3:   59.32357 73.49386  12.62365 50.18466 10247.026
 4:   81.72157 20.00639  40.20866 93.14260 14830.970
 5:   18.08152 52.52404  88.42411 19.10752 15388.778
 6:   54.50308 91.24726  27.19433 80.65325 17081.717
 7:   73.17393 19.83704  60.40830 23.68220  4668.884
 8:   77.57680 87.32211  76.25292 12.22423 16361.216
 9:   93.60303 55.62256  95.20154 32.75852  2562.363

Also the new dimensions of all the trip objects:

 lapply(lapply(ls(pattern = "^trip"),get),dim)
[[1]]
[1] 9 5

[[2]]
[1] 9 5

[[3]]
[1] 10  5

DATA TABLE way

In data.table instead of loop you can always perform operations between columns as shown below:

trip1[,distance2:=gcd.hf(long.start,lat.start,long.end,lat.end),by=1:nrow(trip1)]

> trip1
   long.start long.end lat.start  lat.end  distance distance2
1:   89.18974 98.44804  34.68381 62.55508  1413.027  1413.027
2:   55.95637 95.27552  23.33369 75.74160 12065.602 12065.602
                               [...]


问:
CSS background-image transitions effects not working as expected
Ok, so I'm working on this swipe effect on hover using div and background image. background image uses outer div max-width and inner div with padding-bottom percentage to maintain aspect ratio.

There are a few things here I don't understand.

I was very surprised that my %200 background position only pushed the image over a few pixels, in the end, a massive 7100% was required to fully move the image over so the repeated image was fully visible.

When I set the padding-bottom to anything over 54%, the transition and everything stops working.

This '7100%' seems to produce the right effect in chrome, firefox, and opera, but not safari.

My fiddle, thoughts?
https://jsfiddle.net/riegersn/a3mnr9um

```<code>.container {
      max-width: 480px;
    }

.project {
  margin-bottom: 15px;
  cursor: pointer;
  overflow: hidden;
  width: 100%;
  background-position: center center;
  background-repeat: repeat-x;
  background-size: contain;
  transition: all 0.2s ease-out;
  padding-bottom: 54%;
  &:hover {
    background-position: 7100% 50%;
  }
}
</code>```

答:
When it comes to using percent with position background images, it gets somewhat complicated.

Moving a background image by X% means it will align the X% point in
the image to the X% point in the container. For example, 50% means it
will align the middle of the image with the middle of the container.
100% means it will align the last pixel of the image with the last
pixel of the container, and so on.

Src: https://css-tricks.com/almanac/properties/b/background-position/)

Here is also a very good explanation of how it works: how-does-css-computation-for-background-percentages-work

May I recommend a pseudo element instead, where you can use transform, which performs better than background-position when it comes to animations.

With a pseudo you can also zoom, rotate, skew, animate back and forth, etc., stuff which is simply not possible with the background-image alone.

What happens in below sample is, I made the pseudo twice the width of the project, positioned it half its width to the left (left: -100%, where 100% comes from its parent) and then, when hovered, I move it back so left becomes 0 (transform: translateX(50%)), where translateX(50%) means move it half its own width to the right.

.container {
  max-width: 480px;
}

.project {
  position: relative;
  margin-bottom: 15px;
  cursor: pointer;
  overflow: hidden;
  width: 100%;
  padding-bottom: 54%;
  background-size: 0;
}
.project::before {
  content: '';
  position: absolute;
  left: -100%; top: 0;
  width: 200%; height: 100%;
  background-position: left center;
  background-repeat: repeat-x;
  background-size: contain;
  background-image: inherit;
  transition: transform 0.5s ease-out;
}
.project:hover::before {
  transform: translateX(50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="project" style="background-image:url('https://www.dropbox.com/s/fpha4d0uyu71whe/pandora_thumb.png?dl=1')">
  </div>
</div></code>```

Body:
Ok, so I'm working on this swipe effect on hover using div and background image. background image uses outer div max-width and inner div with padding-bottom percentage to maintain aspect ratio.

There are a few things here I don't understand.

I was very surprised that my %200 background position only pushed the image over a few pixels, in the end, a massive 7100% was required to fully move the image over so the repeated image was fully visible.

When I set the padding-bottom to anything over 54%, the transition and everything stops working.

This '7100%' seems to produce the right effect in chrome, firefox, and opera, but not safari.

My fiddle, thoughts?
https://jsfiddle.net/riegersn/a3mnr9um

.container {
      max-width: 480px;
    }

.project {
  margin-bottom: 15px;
  cursor: pointer;
  overflow: hidden;
  width: 100%;
  background-position: center center;
  background-repeat: repeat-x;
  background-size: contain;
  transition: all 0.2s ease-out;
  padding-bottom: 54%;
  &:hover {
    background-position: 7100% 50%;
  }
}

Body:
When it comes to using percent with position background images, it gets somewhat complicated.

Moving a background image by X% means it will align the X% point in
the image to the X% point in the container. For example, 50% means it
will align the middle of the image with the middle of the container.
100% means it will align the last pixel of the image with the last
pixel of the container, and so on.

Src: https://css-tricks.com/almanac/properties/b/background-position/)

Here is also a very good explanation of how it works: how-does-css-computation-for-background-percentages-work

May I recommend a pseudo element instead, where you can use transform, which performs better than background-position when it comes to animations.

With a pseudo you can also zoom, rotate, skew, animate back and forth, etc., stuff which is simply not possible with the background-image alone.

What happens in below sample is, I made the pseudo twice the width of the project, positioned it half its width to the left (left: -100%, where 100% comes from its parent) and then, when hovered, I move it back so left becomes 0 (transform: translateX(50%)), where translateX(50%) means move it half its own width to the right.

.container {
  max-width: 480px;
}

.project {
  position: relative;
  margin-bottom: 15px;
  cursor: pointer;
  overflow: hidden;
  width: 100%;
  padding-bottom: 54%;
  background-size: 0;
}
.project::before {
  content: '';
  position: absolute;
  left: -100%; top: 0;
  width: 200%; height: 100%;
  background-position: left center;
  background-repeat: repeat-x;
  background-size: contain;
  background-image: inherit;
  transition: transform 0.5s ease-out;
}
.project:hover::before {
  transform: translateX(50%);
}

<div class="container">
  <div class="project" style="background-image:url('https://www.dropbox.com/s/fpha4d0uyu71whe/pandora_thumb.png?dl=1')">
  </div>
</div>


问:
How to list all files added to the first commit of a GIT repository?
Current status:
I am using git diff-tree -r HASH to list all added, modified and deleted files in a specific commit. This worked until today.

The problem:
I want to list all added files in my first commit, however passing the first HASH as a parameter doesn't work. Why?

Main question:
How can I get the list of all files added in my first commit?

答: git show --pretty=format: --name-only <revision>


问:
Printing array with Processingjs

I'm reading through the khan academy course on algorithms. I'm at https://www.khanacademy.org/computing/computer-science/algorithms/sorting-algorithms/p/project-selection-sort-visualizer .

The code is working and I can get it to print to the console but I need to be able to print to the canvas.

I've tried :

```<code>var displayArray = function(array) {
    textFont(createFont("monospace"), 12);
    println(array);

};
</code>```

Bu this again just prints to the console. How can I print to the canvas with processingjs?

答:
You're still using "println", you need to use 'text' function.

http://processingjs.org/reference/text_/ is the reference on how to use this.

Title: Printing array with Processingjs

Body:
I'm reading through the khan academy course on algorithms. I'm at https://www.khanacademy.org/computing/computer-science/algorithms/sorting-algorithms/p/project-selection-sort-visualizer .

The code is working and I can get it to print to the console but I need to be able to print to the canvas.

I've tried :

var displayArray = function(array) {
    textFont(createFont("monospace"), 12);
    println(array);

};

Bu this again just prints to the console. How can I print to the canvas with processingjs?


问:
Why is selfregistration bad?
Assuming self-registration is used to install components as part of a larger installer program, why is self-registration bad? E.g. self-registering vb custom controls or capicom or whatever.  I acknowledge that self-registration is probably not as safe in the case of a dll you wrote yourself, but I'm not discussing those.

The MSDN lists several reasons why self-registration is bad, reproduced here:

 Rollback won't work properly.

OK, this reason makes sense.

 Advertisement will not work as well.

Ignoring the fact that advertisement is only important for certain types of software clients, I don't understand why this is an issue.  Only the main application needs to be advertised, not its components.

Self-registration does not support per-user keys properly.

So what? Giving every user access to "common" components is not a bad thing unless you have a lot of users on the machine, in which case it's still not world-ending.

 Self-registration is more susceptible to coding errors.

I can definitely believe this, except in the case of dlls which were written by Microsoft (they may have errors, but I don't think trusting them is unreasonable).  And in the case of tlbs and ocxs which were generated by software, coding errors seem pretty unlikely.

 Self-registering dlls may link to other dlls.

In the case of dlls generated by programs, it doesn't seem likely that self-registration will fail due to this but adding the registration keys manually would have worked.  I'd rather have my self-registration return an error that I'm missing the dlls.

I'm sure this will draw flames :/

Edit: Crossed out arguments that I think actually matter (based on user responses and my own).

答:
The item

Self-registering dlls may link to
  other dlls

applies when you try to register the dll, but the installer has not yet copied/installed another dll your registering function requires.

OwnerDisplayName: Brian

ContentLicense: CC BY-SA 2.5

Title: Why is selfregistration bad?

LastEditorDisplayName: Brian

OwnerDisplayName: Stefan


问:
How is it possible to reliably send JMS message? (fail over MessageProducer.send() errors)
Is it possible to reliably send JMS message to the destination? By reliably I mean ensuring that if e.g. MessageProducer.send() call fails for some reason, it will be retried automatically. I realize that transaction session may use .recover() as last resort, but what about retrying? E.g. I have intermittent network failure in between session was established and attempted to send a message. How would recover() help in this case?

答:
JMS doesn't specify the behavior you are looking for.  In fact, JMS specifically addresses problems due to network failure by noting that you may get the same message twice and calls this a "functionally duplicate" message since from the point of view of the JMS broker, it has only been delivered once.

Since this is not part of JMS your answer lies in the different vendor implementations.  For example, WebSphere MQ has a feature called "Multi-Instance Queue Manager" as of v7.0.1.  A v7.0.1 client application will automatically retry the connection and even follow the QMgr from the primary to the secondary node in the event of a failure.  The application blocks while this occurs and is not aware of the failover.

However, even with this behavior, your app still needs to code for the failure.  For example, if using the WMQ automatic reconnect (or any provider's reconnect for that matter) you probably want to tune the length of time the app might block waiting to recover the connection so that the user doesn't experience an indefinite hang.  When the call unblocks, the transaction is rolled back and any retry must occur in the code.  This is appropriate since the transaction is associated with a connection that is no longer valid.


问:
How to get a value from controller to view in laravel?
I have a simple input form with a text input field and a submit button. I am trying to get the value from the input field to be displayed again on the same page after the submit button is clicked. So far laravel always throws an error that the variable is undefined.

Route:

```<code>Route::get('/find/names', "FindController@get_name")->name('names');
</code>```

Controller

```<code> public function get_name(){
         $name = Input::get('name_by_user');
         return $name;
    }
</code>```

view

```<code>        <form role="form" method="GET">
                    <div class="row">
                        <div class="form-group">
                            <div class="input-group">
                                <input type="text" name="name_by_user"/>
                                <span class="input-group-btn">
                                    <button class="btn search-button" type="submit">
                                    <span aria-hidden="true">
                                    <span>Search</span>
                                    </button>
                                </span>
                                </span>
                            </div>
                        </div>
                    </div>
                </form>

  display name after submitting:  {{$name}}
</code>```

答:
When generating a view inside a controller for a route, you can do the following in a function to return a view with data depending on whether it exists.</p>

```<code>public function showNameView() {

    if(is_null(Input::get('name_by_user'))
    {

        return view('my.view')->with(['name' => Input::get('name_by_user')]);

    }
    else
    {

        return view('my.view')->with(['name' => Input::get('name_by_user')]);

    }

}
</code>```

Body:
I have a simple input form with a text input field and a submit button. I am trying to get the value from the input field to be displayed again on the same page after the submit button is clicked. So far laravel always throws an error that the variable is undefined.

Route:

Route::get('/find/names', "FindController@get_name")->name('names');

Controller

 public function get_name(){
         $name = Input::get('name_by_user');
         return $name;
    }

view

        <form role="form" method="GET">

                                <input type="text" name="name_by_user"/>

                                    <button class="btn search-button" type="submit">

                                    Search
                                    </button>

                </form>

  display name after submitting:  {{$name}}

Body:
When generating a view inside a controller for a route, you can do the following in a function to return a view with data depending on whether it exists.

public function showNameView() {

    if(is_null(Input::get('name_by_user'))
    {

        return view('my.view')->with(['name' => Input::get('name_by_user')]);

    }
    else
    {

        return view('my.view')->with(['name' => Input::get('name_by_user')]);

    }

}


问:
Combine 2 TextBoxFor bound to one property MVC
I need to save the Contact Number in a registration form wherein i'm having 2 TextBox, one for Country Code and another for Number. Now i need to combine both and bind into a single property which i have in my class. How can i do that?

View:

```<code> <div class="form-group">
      @Html.LabelFor(m => m.Phone, "Contact Number:")
      @Html.TextBoxFor(m => m.xxxx,new { @class = "form-control", @id = "txtContactCode", required="required", type ="number" })-
      @Html.TextBoxFor(m => m.Phone,new { @class = "form-control", @id = "txtContactNumber", required="required", type ="number" })
 </div>
</code>```

Property,

```<code> public string Phone { get; set; }
</code>```

Now what should i bind the property in the code of the phone number field to concatenate as one? Is there any way or i should declare another property named Code and then proceed?

答:
You can easily do this by using the BindModel() method which is available in the IModelBinder interface.

IModelBinder.BindModel: Binds the model to a value by using the specified controller context and binding context.

Also see this explanation with real-time example.

Note: In the above example, first_name, middle_name and last_name were bound to the full name property. You can bind your required two properties to the one property in the same way.

Body:
I need to save the Contact Number in a registration form wherein i'm having 2 TextBox, one for Country Code and another for Number. Now i need to combine both and bind into a single property which i have in my class. How can i do that?

View:

      @Html.LabelFor(m => m.Phone, "Contact Number:")
      @Html.TextBoxFor(m => m.xxxx,new { @class = "form-control", @id = "txtContactCode", required="required", type ="number" })-
      @Html.TextBoxFor(m => m.Phone,new { @class = "form-control", @id = "txtContactNumber", required="required", type ="number" })

Property,

 public string Phone { get; set; }

Now what should i bind the property in the code of the phone number field to concatenate as one? Is there any way or i should declare another property named Code and then proceed?


问:
Android - How to launch Google map intent in driving mode?
I am able to launch Google Maps intent with

```<code>Uri location = Uri.parse("geo:0,0");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, location);
startActivity(mapIntent);
</code>```

How can I launch the intent in Driving mode (with no destination, unless previously set in Maps) so that it looks like on the screenshot below?

I tried setting mode=driving but that just opens the regular map with the "driving" tab selected:

```<code> Uri location = Uri.parse("geo:0,0?mode=driving");
</code>```

答:
I understand you would like to open a Google Maps app in navigation mode. For this purpose you can use an URL described in the Google Maps URLs API:

https://developers.google.com/maps/documentation/urls/guide#directions-action

The following code should do a trick, and I believe you need to provide a destination parameter to open this mode directly

```<code>String URL = "https://www.google.com/maps/dir/?api=1&travelmode=driving&dir_action=navigate&destination=Los+Angeles";
Uri location = Uri.parse(URL);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, location);
startActivity(mapIntent);
</code>```

I hope this helps!

Body:
I am able to launch Google Maps intent with

Uri location = Uri.parse("geo:0,0");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, location);
startActivity(mapIntent);

How can I launch the intent in Driving mode (with no destination, unless previously set in Maps) so that it looks like on the screenshot below?

I tried setting mode=driving but that just opens the regular map with the "driving" tab selected:

 Uri location = Uri.parse("geo:0,0?mode=driving");

Body:
I understand you would like to open a Google Maps app in navigation mode. For this purpose you can use an URL described in the Google Maps URLs API:

https://developers.google.com/maps/documentation/urls/guide#directions-action

The following code should do a trick, and I believe you need to provide a destination parameter to open this mode directly

String URL = "https://www.google.com/maps/dir/?api=1&travelmode=driving&dir_action=navigate&destination=Los+Angeles";
Uri location = Uri.parse(URL);
Intent mapIntent = new Intent(Intent.ACTION_VIEW, location);
startActivity(mapIntent);

I hope this helps!


问:
Divide rows with date in SQL Server 2014
I have a problem with SQL. I have the following table:

```<code>declare @t table (START_DATE datetime,
                  END_DATE datetime,
                  GROSS_SALES_PRICE decimal(10,2)
                 );

insert into @t
values ('2014-08-06 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
       ('2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
       ('2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
       ('2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)
</code>```

I would like to separate the dates which overlaps. For example I have in the first row START_DATE 2014-08-06 and END_DATE 2014-10-06. We can see that the dates from the second and the third row are inside this period of time from first row.

So I would like to separate them as follows:

```<code>declare @t2 table (START_DATE datetime,
                   END_DATE datetime,
                   GROSS_SALES_PRICE decimal(10,2)
                  );

insert into @t2
values ('2014-08-06 00:00:00.000', '2014-09-05 23:59:59.000', 29.99),
       ('2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
       ('2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
       ('2014-10-01 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
       ('2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)
</code>```

So the second and the third rows remained unchanged. The first row should have new END_DATE. We also have new row. The GROSS_SALES_PRICE should remain as it is in internal period. Thanks for help. I am using SQL Server 2014

答:
This can be solved with simple joins and unions. However better with an ID. The common table expression is only to add an ID.</p>

```<code>declare @t table(START_DATE datetime,END_DATE datetime, GROSS_SALES_PRICE
 decimal(10,2));
insert into @t values
 ( '2014-08-06 00:00:00.000',   '2014-10-06 23:59:59.000',  29.99),
 ( '2014-09-06 00:00:00.000',   '2014-09-09 23:59:59.000',  32.99),
 ( '2014-09-10 00:00:00.000',   '2014-09-30 23:59:59.000',  32.99),
 ( '2014-10-07 00:00:00.000',   '2049-12-31 23:59:59.000',  34.99)

;with t_cte as
(select row_number() over( order by start_date,end_date,GROSS_SALES_PRICE) ID,*
from @t
)

select t1.start_date,min(t2.start_date),t1.GROSS_SALES_PRICE
from t_cte t1
join t_cte t2 on t1.END_DATE > t2.START_DATE and t1.END_DATE> t2.START_DATE and t1.id< t2.id
group by t1.START_DATE,t1.END_DATE,t1.GROSS_SALES_PRICE
union all
select min(t2.start_date),t1.end_date,t1.GROSS_SALES_PRICE
from t_cte t1
join t_cte t2 on t1.END_DATE > t2.START_DATE and t1.END_DATE> t2.START_DATE and t1.id< t2.id
group by t1.START_DATE,t1.END_DATE,t1.GROSS_SALES_PRICE
union all
select t1.start_date,t1.END_DATE,t1.GROSS_SALES_PRICE
from t_cte t1
left join t_cte t2 on t1.END_DATE > t2.START_DATE and t1.END_DATE> t2.START_DATE and t1.id< t2.id
where t2.id is null
order by 1,2,3
</code>```

Body:
I have a problem with SQL. I have the following table:

declare @t table (START_DATE datetime,
                  END_DATE datetime,
                  GROSS_SALES_PRICE decimal(10,2)
                 );

insert into @t
values ('2014-08-06 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
       ('2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
       ('2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
       ('2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)

I would like to separate the dates which overlaps. For example I have in the first row START_DATE 2014-08-06 and END_DATE 2014-10-06. We can see that the dates from the second and the third row are inside this period of time from first row.

So I would like to separate them as follows:

declare @t2 table (START_DATE datetime,
                   END_DATE datetime,
                   GROSS_SALES_PRICE decimal(10,2)
                  );

insert into @t2
values ('2014-08-06 00:00:00.000', '2014-09-05 23:59:59.000', 29.99),
       ('2014-09-06 00:00:00.000', '2014-09-09 23:59:59.000', 32.99),
       ('2014-09-10 00:00:00.000', '2014-09-30 23:59:59.000', 32.99),
       ('2014-10-01 00:00:00.000', '2014-10-06 23:59:59.000', 29.99),
       ('2014-10-07 00:00:00.000', '2049-12-31 23:59:59.000', 34.99)

So the second and the third rows remained unchanged. The first row should have new END_DATE. We also have new row. The GROSS_SALES_PRICE should remain as it is in internal period. Thanks for help. I am using SQL Server 2014

Body:
This can be solved with simple joins and unions. However better with an ID. The common table expression is only to add an ID.

declare @t table(START_DATE datetime,END_DATE datetime, GROSS_SALES_PRICE
 decimal(10,2));
insert into @t values
 ( '2014-08-06 00:00:00.000',   '2014-10-06 23:59:59.000',  29.99),
 ( '2014-09-06 00:00:00.000',   '2014-09-09 23:59:59.000',  32.99),
 ( '2014-09-10 00:00:00.000',   '2014-09-30 23:59:59.000',  32.99),
 ( '2014-10-07 00:00:00.000',   '2049-12-31 23:59:59.000',  34.99)

;with t_cte as
(select row_number() over( order by start_date,end_date,GROSS_SALES_PRICE) ID,*
from @t
)

select t1.start_date,min(t2.start_date),t1.GROSS_SALES_PRICE
from t_cte t1
join t_cte t2 on t1.END_DATE > t2.START_DATE and t1.END_DATE> t2.START_DATE and t1.id< t2.id
group by t1.START_DATE,t1.END_DATE,t1.GROSS_SALES_PRICE
union all
select min(t2.start_date),t1.end_date,t1.GROSS_SALES_PRICE
from t_cte t1
join t_cte t2 on t1.END_DATE > t2.START_DATE and t1.END_DATE> t2.START_DATE and t1.id< t2.id
group by t1.START_DATE,t1.END_DATE,t1.GROSS_SALES_PRICE
union all
select t1.start_date,t1.END_DATE,t1.GROSS_SALES_PRICE
from t_cte t1
left join t_cte t2 on t1.END_DATE > t2.START_DATE and t1.END_DATE> t2.START_DATE and t1.id< t2.id
where t2.id is null
order by 1,2,3


问:
how to do tooltip on button in iphone?
I am having download icon on my page i want that when the user takes his finger over the button a tooltip should show as showing download in text.

is there any option in iphone to show a tooltip???

答:
Nothing built-in, no. If you think about it, generally a tooltip appears when you mouse over the target item. There's no "mousing over" with a touch interface.

You can definitely roll your own, though. Start by placing a view containing your tooltip contents exactly where you want it with an alpha of 0%. Make a custom button with no content that outlines your download icon, and hook its "touch down inside" action to a method that animates the tooltip view to an alpha of 100%. Hook your button's "touch up inside" , "touch down outside" and "touch up outside" actions (and maybe some others--you might want to experiment with that) to a method that animates the tooltip view back to an alpha of 0%.

Title: how to do tooltip on button in iphone?


问:
How to have powershell use a else statement to search another folder
I am trying to import some PST files into Outlook automatically, I currently am using the following script

```<code>Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null
$outlook = new-object -comobject outlook.application
$namespace = $outlook.GetNameSpace("MAPI")
dir “$env:USERPROFILE\appdata\local\microsoft\outlook\.pst” | % {
$namespace.AddStore($_.FullName) }
</code>```

I would like to add a else statement so that if the pst file is not found in the first location then it will check in "$env:USERPROFILE\Documents\Outlook Files"

答:
For a single file, use Test-Path to verify if the file is in the location you expect, for example:

```<code>$pathA = "C:\path\to\my\file"
$pathB = "C:\path\to\another\file"

if(Test-Path $pathA){
  # do something with $pathA
}
else {
  # do something with $pathB
}
</code>```

In your case you are using dir (an alias for Get-ChildItem) which returns all files in a folder matching the path/name specified. What you may want to do is to look for the files first in PathA and, if you don't find any, look in PathB:

```<code>$pathA = "C:\path\to\my\folder\*.pst"
$pathB = "C:\path\to\another\folder\*.pst"

$files = Get-ChildItem $pathA

if($files){
  # do something with $pathA
}
else {
  # do something with $pathB
}
</code>```

Body:
I am trying to import some PST files into Outlook automatically, I currently am using the following script

Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null
$outlook = new-object -comobject outlook.application
$namespace = $outlook.GetNameSpace("MAPI")
dir “$env:USERPROFILE\appdata\local\microsoft\outlook\.pst” | % {
$namespace.AddStore($_.FullName) }

I would like to add a else statement so that if the pst file is not found in the first location then it will check in "$env:USERPROFILE\Documents\Outlook Files"

Body:
For a single file, use Test-Path to verify if the file is in the location you expect, for example:

$pathA = "C:\path\to\my\file"
$pathB = "C:\path\to\another\file"

if(Test-Path $pathA){
  # do something with $pathA
}
else {
  # do something with $pathB
}

In your case you are using dir (an alias for Get-ChildItem) which returns all files in a folder matching the path/name specified. What you may want to do is to look for the files first in PathA and, if you don't find any, look in PathB:

$pathA = "C:\path\to\my\folder\*.pst"
$pathB = "C:\path\to\another\folder\*.pst"

$files = Get-ChildItem $pathA

if($files){
  # do something with $pathA
}
else {
  # do something with $pathB
}


问:
How to find a number that isn't there?
We have a custom number field on a training record, the number is recorded sequentially but there are gaps.  How do I find those gaps?  Consider this pseudocode

```<code>SELECT MIN(X)
FROM DUAL
WHERE X BETWEEN 1 AND 999999
  AND X NOT IN (SELECT AG_TRNID
                FROM PS_TRAINING
                WHERE AG_TRNID = X)
</code>```

This doesn't work, "X" is unknown.

Thanks!
Bruce

答:
You can create a "virtual" table that contains all numbers from 1 to 999999 then remove those that are present in your table:

```<code>select level
from dual
connect by level <= 999999
minus
select ag_trnid
from ps_training;
</code>```

The above will output all gaps, not just the first one.

The connect by level <= 999999 is an undocumented trick to generate all numbers from 1 to 999999.

Title: How to find a number that isn't there?

Body:
We have a custom number field on a training record, the number is recorded sequentially but there are gaps.  How do I find those gaps?  Consider this pseudocode

SELECT MIN(X)
FROM DUAL
WHERE X BETWEEN 1 AND 999999
  AND X NOT IN (SELECT AG_TRNID
                FROM PS_TRAINING
                WHERE AG_TRNID = X)

This doesn't work, "X" is unknown.

Thanks!
Bruce

Body:
You can create a "virtual" table that contains all numbers from 1 to 999999 then remove those that are present in your table:

select level
from dual
connect by level <= 999999
minus
select ag_trnid
from ps_training;

The above will output all gaps, not just the first one.

The connect by level <= 999999 is an undocumented trick to generate all numbers from 1 to 999999.


问:
mouse move in python video game
This code causes my screen to go black

I am using PIL imagegrab to process images

whenever i make a call to move the mouse using the following code the screen goes black:

```<code>def MoveMouse(x, y):
    extra = ctypes.c_ulong(0)
    ii_ = Input_I()
    x = int(x*(65536/ctypes.windll.user32.GetSystemMetrics(0))+1)
    y = int(y*(65536/ctypes.windll.user32.GetSystemMetrics(1))+1)
    ii_.mi = MouseInput(x, y, 0, 0x0001 | 0x8000, 1, ctypes.pointer(extra))
    x = Input(ctypes.c_ulong(0), ii_)
    ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))
</code>```

答:
I also had that problem and it took WAY to long to figure it out, anyway for me the fix was to change in the line:

```<code>ii_.mi = MouseInput(x, y, 0, 0x0001 | 0x8000, 1, ctypes.pointer(extra))
</code>```

the fifth parameter (i.e. "1") to 0:

```<code>ii_.mi = MouseInput(x, y, 0, 0x0001 | 0x8000, 0, ctypes.pointer(extra))
</code>```

hope this helps.

Title: mouse move in python video game

Body:
This code causes my screen to go black

I am using PIL imagegrab to process images

whenever i make a call to move the mouse using the following code the screen goes black:

def MoveMouse(x, y):
    extra = ctypes.c_ulong(0)
    ii_ = Input_I()
    x = int(x*(65536/ctypes.windll.user32.GetSystemMetrics(0))+1)
    y = int(y*(65536/ctypes.windll.user32.GetSystemMetrics(1))+1)
    ii_.mi = MouseInput(x, y, 0, 0x0001 | 0x8000, 1, ctypes.pointer(extra))
    x = Input(ctypes.c_ulong(0), ii_)
    ctypes.windll.user32.SendInput(1, ctypes.pointer(x), ctypes.sizeof(x))

Body:
I also had that problem and it took WAY to long to figure it out, anyway for me the fix was to change in the line:

ii_.mi = MouseInput(x, y, 0, 0x0001 | 0x8000, 1, ctypes.pointer(extra))

the fifth parameter (i.e. "1") to 0:

ii_.mi = MouseInput(x, y, 0, 0x0001 | 0x8000, 0, ctypes.pointer(extra))

hope this helps.