Programs & Examples On #Messagebox

A message box is a prefabricated modal dialog box that displays a text message to a user.

How to pop an alert message box using PHP?

I have done it this way:

<?php 
$PHPtext = "Your PHP alert!";
?>

var JavaScriptAlert = <?php echo json_encode($PHPtext); ?>;
alert(JavaScriptAlert); // Your PHP alert!

center MessageBox in parent form

I have changed a little bit previous answer and compose WPF version of the MessageBoxEx. This code works for me great. Feel free to notify about issues of the code.

Please note: I use GeneralObjects.MainWindowInstance at ctor to initialize class with my main window, but actually I use it for any window due to some kind of cache for last parent window. Therefore you can simple remove out everything from ctor.

public class MessageBoxEx
{
    private static HwndSource source_ = null;
    private static HwndSourceHook hook_ = null;

    static MessageBoxEx()
    {
        try
        {
            // create cached 
            createHwndSource_(GeneralObjects.MainWindowInstance);

            hook_ = new HwndSourceHook(HwndSourceHook);
        }
        finally
        {
            if (null == source_ ||
                null == hook_)
            {
                source_ = null;
                hook_ = null;
            }
        }


    }

    private static void createHwndSource_(Window owner)
    {
        source_ = (HwndSource)PresentationSource.FromVisual(owner);
    }

    public static void Initialize_(Window owner = null)
    {
        try
        {
            if (null != owner)
            {
                if(source_.RootVisual != owner)
                {
                    createHwndSource_(owner);
                }

            }
        }
        finally
        {
            if (null == source_ ||
                null == hook_)
            {
                source_ = null;
                hook_ = null;
            }
        }


        if (null != source_ &&
            null != hook_)
        {
            source_.AddHook(hook_);
        }

    }

    public static MessageBoxResult Show(string messageBoxText)
    {
        Initialize_();
        return System.Windows.MessageBox.Show(messageBoxText);
    }


    public static MessageBoxResult Show(string messageBoxText, string caption)
    {
        Initialize_();
        return System.Windows.MessageBox.Show(messageBoxText, caption);
    }


    public static MessageBoxResult Show(Window owner, string messageBoxText)
    {
        Initialize_(owner);
        return System.Windows.MessageBox.Show(owner, messageBoxText);
    }


    public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button)
    {
        Initialize_();
        return System.Windows.MessageBox.Show(messageBoxText, caption, button);
    }


    public static MessageBoxResult Show(Window owner, string messageBoxText, string caption)
    {
        Initialize_(owner);
        return System.Windows.MessageBox.Show(owner, messageBoxText, caption);
    }


    public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon)
    {
        Initialize_();
        return System.Windows.MessageBox.Show(messageBoxText, caption, button, icon);
    }


    public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button)
    {
        Initialize_(owner);
        return System.Windows.MessageBox.Show(owner, messageBoxText, caption, button);
    }


    public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult)
    {
        Initialize_();
        return System.Windows.MessageBox.Show(messageBoxText, caption, button, icon, defaultResult);
    }


    public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon)
    {
        Initialize_(owner);
        return System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon);
    }


    public static MessageBoxResult Show(string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult, System.Windows.MessageBoxOptions options)
    {
        Initialize_();
        return System.Windows.MessageBox.Show(messageBoxText, caption, button, icon, defaultResult, options);
    }


    public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult)
    {
        Initialize_(owner);
        return System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon, defaultResult);
    }


    public static MessageBoxResult Show(Window owner, string messageBoxText, string caption, MessageBoxButton button, MessageBoxImage icon, MessageBoxResult defaultResult, System.Windows.MessageBoxOptions options)
    {
        Initialize_(owner);
        return System.Windows.MessageBox.Show(owner, messageBoxText, caption, button, icon, defaultResult, options);
    }

    private enum WM : int
    {
        WM_ACTIVATE = 0x0006
    }

    private static IntPtr HwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {

        if ((int)WM.WM_ACTIVATE == msg &&
            source_.Handle == hwnd &&
            0 == (int)wParam)
        {

            try
            {
                CenterWindow(lParam);
            }
            finally
            {
                // remove hook at once after moved message box window.
                source_.RemoveHook(hook_);
            }
        }
        return IntPtr.Zero;
    }

    [DllImport("user32.dll")]
    private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect);


    [DllImport("user32.dll")]
    private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);

    private static void CenterWindow(IntPtr hChildWnd)
    {
        System.Drawing.Rectangle recChild = new System.Drawing.Rectangle(0, 0, 0, 0);

        bool success = GetWindowRect(hChildWnd, ref recChild);

        int width = recChild.Width - recChild.X;
        int height = recChild.Height - recChild.Y;

        System.Drawing.Rectangle recParent = new System.Drawing.Rectangle(0, 0, 0, 0);
        success = GetWindowRect(source_.Handle, ref recParent);

        System.Drawing.Point ptCenter = new System.Drawing.Point(0, 0);
        ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2);
        ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2);


        System.Drawing.Point ptStart = new System.Drawing.Point(0, 0);
        ptStart.X = (ptCenter.X - (width / 2));
        ptStart.Y = (ptCenter.Y - (height / 2));

        // I have commented this code because of I have 2 monitors
        // so If application located at 1st monitor
        // message box can appear at second one.

        /*
        ptStart.X = (ptStart.X < 0) ? 0 : ptStart.X;
        ptStart.Y = (ptStart.Y < 0) ? 0 : ptStart.Y;
        */

        int result = MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width,
                                height, false);

    }


}

MessageBox Buttons?

If you actually want Yes and No buttons (and assuming WinForms):

void button_Click(object sender, EventArgs e)
{
    var message = "Yes or No?";
    var title = "Hey!";
    var result = MessageBox.Show(
        message,                  // the message to show
        title,                    // the title for the dialog box
        MessageBoxButtons.YesNo,  // show two buttons: Yes and No
        MessageBoxIcon.Question); // show a question mark icon

    // the following can be handled as if/else statements as well
    switch (result)
    {
    case DialogResult.Yes:   // Yes button pressed
        MessageBox.Show("You pressed Yes!");
        break;
    case DialogResult.No:    // No button pressed
        MessageBox.Show("You pressed No!");
        break;
    default:                 // Neither Yes nor No pressed (just in case)
        MessageBox.Show("What did you press?");
        break;
    }
}

Close a MessageBox after several seconds

DMitryG's code "get the return value of the underlying MessageBox" has a bug so the timerResult is never actually correctly returned (MessageBox.Show call returns AFTER OnTimerElapsed completes). My fix is below:

public class TimedMessageBox {
    System.Threading.Timer _timeoutTimer;
    string _caption;
    DialogResult _result;
    DialogResult _timerResult;
    bool timedOut = false;

    TimedMessageBox(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None)
    {
        _caption = caption;
        _timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
            null, timeout, System.Threading.Timeout.Infinite);
        _timerResult = timerResult;
        using(_timeoutTimer)
            _result = MessageBox.Show(text, caption, buttons);
        if (timedOut) _result = _timerResult;
    }

    public static DialogResult Show(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None) {
        return new TimedMessageBox(text, caption, timeout, buttons, timerResult)._result;
    }

    void OnTimerElapsed(object state) {
        IntPtr mbWnd = FindWindow("#32770", _caption); // lpClassName is #32770 for MessageBox
        if(mbWnd != IntPtr.Zero)
            SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
        _timeoutTimer.Dispose();
        timedOut = true;
    }

    const int WM_CLOSE = 0x0010;
    [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}

Show a message box from a class in c#?

System.Windows.MessageBox.Show("Hello world"); //WPF
System.Windows.Forms.MessageBox.Show("Hello world"); //WinForms

HTML - Alert Box when loading page

you need a tiny bit of Javascript.

<script type="text/javascript">
window.onload = function(){ 
                alert("Hi there");
                }
</script>

This is only slightly different from Adam's answer. The effective difference is that this one alerts when the browser considers the page fully loaded, while Adam's alerts when the browser scans part the <script> tag in the text. The difference is with, for example, images, which may continue loading in parallel for a while.

Is there a MessageBox equivalent in WPF?

The equivalent to WinForms' MessageBox in WPF is called System.Windows.MessageBox.

How to add message box with 'OK' button?

The code compiles ok for me. May be you have forgotten to add the import:

import android.app.AlertDialog;

Anyway, you have a good tutorial here.

ASP.NET Web Application Message Box

Just for the records.

Here is a link from Microsoft that I think is the best way to present a MessageBox in ASP.Net

Also it presents choices like Yes and NO.

Instructions on how to get the class from the link working on your project:

  1. If you don't have an App_Code folder on your Project, create it.
  2. Right click the App_Code folder and create a Class. Name it MessageBox.cs
  3. Copy the text from the MessageBox.cs file (from the attached code) and paste it on your MessageBox.cs file.
  4. Do the same as steps 2 & 3 for the MessageBoxCore.cs file.
  5. Important: Right click each file MessageBox.cs and MessageBoxCore.cs and make sure the 'Build Action' is set to Compile
  6. Add this code to your aspx page where you want to display the message box:

    <asp:Literal ID="PopupBox" runat="server"></asp:Literal>
    
  7. Add this code on you cs page where you want to decision to be made:

    string title = "My box title goes here";
    string text = "Do you want to Update this record?";
    MessageBox messageBox = new MessageBox(text, title, MessageBox.MessageBoxIcons.Question, MessageBox.MessageBoxButtons.YesOrNo, MessageBox.MessageBoxStyle.StyleA);
    messageBox.SuccessEvent.Add("YesModClick");
    PopupBox.Text = messageBox.Show(this);
    
  8. Add this method to your cs page. This is what will be executed when the user clicks Yes. You don't need to make another one for the NoClick method.

    [WebMethod]
    public static string YesModClick(object sender, EventArgs e)
    {
        string strToRtn = "";
        // The code that you want to execute when the user clicked yes goes here
        return strToRtn;
    }
    
  9. Add a WebUserControl1.ascx file to your root path and add this code to the file:

    <link href="~/Styles/MessageBox.css" rel="stylesheet" type="text/css" />
    <div id="result"></div>
    <asp:ScriptManager runat="server" ID="scriptManager" EnablePageMethods="True">
    </asp:ScriptManager>  //<-- Make sure you only have one ScriptManager on your aspx page.  Remove the one on your aspx page if you already have one.
    
  10. Add this line on top of your aspx page:

    <%@ Register src="~/MessageBoxUserControl.ascx" tagname="MessageBoxUserControl" tagprefix="uc1" %>
    
  11. Add this line inside your aspx page (Inside your asp:Content tag if you have one)

    <uc1:MessageBoxUserControl ID="MessageBoxUserControl1" runat="server" />
    
  12. Save the image files 1.jpg, 2.jpg, 3.jpg, 4.jpg from the Microsoft project above into your ~/Images/ path.

  13. Done

Hope it helps.

Pablo

Show a popup/message box from a Windows batch file

In order to do this, you need to have a small program that displays a messagebox and run that from your batch file.

You could open a console window that displays a prompt though, but getting a GUI message box using cmd.exe and friends only is not possible, AFAIK.

VBA code to show Message Box popup if the formula in the target cell exceeds a certain value

Essentially you want to add code to the Calculate event of the relevant Worksheet.

In the Project window of the VBA editor, double-click the sheet you want to add code to and from the drop-downs at the top of the editor window, choose 'Worksheet' and 'Calculate' on the left and right respectively.

Alternatively, copy the code below into the editor of the sheet you want to use:

Private Sub Worksheet_Calculate()

If Sheets("MySheet").Range("A1").Value > 0.5 Then
    MsgBox "Over 50%!", vbOKOnly
End If

End Sub

This way, every time the worksheet recalculates it will check to see if the value is > 0.5 or 50%.

MessageBox with YesNoCancel - No & Cancel triggers same event

dim result as dialogresult
result = MessageBox.Show("message", "caption", MessageBoxButtons.YesNoCancel)
If result = DialogResult.Cancel Then
    MessageBox.Show("Cancel pressed")
ElseIf result = DialogResult.No Then
    MessageBox.Show("No pressed")
ElseIf result = DialogResult.Yes Then
    MessageBox.Show("Yes pressed")
End If

How to customize message box

Here is the code needed to create your own message box:

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

namespace MyStuff
{
    public class MyLabel : Label
    {
        public static Label Set(string Text = "", Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
        {
            Label l = new Label();
            l.Text = Text;
            l.Font = (Font == null) ? new Font("Calibri", 12) : Font;
            l.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
            l.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
            l.AutoSize = true;
            return l;
        }
    }
    public class MyButton : Button
    {
        public static Button Set(string Text = "", int Width = 102, int Height = 30, Font Font = null, Color ForeColor = new Color(), Color BackColor = new Color())
        {
            Button b = new Button();
            b.Text = Text;
            b.Width = Width;
            b.Height = Height;
            b.Font = (Font == null) ? new Font("Calibri", 12) : Font;
            b.ForeColor = (ForeColor == new Color()) ? Color.Black : ForeColor;
            b.BackColor = (BackColor == new Color()) ? SystemColors.Control : BackColor;
            b.UseVisualStyleBackColor = (b.BackColor == SystemColors.Control);
            return b;
        }
    }
    public class MyImage : PictureBox
    {
        public static PictureBox Set(string ImagePath = null, int Width = 60, int Height = 60)
        {
            PictureBox i = new PictureBox();
            if (ImagePath != null)
            {
                i.BackgroundImageLayout = ImageLayout.Zoom;
                i.Location = new Point(9, 9);
                i.Margin = new Padding(3, 3, 2, 3);
                i.Size = new Size(Width, Height);
                i.TabStop = false;
                i.Visible = true;
                i.BackgroundImage = Image.FromFile(ImagePath);
            }
            else
            {
                i.Visible = true;
                i.Size = new Size(0, 0);
            }
            return i;
        }
    }
    public partial class MyMessageBox : Form
    {
        private MyMessageBox()
        {
            this.panText = new FlowLayoutPanel();
            this.panButtons = new FlowLayoutPanel();
            this.SuspendLayout();
            // 
            // panText
            // 
            this.panText.Parent = this;
            this.panText.AutoScroll = true;
            this.panText.AutoSize = true;
            this.panText.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            //this.panText.Location = new Point(90, 90);
            this.panText.Margin = new Padding(0);
            this.panText.MaximumSize = new Size(500, 300);
            this.panText.MinimumSize = new Size(108, 50);
            this.panText.Size = new Size(108, 50);
            // 
            // panButtons
            // 
            this.panButtons.AutoSize = true;
            this.panButtons.AutoSizeMode = AutoSizeMode.GrowAndShrink;
            this.panButtons.FlowDirection = FlowDirection.RightToLeft;
            this.panButtons.Location = new Point(89, 89);
            this.panButtons.Margin = new Padding(0);
            this.panButtons.MaximumSize = new Size(580, 150);
            this.panButtons.MinimumSize = new Size(108, 0);
            this.panButtons.Size = new Size(108, 35);
            // 
            // MyMessageBox
            // 
            this.AutoScaleDimensions = new SizeF(8F, 19F);
            this.AutoScaleMode = AutoScaleMode.Font;
            this.ClientSize = new Size(206, 133);
            this.Controls.Add(this.panButtons);
            this.Controls.Add(this.panText);
            this.Font = new Font("Calibri", 12F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(0)));
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.Margin = new Padding(4);
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.MinimumSize = new Size(168, 132);
            this.Name = "MyMessageBox";
            this.ShowIcon = false;
            this.ShowInTaskbar = false;
            this.StartPosition = FormStartPosition.CenterScreen;
            this.ResumeLayout(false);
            this.PerformLayout();
        }
        public static string Show(Label Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
        {
            List<Label> Labels = new List<Label>();
            Labels.Add(Label);
            return Show(Labels, Title, Buttons, Image);
        }
        public static string Show(string Label, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
        {
            List<Label> Labels = new List<Label>();
            Labels.Add(MyLabel.Set(Label));
            return Show(Labels, Title, Buttons, Image);
        }
        public static string Show(List<Label> Labels = null, string Title = "", List<Button> Buttons = null, PictureBox Image = null)
        {
            if (Labels == null) Labels = new List<Label>();
            if (Labels.Count == 0) Labels.Add(MyLabel.Set(""));
            if (Buttons == null) Buttons = new List<Button>();
            if (Buttons.Count == 0) Buttons.Add(MyButton.Set("OK"));
            List<Button> buttons = new List<Button>(Buttons);
            buttons.Reverse();

            int ImageWidth = 0;
            int ImageHeight = 0;
            int LabelWidth = 0;
            int LabelHeight = 0;
            int ButtonWidth = 0;
            int ButtonHeight = 0;
            int TotalWidth = 0;
            int TotalHeight = 0;

            MyMessageBox mb = new MyMessageBox();

            mb.Text = Title;

            //Image
            if (Image != null)
            {
                mb.Controls.Add(Image);
                Image.MaximumSize = new Size(150, 300);
                ImageWidth = Image.Width + Image.Margin.Horizontal;
                ImageHeight = Image.Height + Image.Margin.Vertical;
            }

            //Labels
            List<int> il = new List<int>();
            mb.panText.Location = new Point(9 + ImageWidth, 9);
            foreach (Label l in Labels)
            {
                mb.panText.Controls.Add(l);
                l.Location = new Point(200, 50);
                l.MaximumSize = new Size(480, 2000);
                il.Add(l.Width);
            }
            int mw = Labels.Max(x => x.Width);
            il.ToString();
            Labels.ForEach(l => l.MinimumSize = new Size(Labels.Max(x => x.Width), 1));
            mb.panText.Height = Labels.Sum(l => l.Height);
            mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
            mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
            LabelWidth = mb.panText.Width;
            LabelHeight = mb.panText.Height;

            //Buttons
            foreach (Button b in buttons)
            {
                mb.panButtons.Controls.Add(b);
                b.Location = new Point(3, 3);
                b.TabIndex = Buttons.FindIndex(i => i.Text == b.Text);
                b.Click += new EventHandler(mb.Button_Click);
            }
            ButtonWidth = mb.panButtons.Width;
            ButtonHeight = mb.panButtons.Height;

            //Set Widths
            if (ButtonWidth > ImageWidth + LabelWidth)
            {
                Labels.ForEach(l => l.MinimumSize = new Size(ButtonWidth - ImageWidth - mb.ScrollBarWidth(Labels), 1));
                mb.panText.Height = Labels.Sum(l => l.Height);
                mb.panText.MinimumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), ImageHeight);
                mb.panText.MaximumSize = new Size(Labels.Max(x => x.Width) + mb.ScrollBarWidth(Labels), 300);
                LabelWidth = mb.panText.Width;
                LabelHeight = mb.panText.Height;
            }
            TotalWidth = ImageWidth + LabelWidth;

            //Set Height
            TotalHeight = LabelHeight + ButtonHeight;

            mb.panButtons.Location = new Point(TotalWidth - ButtonWidth + 9, mb.panText.Location.Y + mb.panText.Height);

            mb.Size = new Size(TotalWidth + 25, TotalHeight + 47);
            mb.ShowDialog();
            return mb.Result;
        }

        private FlowLayoutPanel panText;
        private FlowLayoutPanel panButtons;
        private int ScrollBarWidth(List<Label> Labels)
        {
            return (Labels.Sum(l => l.Height) > 300) ? 23 : 6;
        }

        private void Button_Click(object sender, EventArgs e)
        {
            Result = ((Button)sender).Text;
            Close();
        }

        private string Result = "";
    }
}   

C# MessageBox dialog result

You can also do it in one row:

if (MessageBox.Show("Text", "Title", MessageBoxButtons.YesNo) == DialogResult.Yes)

And if you want to show a messagebox on top:

if (MessageBox.Show(new Form() { TopMost = true }, "Text", "Text", MessageBoxButtons.YesNo) == DialogResult.Yes)

How to get text and a variable in a messagebox

As has been suggested, using the string.format method is nice and simple and very readable.

In vb.net the " + " is used for addition and the " & " is used for string concatenation.

In your example:

MsgBox("Variable = " + variable)

becomes:

MsgBox("Variable = " & variable)

I may have been a bit quick answering this as it appears these operators can both be used for concatenation, but recommended use is the "&", source http://msdn.microsoft.com/en-us/library/te2585xw(v=VS.100).aspx

maybe call

variable.ToString()

update:

Use string interpolation (vs2015 onwards I believe):

MsgBox($"Variable = {variable}")

How to get DataGridView cell value in messagebox?

   private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        MessageBox.Show(Convert.ToString(dataGridView1.CurrentCell.Value));
    }

a bit late but hope it helps

How to change the button text for 'Yes' and 'No' buttons in the MessageBox.Show dialog?

This may not be the prettiest, but if you don't want to use the MessageBoxManager, (which is awesome):

 public static DialogResult DialogBox(string title, string promptText, ref string value, string button1 = "OK", string button2 = "Cancel", string button3 = null)
    {
        Form form = new Form();
        Label label = new Label();
        TextBox textBox = new TextBox();
        Button button_1 = new Button();
        Button button_2 = new Button();
        Button button_3 = new Button();

        int buttonStartPos = 228; //Standard two button position


        if (button3 != null)
            buttonStartPos = 228 - 81;
        else
        {
            button_3.Visible = false;
            button_3.Enabled = false;
        }


        form.Text = title;

        // Label
        label.Text = promptText;
        label.SetBounds(9, 20, 372, 13);
        label.Font = new Font("Microsoft Tai Le", 10, FontStyle.Regular);

        // TextBox
        if (value == null)
        {
        }
        else
        {
            textBox.Text = value;
            textBox.SetBounds(12, 36, 372, 20);
            textBox.Anchor = textBox.Anchor | AnchorStyles.Right;
        }

        button_1.Text = button1;
        button_2.Text = button2;
        button_3.Text = button3 ?? string.Empty;
        button_1.DialogResult = DialogResult.OK;
        button_2.DialogResult = DialogResult.Cancel;
        button_3.DialogResult = DialogResult.Yes;


        button_1.SetBounds(buttonStartPos, 72, 75, 23);
        button_2.SetBounds(buttonStartPos + 81, 72, 75, 23);
        button_3.SetBounds(buttonStartPos + (2 * 81), 72, 75, 23);

        label.AutoSize = true;
        button_1.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
        button_2.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
        button_3.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;

        form.ClientSize = new Size(396, 107);
        form.Controls.AddRange(new Control[] { label, button_1, button_2 });
        if (button3 != null)
            form.Controls.Add(button_3);
        if (value != null)
            form.Controls.Add(textBox);

        form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height);
        form.FormBorderStyle = FormBorderStyle.FixedDialog;
        form.StartPosition = FormStartPosition.CenterScreen;
        form.MinimizeBox = false;
        form.MaximizeBox = false;
        form.AcceptButton = button_1;
        form.CancelButton = button_2;

        DialogResult dialogResult = form.ShowDialog();
        value = textBox.Text;
        return dialogResult;
    }

Sqlite convert string to date

As Sqlite doesn't have a date type you will need to do string comparison to achieve this. For that to work you need to reverse the order - eg from dd/MM/yyyy to yyyyMMdd, using something like

where substr(column,7)||substr(column,4,2)||substr(column,1,2) 
      between '20101101' and '20101130'

VBA Excel sort range by specific column

Or this:

Range("A2", Range("D" & Rows.Count).End(xlUp).Address).Sort Key1:=[b3], _
    Order1:=xlAscending, Header:=xlYes

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

How can I check for existence of element in std::vector, in one line?

Unsorted vector:

if (std::find(v.begin(), v.end(),value)!=v.end())
    ...

Sorted vector:

if (std::binary_search(v.begin(), v.end(), value)
   ...

P.S. may need to include <algorithm> header

JS strings "+" vs concat method

MDN has the following to say about string.concat():

It is strongly recommended to use the string concatenation operators (+, +=) instead of this method for perfomance reasons

Also see the link by @Bergi.

How does the "view" method work in PyTorch?

I really liked @Jadiel de Armas examples.

I would like to add a small insight to how elements are ordered for .view(...)

  • For a Tensor with shape (a,b,c), the order of it's elements are determined by a numbering system: where the first digit has a numbers, second digit has b numbers and third digit has c numbers.
  • The mapping of the elements in the new Tensor returned by .view(...) preserves this order of the original Tensor.

Python Pandas: Get index of rows which column matches certain value

Can be done using numpy where() function:

import pandas as pd
import numpy as np

In [716]: df = pd.DataFrame({"gene_name": ['SLC45A1', 'NECAP2', 'CLIC4', 'ADC', 'AGBL4'] , "BoolCol": [False, True, False, True, True] },
       index=list("abcde"))

In [717]: df
Out[717]: 
  BoolCol gene_name
a   False   SLC45A1
b    True    NECAP2
c   False     CLIC4
d    True       ADC
e    True     AGBL4

In [718]: np.where(df["BoolCol"] == True)
Out[718]: (array([1, 3, 4]),)

In [719]: select_indices = list(np.where(df["BoolCol"] == True)[0])

In [720]: df.iloc[select_indices]
Out[720]: 
  BoolCol gene_name
b    True    NECAP2
d    True       ADC
e    True     AGBL4

Though you don't always need index for a match, but incase if you need:

In [796]: df.iloc[select_indices].index
Out[796]: Index([u'b', u'd', u'e'], dtype='object')

In [797]: df.iloc[select_indices].index.tolist()
Out[797]: ['b', 'd', 'e']

Vertical and horizontal align (middle and center) with CSS

There are many methods :

  1. Center horizontal and vertical align of an element with fixed measure

CSS

 <div style="width:200px;height:100px;position:absolute;left:50%;top:50%;
margin-left:-100px;margin-top:-50px;">
<!–content–>
</div> 

2 . Center horizontally and vertically a single line of text

CSS

<div style="width:400px;height:200px;text-align:center;line-height:200px;">
<!–content–>
</div>  

3 . Center horizontal and vertical align of an element with no specific measure

CSS

<div style="display:table;height:300px;text-align:center;">
<div style="display:table-cell;vertical-align:middle;">
<!–content–>
</div>
</div>  

Return rows in random order

The usual method is to use the NEWID() function, which generates a unique GUID. So,

SELECT * FROM dbo.Foo ORDER BY NEWID();

How to debug a Flask app

You can use app.run(debug=True) for the Werkzeug Debugger edit as mentioned below, and I should have known.

ModelState.IsValid == false, why?

bool hasErrors =  ViewData.ModelState.Values.Any(x => x.Errors.Count > 1);

or iterate with

    foreach (ModelState state in ViewData.ModelState.Values.Where(x => x.Errors.Count > 0))
    {

    }

How to make Bootstrap 4 cards the same height in card-columns?

Another useful approach is Card Grids:

_x000D_
_x000D_
<div class="row row-cols-1 row-cols-md-2">_x000D_
  <div class="col mb-4">_x000D_
    <div class="card">_x000D_
      <img src="..." class="card-img-top" alt="...">_x000D_
      <div class="card-body">_x000D_
        <h5 class="card-title">Card title</h5>_x000D_
        <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="col mb-4">_x000D_
    <div class="card">_x000D_
      <img src="..." class="card-img-top" alt="...">_x000D_
      <div class="card-body">_x000D_
        <h5 class="card-title">Card title</h5>_x000D_
        <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="col mb-4">_x000D_
    <div class="card">_x000D_
      <img src="..." class="card-img-top" alt="...">_x000D_
      <div class="card-body">_x000D_
        <h5 class="card-title">Card title</h5>_x000D_
        <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content.</p>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="col mb-4">_x000D_
    <div class="card">_x000D_
      <img src="..." class="card-img-top" alt="...">_x000D_
      <div class="card-body">_x000D_
        <h5 class="card-title">Card title</h5>_x000D_
        <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How would one write object-oriented code in C?

Of course, it just won't be as pretty as using a language with built-in support. I've even written "object-oriented assembler".

Read only file system on Android

On my Samsung galaxy mini S5570 (after got root on cellphone):

Fist, as root, I ran:

systemctl start adb

as a normal user:

adb shell 
su 

Grant root permissions on touch screen

mount 

list all mount points that we have and we can see, in my case, that /dev/stl12 was mounted on /system as ro (ready only), so we just need do:

mount -o rw,remount /dev/stl12 /system

Unable to open debugger port in IntelliJ

Your Service/ Application might already be running. In Search enter Services and you will get list of services. Stop yours and then try again.

How might I find the largest number contained in a JavaScript array?

Try this

function largestNum(arr) {
  var currentLongest = arr[0]

  for (var i=0; i< arr.length; i++){
    if (arr[i] > currentLongest){
      currentLongest = arr[i]
    }
  }

  return currentLongest
}

What are functional interfaces used for in Java 8?

A lambda expression can be assigned to a functional interface type, but so can method references, and anonymous classes.

One nice thing about the specific functional interfaces in java.util.function is that they can be composed to create new functions (like Function.andThen and Function.compose, Predicate.and, etc.) due to the handy default methods they contain.

Why ModelState.IsValid always return false in mvc

"ModelState.IsValid" tells you that the model is consumed by the view (i.e. PaymentAdviceEntity) is satisfy all types of validation or not specified in the model properties by DataAnotation.

In this code the view does not bind any model properties. So if you put any DataAnotations or validation in model (i.e. PaymentAdviceEntity). then the validations are not satisfy. say if any properties in model is Name which makes required in model.Then the value of the property remains blank after post.So the model is not valid (i.e. ModelState.IsValid returns false). You need to remove the model level validations.

Check if Internet Connection Exists with jQuery?

I wrote a jQuery plugin for doing this. By default it checks the current URL (because that's already loaded once from the Web) or you can specify a URL to use as an argument. Always doing a request to Google isn't the best idea because it's blocked in different countries at different times. Also you might be at the mercy of what the connection across a particular ocean/weather front/political climate might be like that day.

http://tomriley.net/blog/archives/111

Sort objects in an array alphabetically on one property of the array

objArray.sort( (a, b) => a.id.localeCompare(b.id, 'en', {'sensitivity': 'base'}));

This sorts them alphabetically AND is case insensitive. It's also super clean and easy to read :D

Issue with background color in JavaFX 8

Try this one in your css document,

-fx-background-color : #ffaadd;

or

-fx-base : #ffaadd; 

Also, you can set background color on your object with this code directly.

yourPane.setBackground(new Background(new BackgroundFill(Color.DARKGREEN, CornerRadii.EMPTY, Insets.EMPTY)));

How to delete object?

You can proxyfy references to your object with, for example, dictionary singleton. You may store not object, but its ID or hash and access it trought the dictionary. Then when you need to remove the object you set value for its key to null.

How do I get a specific range of numbers from rand()?

double scale = 1.0 / ((double) RAND_MAX + 1.0);
int min, max;
...
rval = (int)(rand() * scale * (max - min + 1) + min);

How to permanently export a variable in Linux?

If it suits anyone, here are some brief guidelines for adding environment variables permanently.

vi ~/.bash_profile

Add the variables to the file:

export DISPLAY=:0
export JAVA_HOME=~/opt/openjdk11

Immediately apply all changes:

source ~/.bash_profile

Source: https://www.serverlab.ca/tutorials/linux/administration-linux/how-to-set-environment-variables-in-linux/

How to combine two lists in R

I was looking to do the same thing, but to preserve the list as a just an array of strings so I wrote a new code, which from what I've been reading may not be the most efficient but worked for what i needed to do:

combineListsAsOne <-function(list1, list2){
  n <- c()
  for(x in list1){
    n<-c(n, x)
  }
  for(y in list2){
    n<-c(n, y)
  }
  return(n)
}

It just creates a new list and adds items from two supplied lists to create one.

How to execute .sql file using powershell?

Here is a function that I have in my PowerShell profile for loading SQL snapins:

function Load-SQL-Server-Snap-Ins
{
    try 
    {
        $sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"

        if (!(Test-Path $sqlpsreg -ErrorAction "SilentlyContinue"))
        {
            throw "SQL Server Powershell is not installed yet (part of SQLServer installation)."
        }

        $item = Get-ItemProperty $sqlpsreg
        $sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)

        $assemblyList = @(
            "Microsoft.SqlServer.Smo",
            "Microsoft.SqlServer.SmoExtended",
            "Microsoft.SqlServer.Dmf",
            "Microsoft.SqlServer.WmiEnum",
            "Microsoft.SqlServer.SqlWmiManagement",
            "Microsoft.SqlServer.ConnectionInfo ",
            "Microsoft.SqlServer.Management.RegisteredServers",
            "Microsoft.SqlServer.Management.Sdk.Sfc",
            "Microsoft.SqlServer.SqlEnum",
            "Microsoft.SqlServer.RegSvrEnum",
            "Microsoft.SqlServer.ServiceBrokerEnum",
            "Microsoft.SqlServer.ConnectionInfoExtended",
            "Microsoft.SqlServer.Management.Collector",
            "Microsoft.SqlServer.Management.CollectorEnum"
        )

        foreach ($assembly in $assemblyList)
        { 
            $assembly = [System.Reflection.Assembly]::LoadWithPartialName($assembly) 
            if ($assembly -eq $null)
                { Write-Host "`t`t($MyInvocation.InvocationName): Could not load $assembly" }
        }

        Set-Variable -scope Global -name SqlServerMaximumChildItems -Value 0
        Set-Variable -scope Global -name SqlServerConnectionTimeout -Value 30
        Set-Variable -scope Global -name SqlServerIncludeSystemObjects -Value $false
        Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000

        Push-Location

         if ((Get-PSSnapin -Name SqlServerProviderSnapin100 -ErrorAction SilentlyContinue) -eq $null) 
        { 
            cd $sqlpsPath

            Add-PsSnapin SqlServerProviderSnapin100 -ErrorAction Stop
            Add-PsSnapin SqlServerCmdletSnapin100 -ErrorAction Stop
            Update-TypeData -PrependPath SQLProvider.Types.ps1xml
            Update-FormatData -PrependPath SQLProvider.Format.ps1xml
        }
    } 

    catch 
    {
        Write-Host "`t`t$($MyInvocation.InvocationName): $_" 
    }

    finally
    {
        Pop-Location
    }
}

update to python 3.7 using anaconda

Python 3.7 is now available to be installed, but many packages have not been updated yet. As noted by another answer here, there is a GitHub issue tracking the progress of Anaconda building all the updated packages.


Until someone creates a conda package for Python 3.7, you can't install it. Unfortunately, something like 3500 packages show up in a search for "python" on Anaconda.org (https://anaconda.org/search?q=%22python%22) so I couldn't see if anyone has done that yet.

You might be able to build your own package, depending on what OS you want it for. You can start with the recipe that conda-forge uses to build Python: https://github.com/conda-forge/python-feedstock/

In the past, I think Continuum have generally waited until a stable release to push out packages for new Pythons, but I don't work there, so I don't know what their actual policy is.

Find all files in a directory with extension .txt in Python

You can simply use pathlibs glob 1:

import pathlib

list(pathlib.Path('your_directory').glob('*.txt'))

or in a loop:

for txt_file in pathlib.Path('your_directory').glob('*.txt'):
    # do something with "txt_file"

If you want it recursive you can use .glob('**/*.txt)


1The pathlib module was included in the standard library in python 3.4. But you can install back-ports of that module even on older Python versions (i.e. using conda or pip): pathlib and pathlib2.

Android RatingBar change star colors

Withou adding a new style you can use the tint color within the RatingBar

             <RatingBar
                    android:id="@+id/ratingBar"
                    style="@android:style/Widget.Holo.RatingBar.Small"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:numStars="5"
                    android:rating="4.5"
                    android:stepSize="0.5"
                    android:progressTint="@color/colorPrimary"/>

How do I display local image in markdown?

Either put the image in the same folder as the markdown file or use a relative path to the image.

Correct way to populate an Array with a Range in Ruby

Sounds like you're doing this:

0..10.to_a

The warning is from Fixnum#to_a, not from Range#to_a. Try this instead:

(0..10).to_a

How to remove listview all items

You can do this:

listView.setAdapter(null);

Random shuffling of an array

Here is a solution using Apache Commons Math 3.x (for int[] arrays only):

MathArrays.shuffle(array);

http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/util/MathArrays.html#shuffle(int[])

Alternatively, Apache Commons Lang 3.6 introduced new shuffle methods to the ArrayUtils class (for objects and any primitive type).

ArrayUtils.shuffle(array);

http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/ArrayUtils.html#shuffle-int:A-

Best practices for styling HTML emails

I find that image mapping works pretty well. If you have any headers or footers that are images make sure that you apply a bgcolor="fill in the blank" because outlook in most cases wont load the image and you will be left with a transparent header. If you at least designate a color that works with the over all feel of the email it will be less of a shock for the user. Never try and use any styling sheets. Or CSS at all! Just avoid it.

Depending if you're copying content from a word or shared google Doc be sure to (command+F) Find all the (') and (") and replace them within your editing software (especially dreemweaver) because they will show up as code and it's just not good.

ALT is your best friend. use the ALT tag to add in text to all your images. Because odds are they are not going to load right. And that ALT text is what gets people to click the (see images) button. Also define your images Width, Height and make the boarder 0 so you dont get weird lines around your image.

Consider editing all images within Photoshop with a 15px boarder on each side (make background transparent and save as a PNG 24) of image. Sometimes the email clients do not read any padding styles that you apply to the images so it avoids any weird formatting!

Also i found the line under links particularly annoying so if you apply < style="text-decoration:none; color:#whatever color you want here!" > it will remove the line and give you the desired look.

There is alot that can really mess with the over all look and feel.

How to create a Calendar table for 100 years in Sql

This will create you the result in lightning fast.

select top 100000  identity (int ,1,1) as Sequence into Tally from sysobjects , sys.all_columns


select dateadd(dd,sequence,-1) Dates into CalenderTable from tally


delete from CalenderTable where dates < -- mention the mindate you need
delete from CalenderTable where dates >  -- mention the max date you need

Step 1 : Create a sequence table

Step 2 : Use the sequence table to generate the desired dates

Step 3 : Delete unwanted dates

How to call a shell script from python code?

Subprocess module is a good module to launch subprocesses. You can use it to call shell commands as this:

subprocess.call(["ls","-l"]);
#basic syntax
#subprocess.call(args, *)

You can see its documentation here.

If you have your script written in some .sh file or a long string, then you can use os.system module. It is fairly simple and easy to call:

import os
os.system("your command here")
# or
os.system('sh file.sh')

This command will run the script once, to completion, and block until it exits.

Convert HTML string to image

Try the following:

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

class Program
{
    static void Main(string[] args)
    {
        var source =  @"
        <!DOCTYPE html>
        <html>
            <body>
                <p>An image from W3Schools:</p>
                <img 
                    src=""http://www.w3schools.com/images/w3schools_green.jpg"" 
                    alt=""W3Schools.com"" 
                    width=""104"" 
                    height=""142"">
            </body>
        </html>";
        StartBrowser(source);
        Console.ReadLine();
    }

    private static void StartBrowser(string source)
    {
        var th = new Thread(() =>
        {
            var webBrowser = new WebBrowser();
            webBrowser.ScrollBarsEnabled = false;
            webBrowser.DocumentCompleted +=
                webBrowser_DocumentCompleted;
            webBrowser.DocumentText = source;
            Application.Run();
        });
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
    }

    static void 
        webBrowser_DocumentCompleted(
        object sender, 
        WebBrowserDocumentCompletedEventArgs e)
    {
        var webBrowser = (WebBrowser)sender;
        using (Bitmap bitmap = 
            new Bitmap(
                webBrowser.Width, 
                webBrowser.Height))
        {
            webBrowser
                .DrawToBitmap(
                bitmap, 
                new System.Drawing
                    .Rectangle(0, 0, bitmap.Width, bitmap.Height));
            bitmap.Save(@"filename.jpg", 
                System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}

Note: Credits should go to Hans Passant for his excellent answer on the question WebBrowser Control in a new thread which inspired this solution.

SQL Server function to return minimum date (January 1, 1753)

Have you seen the SqlDateTime object? use SqlDateTime.MinValue to get your minimum date (Jan 1 1753).

Sending websocket ping/pong frame from browser

Ping is meant to be sent only from server to client, and browser should answer as soon as possible with Pong OpCode, automatically. So you have not to worry about that on higher level.

Although that not all browsers support standard as they suppose to, they might have some differences in implementing such mechanism, and it might even means there is no Pong response functionality. But personally I am using Ping / Pong, and never saw client that does not implement this type of OpCode and automatic response on low level client side implementation.

How can I make a CSS glass/blur effect work for an overlay?

Here's a solution that works with fixed backgrounds, if you have a fixed background and you have some overlayed elements and you need blured backgrounds for them, this solution works:

Image we have this simple HTML:

<body> <!-- or any wrapper -->
   <div class="content">Some Texts</div>
</body>

A fixed background for <body> or the wrapper element:

body {
  background-image: url(http://placeimg.com/640/360/any);
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed;
}

And here for example we have a overlayed element with a white transparent background:

.content {
  background-color: rgba(255, 255, 255, 0.3);
  position: relative;
}

Now we need to use the exact same background image of our wrapper for our overlay elements too, i use it as a :before psuedo-class:

.content:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  filter: blur(5px);
  background-image: url(http://placeimg.com/640/360/any);
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed;
}

Since the fixed background works in a same way in both wrapper and overlayed elements, we have the background in exactly same scroll position of the overlayed element and we can simply blur it. Here's a working fiddle, tested in Firefox, Chrome, Opera and Edge: https://jsfiddle.net/0vL2rc4d/

NOTE: In firefox there's a bug that makes screen flicker when scrolling and there are fixed blurred backgrounds. if there's any fix, let me know

Android: adb pull file on desktop

do adb pull \sdcard\log.txt C:Users\admin\Desktop

How can I sanitize user input with PHP?

You never sanitize input.

You always sanitize output.

The transforms you apply to data to make it safe for inclusion in an SQL statement are completely different from those you apply for inclusion in HTML are completely different from those you apply for inclusion in Javascript are completely different from those you apply for inclusion in LDIF are completely different from those you apply to inclusion in CSS are completely different from those you apply to inclusion in an Email....

By all means validate input - decide whether you should accept it for further processing or tell the user it is unacceptable. But don't apply any change to representation of the data until it is about to leave PHP land.

A long time ago someone tried to invent a one-size fits all mechanism for escaping data and we ended up with "magic_quotes" which didn't properly escape data for all output targets and resulted in different installation requiring different code to work.

How do I get the web page contents from a WebView?

I know this is a late answer, but I found this question because I had the same problem. I think I found the answer in this post on lexandera.com. The code below is basically a cut-and-paste from the site. It seems to do the trick.

final Context myApp = this;

/* An instance of this class will be registered as a JavaScript interface */
class MyJavaScriptInterface
{
    @JavascriptInterface
    @SuppressWarnings("unused")
    public void processHTML(String html)
    {
        // process the html as needed by the app
    }
}

final WebView browser = (WebView)findViewById(R.id.browser);
/* JavaScript must be enabled if you want it to work, obviously */
browser.getSettings().setJavaScriptEnabled(true);

/* Register a new JavaScript interface called HTMLOUT */
browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");

/* WebViewClient must be set BEFORE calling loadUrl! */
browser.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url)
    {
        /* This call inject JavaScript into the page which just finished loading. */
        browser.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
    }
});

/* load a web page */
browser.loadUrl("http://lexandera.com/files/jsexamples/gethtml.html");

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

Hi you can make something like this:

  1. Create class which implements AsyncTask

    // TASK 
    public class SomeClass extends AsyncTask<Void, Void, String>>
    {
    
        private OnTaskExecutionFinished _task_finished_event;
    
        public interface OnTaskExecutionFinished
        {
            public void OnTaskFihishedEvent(String Reslut);
        }
    
        public void setOnTaskFinishedEvent(OnTaskExecutionFinished _event)
        {
            if(_event != null)
            {
                this._task_finished_event = _event;
            }
        }
    
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
    
        }
    
        @Override
        protected String doInBackground(Void... params)
        {
            // do your background task here ...
    
            return "Done!";
        }
    
        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);
            if(this._task_finished_event != null)
            {
                this._task_finished_event.OnTaskFihishedEvent(result);
            }
            else
            {
                Log.d("SomeClass", "task_finished even is null");
            }
        }
    }
    
  2. Add in Main Activity

    // MAIN ACTIVITY
    public class MyActivity extends ListActivity
    {
       ...
        SomeClass _some_class = new SomeClass();
        _someclass.setOnTaskFinishedEvent(new _some_class.OnTaskExecutionFinished()
        {
        @Override
        public void OnTaskFihishedEvent(String result)
        {
            Toast.makeText(getApplicationContext(),
                    "Phony thread finished: " + result,
                    Toast.LENGTH_SHORT).show();
        }
    
       });
       _some_class.execute();
       ...
     }
    

Add 'x' number of hours to date

   $now = date("Y-m-d H:i:s");
   date("Y-m-d H:i:s", strtotime("+1 hours $now"));

How exactly does <script defer="defer"> work?

A few snippets from the HTML5 spec: http://w3c.github.io/html/semantics-scripting.html#element-attrdef-script-async

The defer and async attributes must not be specified if the src attribute is not present.


There are three possible modes that can be selected using these attributes [async and defer]. If the async attribute is present, then the script will be executed asynchronously, as soon as it is available. If the async attribute is not present but the defer attribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.


The exact processing details for these attributes are, for mostly historical reasons, somewhat non-trivial, involving a number of aspects of HTML. The implementation requirements are therefore by necessity scattered throughout the specification. The algorithms below (in this section) describe the core of this processing, but these algorithms reference and are referenced by the parsing rules for script start and end tags in HTML, in foreign content, and in XML, the rules for the document.write() method, the handling of scripting, etc.


If the element has a src attribute, and the element has a defer attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute:

The element must be added to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.

How do I check if an HTML element is empty using jQuery?

jQuery.fn.doSomething = function() {
   //return something with 'this'
};

$('selector:empty').doSomething();

Row Offset in SQL Server

See my select for paginator

SELECT TOP @limit * FROM (
   SELECT ROW_NUMBER() OVER (ORDER BY colunx ASC) offset, * FROM (

     -- YOU SELECT HERE
     SELECT * FROM mytable


   ) myquery
) paginator
WHERE offset > @offset

This solves the pagination ;)

USB Debugging option greyed out

Unplug your phone from the your computer, then choose PC Software as PC Connection Type. Then go into Developer Options and select USB Debugging

Python debugging tips

PyDev

PyDev has a pretty good interactive debugger. It has watch expressions, hover-to-evaluate, thread and stack listings and (almost) all the usual amenities you expect from a modern visual debugger. You can even attach to a running process and do remote debugging.

Like other visual debuggers, though, I find it useful mostly for simple problems, or for very complicated problems after I've tried everything else. I still do most of the heavy lifting with logging.

Easiest way to activate PHP and MySQL on Mac OS 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion)?

I would agree with Benjamin, either install MAMP or MacPorts (http://www.macports.org/). Keeping your PHP install separate is simpler and avoids messing up the core PHP install if you make any mistakes!

MacPorts is a bit better for installing other software, such as ImageMagick. See a full list of available ports at http://www.macports.org/ports.php

MAMP just really does PHP, Apache and MySQL so any future PHP modules you want will need to be manually enabled. It is incredibly easy to use though.

A message body writer for Java type, class myPackage.B, and MIME media type, application/octet-stream, was not found

This can also happen if you've recently upgraded Ant. I was using Ant 1.8.4 on a project, and upgraded Ant to 1.9.4, and started to get this error when building a fat jar using Ant.

The solution for me was to downgrade back to Ant 1.8.4 for the command line and Eclipse using the process detailed here

Display animated GIF in iOS

If you are targeting iOS7 and already have the image split into frames you can use animatedImageNamed:duration:.

Let's say you are animating a spinner. Copy all of your frames into the project and name them as follows:

  • spinner-1.png
  • spinner-2.png
  • spinner-3.png
  • etc.,

Then create the image via:

[UIImage animatedImageNamed:@"spinner-" duration:1.0f];

From the docs:

This method loads a series of files by appending a series of numbers to the base file name provided in the name parameter. For example, if the name parameter had ‘image’ as its contents, this method would attempt to load images from files with the names ‘image0’, ‘image1’ and so on all the way up to ‘image1024’. All images included in the animated image should share the same size and scale.

Android customized button; changing text color

Use getColorStateList like this

setTextColor(resources.getColorStateList(R.color.button_states_color))

instead of getColor

setTextColor(resources.getColor(R.color.button_states_color))

Get text from pressed button

Try to use:

String buttonText = ((Button)v).getText().toString();

SQL : BETWEEN vs <= and >=

Typically, there is no difference - the BETWEEN keyword is not supported on all RDBMS platforms, but if it is, the two queries should be identical.

Since they're identical, there's really no distinction in terms of speed or anything else - use the one that seems more natural to you.

Twitter bootstrap collapse: change display of toggle button

try this. http://jsfiddle.net/fVpkm/

Html:-

<div class="row-fluid summary">
    <div class="span11">
        <h2>MyHeading</h2>  
    </div>
    <div class="span1">
        <button class="btn btn-success" data-toggle="collapse" data-target="#intro">+</button>
    </div>
</div>
<div class="row-fluid summary">
    <div id="intro" class="collapse"> 
        Here comes the text...
    </div>
</div>

JS:-

$('button').click(function(){ //you can give id or class name here for $('button')
    $(this).text(function(i,old){
        return old=='+' ?  '-' : '+';
    });
});

Update With pure Css, pseudo elements

http://jsfiddle.net/r4Bdz/

Supported Browsers

button.btn.collapsed:before
{
    content:'+' ;
    display:block;
    width:15px;
}
button.btn:before
{
    content:'-' ;
    display:block;
    width:15px;
}

Update 2 With pure Javascript

http://jsfiddle.net/WteTy/

function handleClick()
{
    this.value = (this.value == '+' ? '-' : '+');
}
document.getElementById('collapsible').onclick=handleClick;

iOS: Compare two dates

According to Apple documentation of NSDate compare:

Returns an NSComparisonResult value that indicates the temporal ordering of the receiver and another given date.

- (NSComparisonResult)compare:(NSDate *)anotherDate

Parameters anotherDate

The date with which to compare the receiver. This value must not be nil. If the value is nil, the behavior is undefined and may change in future versions of Mac OS X.

Return Value

If:

The receiver and anotherDate are exactly equal to each other, NSOrderedSame

The receiver is later in time than anotherDate, NSOrderedDescending

The receiver is earlier in time than anotherDate, NSOrderedAscending

In other words:

if ([date1 compare:date2] == NSOrderedSame) ...

Note that it might be easier in your particular case to read and write this :

if ([date2 isEqualToDate:date2]) ...

See Apple Documentation about this one.

How to have an automatic timestamp in SQLite?

you can use triggers. works very well

CREATE TABLE MyTable(
ID INTEGER PRIMARY KEY,
Name TEXT,
Other STUFF,
Timestamp DATETIME);


CREATE TRIGGER insert_Timestamp_Trigger
AFTER INSERT ON MyTable
BEGIN
   UPDATE MyTable SET Timestamp =STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW') WHERE id = NEW.id;
END;

CREATE TRIGGER update_Timestamp_Trigger
AFTER UPDATE On MyTable
BEGIN
   UPDATE MyTable SET Timestamp = STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW') WHERE id = NEW.id;
END;

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

pip or pip3 to install packages for Python 3?

When you install python3, pip3 gets installed. And if you don't have another python installation(like python2.7) then a link is created which points pip to pip3.

So pip is a link to to pip3 if there is no other version of python installed(other than python3). pip generally points to the first installation.

Installing pip packages to $HOME folder

I would use virtualenv at your HOME directory.

$ sudo easy_install -U virtualenv
$ cd ~
$ virtualenv .
$ bin/pip ...

You could then also alter ~/.(login|profile|bash_profile), whichever is right for your shell to add ~/bin to your PATH and then that pip|python|easy_install would be the one used by default.

Getting Gradle dependencies in IntelliJ IDEA using Gradle build

In my case,I was getting error while refreshing gradle ('View'->Tool Windows->Gradle) tab and hit "refresh" and getting this error no such property gradleversion for class jetgradleplugin.

Had to install latest intellij compatible with gradle 5+

How to start Fragment from an Activity

Firstly, you start Activities and Services with an intent, you start fragments with fragment transactions. Secondly, your transaction isnt doing anything. Change it to something like:

FragmentTransaction transaction = getFragmentManager();
    transaction.beginTransaction()
        .replace(R.layout.container, newFragment) //<---replace a view in your layout (id: container) with the newFragment 
        .commit();

File Explorer in Android Studio

View > Tool Windows > Device File Explorer

MySQL with Node.js

You can skip the ORM, builders, etc. and simplify your DB/SQL management using sqler and sqler-mdb.

-- create this file at: db/mdb/setup/create.database.sql
CREATE DATABASE IF NOT EXISTS sqlermysql
const conf = {
  "univ": {
    "db": {
      "mdb": {
        "host": "localhost",
        "username":"admin",
        "password": "mysqlpassword"
      }
    }
  },
  "db": {
    "dialects": {
      "mdb": "sqler-mdb"
    },
    "connections": [
      {
        "id": "mdb",
        "name": "mdb",
        "dir": "db/mdb",
        "service": "MySQL",
        "dialect": "mdb",
        "pool": {},
        "driverOptions": {
          "connection": {
            "multipleStatements": true
          }
        }
      }
    ]
  }
};

// create/initialize manager
const manager = new Manager(conf);
await manager.init();

// .sql file path is path to db function
const result = await manager.db.mdb.setup.create.database();

console.log('Result:', result);

// after we're done using the manager we should close it
process.on('SIGINT', async function sigintDB() {
  await manager.close();
  console.log('Manager has been closed');
});

How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?

You can use dispatch_after to call a block later. In Xcode, start typing dispatch_after and hit Enter to autocomplete to the following:

enter image description here

Here's an example with two floats as "arguments." You don't have to rely on any type of macro, and the intent of the code is quite clear:

Swift 3, Swift 4

let time1 = 8.23
let time2 = 3.42

// Delay 2 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
    print("Sum of times: \(time1 + time2)")
}

Swift 2

let time1 = 8.23
let time2 = 3.42

// Delay 2 seconds
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2.0 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
        println("Sum of times: \(time1 + time2)")
}

Objective C

CGFloat time1 = 3.49;
CGFloat time2 = 8.13;

// Delay 2 seconds
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    CGFloat newTime = time1 + time2;
    NSLog(@"New time: %f", newTime);
});

The entity type <type> is not part of the model for the current context

One other thing to check with your connection string - the model name. I was using two entity models, DB first. In the config I copied the entity connection for one, renamed it, and changed the connection string part. What I didn't change was the model name, so while the entity model generated correctly, when the context was initiated EF was looking in the wrong model for the entities.

Looks obvious written down, but there are four hours I won't get back.

how do I change text in a label with swift?

Swift uses the same cocoa-touch API. You can call all the same methods, but they will use Swift's syntax. In this example you can do something like this:

self.simpleLabel.text = "message"

Note the setText method isn't available. Setting the label's text with = will automatically call the setter in swift.

How can I test a change made to Jenkinsfile locally?

For simplicity, you can create a Jenkinsfile at the root of the git repository, similar to the below example 'Jenkinsfile' based on the groovy syntax of the declarative pipeline.

pipeline {

    agent any

    stages {
        stage('Build the Project') {
            steps {
                git 'https://github.com/jaikrgupta/CarthageAPI-1.0.git'
                echo pwd()
                sh 'ls -alrt'
                sh 'pip install -r requirements.txt'
                sh 'python app.py &'
                echo "Build stage gets finished here"
            }
        }
        stage('Test') {
            steps {
                sh 'chmod 777 ./scripts/test-script.sh'
                sh './scripts/test-script.sh'
                sh 'cat ./test-reports/test_script.log'
                echo "Test stage gets finished here"
            }
        }
}

https://github.com/jaikrgupta/CarthageAPI-1.0.git

You can now set up a new item in Jenkins as a Pipeline job. Select the Definition as Pipeline script from SCM and Git for the SCM option. Paste the project's git repo link in the Repository URL and Jenkinsfile in the script name box. Then click on the lightweight checkout option and save the project. So whenever you pushed a commit to the git repo, you can always test the changes running the Build Now every time in Jenkins.

Please follow the instructions in the below visuals for easy setup a Jenkins Pipeline's job.

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

What is an NP-complete in computer science?

It's a class of problems where we must simulate every possibility to be sure we have the optimal solution.

There are a lot of good heuristics for some NP-Complete problems, but they are only an educated guess at best.

Detect whether Office is 32bit or 64bit via the registry

I don't have a key called bitness in either of these folders. I do have a key called "default" in both of these folders and the value is "unset" My computer came with office 2010 starter (I assume 64 bit). I removed it and tried to do a full install of 32 bit office. I keep getting the following message. the file is incompatible, check to see whether you need x86 or x64 version of the program.

any advice for me?

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

Error: java.lang.NoSuchMethodError: javax.persistence.JoinTable.indexes()[Ljavax/persistence/Index;

The only thing that solved my problem was removing the following dependency in pom.xml: <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.1-api</artifactId> <version>1.0.0.Final</version> </dependency>

And replace it for:

<dependency>
  <groupId>javax.persistence</groupId>
  <artifactId>persistence-api</artifactId>
  <version>1.0.2</version>
</dependency>

Hope it helps someone.

console.log(result) returns [object Object]. How do I get result.name?

Try adding JSON.stringify(result) to convert the JS Object into a JSON string.

From your code I can see you are logging the result in error which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).

Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.

How can I install Python's pip3 on my Mac?

I ran the below where <user>:<group> matched the other <user>:<group> for other files in the /usr/local/lib/python3.7/site-packages/ directory:

sudo chown -R <user>:<group> /usr/local/lib/python3.7/site-packages/pip*
brew postinstall python3

Handling errors in Promise.all

Have you considered Promise.prototype.finally()?

It seems to be designed to do exactly what you want - execute a function once all the promises have settled (resolved/rejected), regardless of some of the promises being rejected.

From the MDN documentation:

The finally() method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome.

The finally() method is very similar to calling .then(onFinally, onFinally) however there are couple of differences:

When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it.

A finally callback will not receive any argument, since there's no reliable means of determining if the promise was fulfilled or rejected. This use case is for precisely when you do not care about the rejection reason, or the fulfillment value, and so there's no need to provide it.

Unlike Promise.resolve(2).then(() => {}, () => {}) (which will be resolved with undefined), Promise.resolve(2).finally(() => {}) will be resolved with 2. Similarly, unlike Promise.reject(3).then(() => {}, () => {}) (which will be fulfilled with undefined), Promise.reject(3).finally(() => {}) will be rejected with 3.

== Fallback ==

If your version of JavaScript doesn't support Promise.prototype.finally() you can use this workaround from Jake Archibald: Promise.all(promises.map(p => p.catch(() => undefined)));

How to suspend/resume a process in Windows?

Well, Process Explorer has a suspend option. You can right click a process in the process column and select suspend. Once you are ready to resume it again right click and this time select resume. Process Explorer can be obtained from here:

http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx

Twitter bootstrap scrollable table

None of these answers worked satisfactorily for me. They either didn't fix the table heading row in place or they required fixed column widths to work, and even then tended to have the heading row and body rows misaligned in various browsers.

I recommend biting the bullet and using a proper grid control like jsGrid or my personal favorite, SlickGrid. It obviously introduces a dependency but if you want your tables to behave like real grids with cross-browser support, this will save you pulling your hair out. It also gives you the option of sorting and resizing columns plus tons of other features if you want them.

The type or namespace cannot be found (are you missing a using directive or an assembly reference?)

I get this error when my project .net framework version does not match the framework version of the DLL I am linking to. In my case, I was getting:

"The type or namespace name 'UserVoice' could not be found (are you missing a using directive or an assembly reference?).

UserVoice was .Net 4.0, and my project properties were set to ".Net 4.0 Client Profile". Changing to .Net 4.0 on the project cleared the error. I hope this helps someone.

How to convert a char array back to a string?

String output = new String(charArray);

Where charArray is the character array and output is your character array converted to the string.

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

From Object Explorer in SQL Server Management Studio, find your database and expand the node (click on the + sign beside your database). The first item from that expanded tree is Database Diagrams. Right-click on that and you'll see various tasks including creating a new database diagram. If you've never created one before, it'll ask if you want to install the components for creating diagrams. Click yes then proceed.

KnockoutJs v2.3.0 : Error You cannot apply bindings multiple times to the same element

ko.cleanNode($("#modalPartialView")[0]);
ko.applyBindings(vm, $("#modalPartialView")[0]);

works for me, but as others note, the cleanNode is internal ko function, so there is probably a better way.

Get Specific Columns Using “With()” Function in Laravel Eloquent

For loading models with specific column, though not eager loading, you could:

In your Post model

public function user()
{
    return $this->belongsTo('User')->select(array('id', 'username'));
}

Original credit goes to Laravel Eager Loading - Load only specific columns

How do you UDP multicast in Python?

In order to Join multicast group Python uses native OS socket interface. Due to portability and stability of Python environment many of socket options are directly forwarded to native socket setsockopt call. Multicast mode of operation such as joining and dropping group membership can be accomplished by setsockopt only.

Basic program for receiving multicast IP packet can look like:

from socket import *

multicast_port  = 55555
multicast_group = "224.1.1.1"
interface_ip    = "10.11.1.43"

s = socket(AF_INET, SOCK_DGRAM )
s.bind(("", multicast_port ))
mreq = inet_aton(multicast_group) + inet_aton(interface_ip)
s.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, str(mreq))

while 1:
    print s.recv(1500)

Firstly it creates socket, binds it and triggers triggers multicast group joining by issuing setsockopt. At very end it receives packets forever.

Sending multicast IP frames is straight forward. If you have single NIC in your system sending such packets does not differ from usual UDP frames sending. All you need to take care of is just set correct destination IP address in sendto() method.

I noticed that lot of examples around Internet works by accident in fact. Even on official python documentation. Issue for all of them are using struct.pack incorrectly. Please be advised that typical example uses 4sl as format and it is not aligned with actual OS socket interface structure.

I will try to describe what happens underneath the hood when exercising setsockopt call for python socket object.

Python forwards setsockopt method call to native C socket interface. Linux socket documentation (see man 7 ip) introduces two forms of ip_mreqn structure for IP_ADD_MEMBERSHIP option. Shortest is form is 8 bytes long and longer is 12 bytes long. Above example generates 8 byte setsockopt call where first four bytes define multicast_group and second four bytes define interface_ip.

presentViewController and displaying navigation bar

Can you use:

[self.navigationController pushViewController:controller animated:YES];

Going back (I think):

[self.navigationController popToRootViewControllerAnimated:YES];

Why are there no ++ and --? operators in Python?

This may be because @GlennMaynard is looking at the matter as in comparison with other languages, but in Python, you do things the python way. It's not a 'why' question. It's there and you can do things to the same effect with x+=. In The Zen of Python, it is given: "there should only be one way to solve a problem." Multiple choices are great in art (freedom of expression) but lousy in engineering.

How to display an image stored as byte array in HTML/JavaScript?

Try putting this HTML snippet into your served document:

<img id="ItemPreview" src="">

Then, on JavaScript side, you can dynamically modify image's src attribute with so-called Data URL.

document.getElementById("ItemPreview").src = "data:image/png;base64," + yourByteArrayAsBase64;

Alternatively, using jQuery:

$('#ItemPreview').attr('src', `data:image/png;base64,${yourByteArrayAsBase64}`);

This assumes that your image is stored in PNG format, which is quite popular. If you use some other image format (e.g. JPEG), modify the MIME type ("image/..." part) in the URL accordingly.

Similar Questions:

How to redirect output of an already running process

I collected some information on the internet and prepared the script that requires no external tool: See my response here. Hope it's helpful.

How to prevent scientific notation in R?

Try format function:

> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"

Python dictionary : TypeError: unhashable type: 'list'

This is indeed rather odd.

If aSourceDictionary were a dictionary, I don't believe it is possible for your code to fail in the manner you describe.

This leads to two hypotheses:

  1. The code you're actually running is not identical to the code in your question (perhaps an earlier or later version?)

  2. aSourceDictionary is in fact not a dictionary, but is some other structure (for example, a list).

jQuery: Handle fallback for failed AJAX Request

Yes, it's built in to jQuery. See the docs at jquery documentation.

ajaxError may be what you want.

How to call base.base.method()?

Just want to add this here, since people still return to this question even after many time. Of course it's bad practice, but it's still possible (in principle) to do what author wants with:

class SpecialDerived : Derived
{
    public override void Say()
    {
        Console.WriteLine("Called from Special Derived.");
        var ptr = typeof(Base).GetMethod("Say").MethodHandle.GetFunctionPointer();            
        var baseSay = (Action)Activator.CreateInstance(typeof(Action), this, ptr);
        baseSay();            
    }
}

Sorting hashmap based on keys

Use a TreeMap with a custom comparator.

class MyComparator implements Comparator<String>
    {
        public int compare(String o1,String o2)
        {
            // Your logic for comparing the key strings
        }
    }

TreeMap<String, Float> tm = new TreeMap<String , Float>(new MyComparator());

As you add new elements, they will be automatically sorted.

In your case, it might not even be necessary to implement a comparator because String ordering might be sufficient. But if you want to implement special cases, like lower case alphas appear before upper case, or treat the numbers a certain way, use the comparator.

Submit form using <a> tag

Submit your form like this ...

Your HTML code

    <form name="myform" action="handle-data.php"> Search: <input type='text' name='query' />
     <a href="javascript: submitform()">Search</a> 
   </form> 

JavaScript Code

  <script type="text/javascript"> 
        function submitform() {   document.myform.submit(); } 
   </script> 

Java - Convert integer to string

Integer class has static method toString() - you can use it:

int i = 1234;
String str = Integer.toString(i);

Returns a String object representing the specified integer. The argument is converted to signed decimal representation and returned as a string, exactly as if the argument and radix 10 were given as arguments to the toString(int, int) method.

JPA EntityManager: Why use persist() over merge()?

persist(entity) should be used with totally new entities, to add them to DB (if entity already exists in DB there will be EntityExistsException throw).

merge(entity) should be used, to put entity back to persistence context if the entity was detached and was changed.

Probably persist is generating INSERT sql statement and merge UPDATE sql statement (but i'm not sure).

Creating temporary files in Android

Best practices on internal and external temporary files:

Internal Cache

If you'd like to cache some data, rather than store it persistently, you should use getCacheDir() to open a File that represents the internal directory where your application should save temporary cache files.

When the device is low on internal storage space, Android may delete these cache files to recover space. However, you should not rely on the system to clean up these files for you. You should always maintain the cache files yourself and stay within a reasonable limit of space consumed, such as 1MB. When the user uninstalls your application, these files are removed.

External Cache

To open a File that represents the external storage directory where you should save cache files, call getExternalCacheDir(). If the user uninstalls your application, these files will be automatically deleted.

Similar to ContextCompat.getExternalFilesDirs(), mentioned above, you can also access a cache directory on a secondary external storage (if available) by calling ContextCompat.getExternalCacheDirs().

Tip: To preserve file space and maintain your app's performance, it's important that you carefully manage your cache files and remove those that aren't needed anymore throughout your app's lifecycle.

Can I remove the URL from my print css, so the web address doesn't print?

In Firefox, https://bug743252.bugzilla.mozilla.org/attachment.cgi?id=714383 (view page source :: tag HTML).

In your code, replace <html> with <html moznomarginboxes mozdisallowselectionprint>.

In others browsers, I don't know, but you can view http://www.mintprintables.com/print-tips/header-footer-windows/

PHP replacing special characters like à->a, è->e

Wish I found this thread sooner. The function I made (that took me way too long) is below:

function CheckLetters($field){
    $letters = [
        0 => "a à á â ä æ ã å a",
        1 => "c ç c c",
        2 => "e é è ê ë e e e",
        3 => "i i i í ì ï î",
        4 => "l l",
        5 => "n ñ n",
        6 => "o o ø œ õ ó ò ö ô",
        7 => "s ß s š",
        8 => "u u ú ù ü û",
        9 => "w w",
        10 => "y y ÿ",
        11 => "z z ž z",
    ];
    foreach ($letters as &$values){
        $newValue = substr($values, 0, 1);
        $values = substr($values, 2, strlen($values));
        $values = explode(" ", $values);
        foreach ($values as &$oldValue){
            while (strpos($field,$oldValue) !== false){
                $field = preg_replace("/" . $oldValue . '/', $newValue, $field, 1);
            }
        }
    }
    return $field;
}

SyntaxError: Use of const in strict mode?

The const and let are part of ECMAScript 2015 (a.k.a. ES6 and Harmony), and was not enabled by default in Node.js 0.10 or 0.12. Since Node.js 4.x, “All shipping [ES2015] features, which V8 considers stable, are turned on by default on Node.js and do NOT require any kind of runtime flag.”. Node.js docs has an overview of what ES2015 features are enabled by default, and which who require a runtime flag. So by upgrading to Node.js 4.x or newer the error should disappear.

To enable some of the ECMAScript 2015 features (including const and let) in Node.js 0.10 and 0.12; start your node program with a harmony flag, otherwise you will get a syntax error. For example:

node --harmony app.js

It all depends on which side your strict js is located. I would recommend using strict mode with const declarations on your server side and start the server with the harmony flag. For the client side, you should use Babel or similar tool to convert ES2015 to ES5, since not all client browsers support the const declarations.

Missing Microsoft RDLC Report Designer in Visual Studio

Below Different tools for Editing Rdlc report:

  1. ReportBuilder 3.0 : Microsoft Editor for Rdlc report.
  2. Microsoft® SQL Server® 2008 Express with Advanced Services: Another tool is to use Sql Server Business intelligence for reporting that can be installed with Sql Server Express with Advanced Sevices.
  3. fyiReporting: It is opensource tool presented for editing Rdlc reports .

Proper use of the IDisposable interface

If anything, I'd expect the code to be less efficient than when leaving it out.

Calling the Clear() methods are unnecessary, and the GC probably wouldn't do that if the Dispose didn't do it...

Http Post With Body

You can try something like this using HttpClient and HttpPost:

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("mystring", "value_of_my_string"));
// etc...

// Post data to the server
HttpPost httppost = new HttpPost("http://...");
httppost.setEntity(new UrlEncodedFormEntity(params));

HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httppost);

Unable to resolve host "<insert URL here>" No address associated with hostname

Please, check if you have valid internet connection.

Create pandas Dataframe by appending one row at a time

If you have a data frame df and want to add a list new_list as a new row to df, you can simply do:

df.loc[len(df)] = new_list

If you want to add a new data frame new_df under data frame df, then you can use:

df.append(new_df)

How stable is the git plugin for eclipse?

There is also gitclipse(based on JavaGit), but seems dead.

React - How to force a function component to render?

Update react v16.8 (16 Feb 2019 realease)

Since react 16.8 released with hooks, function components are now have the ability to hold persistent state. With that ability you can now mimic a forceUpdate:

_x000D_
_x000D_
function App() {_x000D_
  const [, updateState] = React.useState();_x000D_
  const forceUpdate = React.useCallback(() => updateState({}), []);_x000D_
  console.log("render");_x000D_
  return (_x000D_
    <div>_x000D_
      <button onClick={forceUpdate}>Force Render</button>_x000D_
    </div>_x000D_
  );_x000D_
}_x000D_
_x000D_
const rootElement = document.getElementById("root");_x000D_
ReactDOM.render(<App />, rootElement);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script>_x000D_
<div id="root"/>
_x000D_
_x000D_
_x000D_

Note that this approach should be re-considered and in most cases when you need to force an update you probably doing something wrong.


Before react 16.8.0

No you can't, State-Less function components are just normal functions that returns jsx, you don't have any access to the React life cycle methods as you are not extending from the React.Component.

Think of function-component as the render method part of the class components.

How to specify the download location with wget?

-O is the option to specify the path of the file you want to download to:

wget <uri> -O /path/to/file.ext

-P is prefix where it will download the file in the directory:

wget <uri> -P /path/to/folder

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

Update the tensorflow binary for your CPU & OS using this command

pip install --ignore-installed --upgrade "Download URL"

The download url of the whl file can be found here

https://github.com/lakshayg/tensorflow-build

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

Quick answer:
A child scope normally prototypically inherits from its parent scope, but not always. One exception to this rule is a directive with scope: { ... } -- this creates an "isolate" scope that does not prototypically inherit. This construct is often used when creating a "reusable component" directive.

As for the nuances, scope inheritance is normally straightfoward... until you need 2-way data binding (i.e., form elements, ng-model) in the child scope. Ng-repeat, ng-switch, and ng-include can trip you up if you try to bind to a primitive (e.g., number, string, boolean) in the parent scope from inside the child scope. It doesn't work the way most people expect it should work. The child scope gets its own property that hides/shadows the parent property of the same name. Your workarounds are

  1. define objects in the parent for your model, then reference a property of that object in the child: parentObj.someProp
  2. use $parent.parentScopeProperty (not always possible, but easier than 1. where possible)
  3. define a function on the parent scope, and call it from the child (not always possible)

New AngularJS developers often do not realize that ng-repeat, ng-switch, ng-view, ng-include and ng-if all create new child scopes, so the problem often shows up when these directives are involved. (See this example for a quick illustration of the problem.)

This issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-models – watch 3 minutes worth. Misko demonstrates the primitive binding issue with ng-switch.

Having a '.' in your models will ensure that prototypal inheritance is in play. So, use

<input type="text" ng-model="someObj.prop1">

<!--rather than
<input type="text" ng-model="prop1">`
-->


L-o-n-g answer:

JavaScript Prototypal Inheritance

Also placed on the AngularJS wiki: https://github.com/angular/angular.js/wiki/Understanding-Scopes

It is important to first have a solid understanding of prototypal inheritance, especially if you are coming from a server-side background and you are more familiar with class-ical inheritance. So let's review that first.

Suppose parentScope has properties aString, aNumber, anArray, anObject, and aFunction. If childScope prototypically inherits from parentScope, we have:

prototypal inheritance

(Note that to save space, I show the anArray object as a single blue object with its three values, rather than an single blue object with three separate gray literals.)

If we try to access a property defined on the parentScope from the child scope, JavaScript will first look in the child scope, not find the property, then look in the inherited scope, and find the property. (If it didn't find the property in the parentScope, it would continue up the prototype chain... all the way up to the root scope). So, these are all true:

childScope.aString === 'parent string'
childScope.anArray[1] === 20
childScope.anObject.property1 === 'parent prop1'
childScope.aFunction() === 'parent output'

Suppose we then do this:

childScope.aString = 'child string'

The prototype chain is not consulted, and a new aString property is added to the childScope. This new property hides/shadows the parentScope property with the same name. This will become very important when we discuss ng-repeat and ng-include below.

property hiding

Suppose we then do this:

childScope.anArray[1] = '22'
childScope.anObject.property1 = 'child prop1'

The prototype chain is consulted because the objects (anArray and anObject) are not found in the childScope. The objects are found in the parentScope, and the property values are updated on the original objects. No new properties are added to the childScope; no new objects are created. (Note that in JavaScript arrays and functions are also objects.)

follow the prototype chain

Suppose we then do this:

childScope.anArray = [100, 555]
childScope.anObject = { name: 'Mark', country: 'USA' }

The prototype chain is not consulted, and child scope gets two new object properties that hide/shadow the parentScope object properties with the same names.

more property hiding

Takeaways:

  • If we read childScope.propertyX, and childScope has propertyX, then the prototype chain is not consulted.
  • If we set childScope.propertyX, the prototype chain is not consulted.

One last scenario:

delete childScope.anArray
childScope.anArray[1] === 22  // true

We deleted the childScope property first, then when we try to access the property again, the prototype chain is consulted.

after removing a child property


Angular Scope Inheritance

The contenders:

  • The following create new scopes, and inherit prototypically: ng-repeat, ng-include, ng-switch, ng-controller, directive with scope: true, directive with transclude: true.
  • The following creates a new scope which does not inherit prototypically: directive with scope: { ... }. This creates an "isolate" scope instead.

Note, by default, directives do not create new scope -- i.e., the default is scope: false.

ng-include

Suppose we have in our controller:

$scope.myPrimitive = 50;
$scope.myObject    = {aNumber: 11};

And in our HTML:

<script type="text/ng-template" id="/tpl1.html">
<input ng-model="myPrimitive">
</script>
<div ng-include src="'/tpl1.html'"></div>

<script type="text/ng-template" id="/tpl2.html">
<input ng-model="myObject.aNumber">
</script>
<div ng-include src="'/tpl2.html'"></div>

Each ng-include generates a new child scope, which prototypically inherits from the parent scope.

ng-include child scopes

Typing (say, "77") into the first input textbox causes the child scope to get a new myPrimitive scope property that hides/shadows the parent scope property of the same name. This is probably not what you want/expect.

ng-include with a primitive

Typing (say, "99") into the second input textbox does not result in a new child property. Because tpl2.html binds the model to an object property, prototypal inheritance kicks in when the ngModel looks for object myObject -- it finds it in the parent scope.

ng-include with an object

We can rewrite the first template to use $parent, if we don't want to change our model from a primitive to an object:

<input ng-model="$parent.myPrimitive">

Typing (say, "22") into this input textbox does not result in a new child property. The model is now bound to a property of the parent scope (because $parent is a child scope property that references the parent scope).

ng-include with $parent

For all scopes (prototypal or not), Angular always tracks a parent-child relationship (i.e., a hierarchy), via scope properties $parent, $$childHead and $$childTail. I normally don't show these scope properties in the diagrams.

For scenarios where form elements are not involved, another solution is to define a function on the parent scope to modify the primitive. Then ensure the child always calls this function, which will be available to the child scope due to prototypal inheritance. E.g.,

// in the parent scope
$scope.setMyPrimitive = function(value) {
     $scope.myPrimitive = value;
}

Here is a sample fiddle that uses this "parent function" approach. (The fiddle was written as part of this answer: https://stackoverflow.com/a/14104318/215945.)

See also https://stackoverflow.com/a/13782671/215945 and https://github.com/angular/angular.js/issues/1267.

ng-switch

ng-switch scope inheritance works just like ng-include. So if you need 2-way data binding to a primitive in the parent scope, use $parent, or change the model to be an object and then bind to a property of that object. This will avoid child scope hiding/shadowing of parent scope properties.

See also AngularJS, bind scope of a switch-case?

ng-repeat

Ng-repeat works a little differently. Suppose we have in our controller:

$scope.myArrayOfPrimitives = [ 11, 22 ];
$scope.myArrayOfObjects    = [{num: 101}, {num: 202}]

And in our HTML:

<ul><li ng-repeat="num in myArrayOfPrimitives">
       <input ng-model="num">
    </li>
<ul>
<ul><li ng-repeat="obj in myArrayOfObjects">
       <input ng-model="obj.num">
    </li>
<ul>

For each item/iteration, ng-repeat creates a new scope, which prototypically inherits from the parent scope, but it also assigns the item's value to a new property on the new child scope. (The name of the new property is the loop variable's name.) Here's what the Angular source code for ng-repeat actually is:

childScope = scope.$new();  // child scope prototypically inherits from parent scope
...
childScope[valueIdent] = value;  // creates a new childScope property

If item is a primitive (as in myArrayOfPrimitives), essentially a copy of the value is assigned to the new child scope property. Changing the child scope property's value (i.e., using ng-model, hence child scope num) does not change the array the parent scope references. So in the first ng-repeat above, each child scope gets a num property that is independent of the myArrayOfPrimitives array:

ng-repeat with primitives

This ng-repeat will not work (like you want/expect it to). Typing into the textboxes changes the values in the gray boxes, which are only visible in the child scopes. What we want is for the inputs to affect the myArrayOfPrimitives array, not a child scope primitive property. To accomplish this, we need to change the model to be an array of objects.

So, if item is an object, a reference to the original object (not a copy) is assigned to the new child scope property. Changing the child scope property's value (i.e., using ng-model, hence obj.num) does change the object the parent scope references. So in the second ng-repeat above, we have:

ng-repeat with objects

(I colored one line gray just so that it is clear where it is going.)

This works as expected. Typing into the textboxes changes the values in the gray boxes, which are visible to both the child and parent scopes.

See also Difficulty with ng-model, ng-repeat, and inputs and https://stackoverflow.com/a/13782671/215945

ng-controller

Nesting controllers using ng-controller results in normal prototypal inheritance, just like ng-include and ng-switch, so the same techniques apply. However, "it is considered bad form for two controllers to share information via $scope inheritance" -- http://onehungrymind.com/angularjs-sticky-notes-pt-1-architecture/ A service should be used to share data between controllers instead.

(If you really want to share data via controllers scope inheritance, there is nothing you need to do. The child scope will have access to all of the parent scope properties. See also Controller load order differs when loading or navigating)

directives

  1. default (scope: false) - the directive does not create a new scope, so there is no inheritance here. This is easy, but also dangerous because, e.g., a directive might think it is creating a new property on the scope, when in fact it is clobbering an existing property. This is not a good choice for writing directives that are intended as reusable components.
  2. scope: true - the directive creates a new child scope that prototypically inherits from the parent scope. If more than one directive (on the same DOM element) requests a new scope, only one new child scope is created. Since we have "normal" prototypal inheritance, this is like ng-include and ng-switch, so be wary of 2-way data binding to parent scope primitives, and child scope hiding/shadowing of parent scope properties.
  3. scope: { ... } - the directive creates a new isolate/isolated scope. It does not prototypically inherit. This is usually your best choice when creating reusable components, since the directive cannot accidentally read or modify the parent scope. However, such directives often need access to a few parent scope properties. The object hash is used to set up two-way binding (using '=') or one-way binding (using '@') between the parent scope and the isolate scope. There is also '&' to bind to parent scope expressions. So, these all create local scope properties that are derived from the parent scope. Note that attributes are used to help set up the binding -- you can't just reference parent scope property names in the object hash, you have to use an attribute. E.g., this won't work if you want to bind to parent property parentProp in the isolated scope: <div my-directive> and scope: { localProp: '@parentProp' }. An attribute must be used to specify each parent property that the directive wants to bind to: <div my-directive the-Parent-Prop=parentProp> and scope: { localProp: '@theParentProp' }.
    Isolate scope's __proto__ references Object. Isolate scope's $parent references the parent scope, so although it is isolated and doesn't inherit prototypically from the parent scope, it is still a child scope.
    For the picture below we have
    <my-directive interpolated="{{parentProp1}}" twowayBinding="parentProp2"> and
    scope: { interpolatedProp: '@interpolated', twowayBindingProp: '=twowayBinding' }
    Also, assume the directive does this in its linking function: scope.someIsolateProp = "I'm isolated"
    isolated scope
    For more information on isolate scopes see http://onehungrymind.com/angularjs-sticky-notes-pt-2-isolated-scope/
  4. transclude: true - the directive creates a new "transcluded" child scope, which prototypically inherits from the parent scope. The transcluded and the isolated scope (if any) are siblings -- the $parent property of each scope references the same parent scope. When a transcluded and an isolate scope both exist, isolate scope property $$nextSibling will reference the transcluded scope. I'm not aware of any nuances with the transcluded scope.
    For the picture below, assume the same directive as above with this addition: transclude: true
    transcluded scope

This fiddle has a showScope() function that can be used to examine an isolate and transcluded scope. See the instructions in the comments in the fiddle.


Summary

There are four types of scopes:

  1. normal prototypal scope inheritance -- ng-include, ng-switch, ng-controller, directive with scope: true
  2. normal prototypal scope inheritance with a copy/assignment -- ng-repeat. Each iteration of ng-repeat creates a new child scope, and that new child scope always gets a new property.
  3. isolate scope -- directive with scope: {...}. This one is not prototypal, but '=', '@', and '&' provide a mechanism to access parent scope properties, via attributes.
  4. transcluded scope -- directive with transclude: true. This one is also normal prototypal scope inheritance, but it is also a sibling of any isolate scope.

For all scopes (prototypal or not), Angular always tracks a parent-child relationship (i.e., a hierarchy), via properties $parent and $$childHead and $$childTail.

Diagrams were generated with "*.dot" files, which are on github. Tim Caswell's "Learning JavaScript with Object Graphs" was the inspiration for using GraphViz for the diagrams.

How to get selected path and name of the file opened with file dialog?

To extract only the filename from the path, you can do the following:

varFileName = Mid(fDialog.SelectedItems(1), InStrRev(fDialog.SelectedItems(1), "\") + 1, Len(fDialog.SelectedItems(1)))

Oracle sqlldr TRAILING NULLCOLS required, but why?

Last column in your input file must have some data in it (be it space or char, but not null). I guess, 1st record contains null after last ',' which sqlldr won't recognize unless specifically asked to recognize nulls using TRAILING NULLCOLS option. Alternatively, if you don't want to use TRAILING NULLCOLS, you will have to take care of those NULLs before you pass the file to sqlldr. Hope this helps

The type or namespace name 'System' could not be found

For me it only happened in one project and I tried everything I found online and nothing seemed to help. I was ready to delete and recreate the project when after messing through the projects properties changing the .NET framework target from 4.7.2 to 4.8 fixed the issue. I changed it back to 4.7.2 later and the error is gone.

Hopefully this helps other users as well.

Convert a JSON String to a HashMap

There’s an older answer using javax.json posted here, however it only converts JsonArray and JsonObject, but there are still JsonString, JsonNumber, and JsonValue wrapper classes in the output. If you want to get rid of these, here’s my solution which will unwrap everything.

Beside that, it makes use of Java 8 streams and is contained in a single method.

/**
 * Convert a JsonValue into a “plain” Java structure (using Map and List).
 * 
 * @param value The JsonValue, not <code>null</code>.
 * @return Map, List, String, Number, Boolean, or <code>null</code>.
 */
public static Object toObject(JsonValue value) {
    Objects.requireNonNull(value, "value was null");
    switch (value.getValueType()) {
    case ARRAY:
        return ((JsonArray) value)
                .stream()
                .map(JsonUtils::toObject)
                .collect(Collectors.toList());
    case OBJECT:
        return ((JsonObject) value)
                .entrySet()
                .stream()
                .collect(Collectors.toMap(
                        Entry::getKey,
                        e -> toObject(e.getValue())));
    case STRING:
        return ((JsonString) value).getString();
    case NUMBER:
        return ((JsonNumber) value).numberValue();
    case TRUE:
        return Boolean.TRUE;
    case FALSE:
        return Boolean.FALSE;
    case NULL:
        return null;
    default:
        throw new IllegalArgumentException("Unexpected type: " + value.getValueType());
    }
}

What's the difference between a single precision and double precision floating point operation?

As to the question "Can the ps3 and xbxo 360 pull off double precision floating point operations or only single precision and in generel use is the double precision capabilities made use of (if they exist?)."

I believe that both platforms are incapable of double floating point. The original Cell processor only had 32 bit floats, same with the ATI hardware which the XBox 360 is based on (R600). The Cell got double floating point support later on, but I'm pretty sure the PS3 doesn't use that chippery.

How can I use regex to get all the characters after a specific character, e.g. comma (",")

[^,]*$

might do. (Matches everything after the last comma).

Explanation: [^,] matches every character except for ,. The * denotes that the regexp matches any number of repetition of [^,]. The $ sign matches the end of the line.

What is the difference between a candidate key and a primary key?

A table can have so many column which can uniquely identify a row. This columns are referred as candidate keys, but primary key should be one of them because one primary key is enough for a table. So selection of primary key is important among so many candidate key. Thats the main difference.

Composer install error - requires ext_curl when it's actually enabled

According to https://github.com/composer/composer/issues/2119 you could extend your local composer.json to state that it provides the extension (which it doesn't really do - that's why you shouldn't publicly publish your package, only use it internally).

How do I escape reserved words used as column names? MySQL/Create Table

If you are interested in portability between different SQL servers you should use ANSI SQL queries. String escaping in ANSI SQL is done by using double quotes ("). Unfortunately, this escaping method is not portable to MySQL, unless it is set in ANSI compatibility mode.

Personally, I always start my MySQL server with the --sql-mode='ANSI' argument since this allows for both methods for escaping. If you are writing queries that are going to be executed in a MySQL server that was not setup / is controlled by you, here is what you can do:

  • Write all you SQL queries in ANSI SQL
  • Enclose them in the following MySQL specific queries:

    SET @OLD_SQL_MODE=@@SQL_MODE;
    SET SESSION SQL_MODE='ANSI';
    -- ANSI SQL queries
    SET SESSION SQL_MODE=@OLD_SQL_MODE;
    

This way the only MySQL specific queries are at the beginning and the end of your .sql script. If you what to ship them for a different server just remove these 3 queries and you're all set. Even more conveniently you could create a script named: script_mysql.sql that would contain the above mode setting queries, source a script_ansi.sql script and reset the mode.

How to enable remote access of mysql in centos?

Bind-address XXX.XX.XX.XXX in /etc/my.cnf

comment line:

skip-networking

or

skip-external-locking

after edit hit service mysqld restart

login into mysql and hit this query:

GRANT ALL PRIVILEGES ON dbname.* TO 'username'@'%' IDENTIFIED BY 'password';

FLUSH PRIVILEGES;
quit;

add firewall rule:

iptables -I INPUT -i eth0 -p tcp --destination-port 3306 -j ACCEPT

Python datetime to string without microsecond component

Keep the first 19 characters that you wanted via slicing:

>>> str(datetime.datetime.now())[:19]
'2011-11-03 14:37:50'

How can I check whether a numpy array is empty or not?

http://www.scipy.org/Tentative_NumPy_Tutorial#head-6a1bc005bd80e1b19f812e1e64e0d25d50f99fe2

NumPy's main object is the homogeneous multidimensional array. In Numpy dimensions are called axes. The number of axes is rank. Numpy's array class is called ndarray. It is also known by the alias array. The more important attributes of an ndarray object are:

ndarray.ndim
the number of axes (dimensions) of the array. In the Python world, the number of dimensions is referred to as rank.

ndarray.shape
the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the rank, or number of dimensions, ndim.

ndarray.size
the total number of elements of the array. This is equal to the product of the elements of shape.

how to copy only the columns in a DataTable to another DataTable?

If only the columns are required then DataTable.Clone() can be used. With Clone function only the schema will be copied. But DataTable.Copy() copies both the structure and data

E.g.

DataTable dt = new DataTable();
dt.Columns.Add("Column Name");
dt.Rows.Add("Column Data");
DataTable dt1 = dt.Clone();
DataTable dt2 = dt.Copy();

dt1 will have only the one column but dt2 will have one column with one row.

How to group by week in MySQL?

Figured it out... it's a little cumbersome, but here it is.

FROM_DAYS(TO_DAYS(TIMESTAMP) -MOD(TO_DAYS(TIMESTAMP) -1, 7))

And, if your business rules say your weeks start on Mondays, change the -1 to -2.


Edit

Years have gone by and I've finally gotten around to writing this up. http://www.plumislandmedia.net/mysql/sql-reporting-time-intervals/

Best way to remove items from a collection

This is my generic solution

public static IEnumerable<T> Remove<T>(this IEnumerable<T> items, Func<T, bool> match)
    {
        var list = items.ToList();
        for (int idx = 0; idx < list.Count(); idx++)
        {
            if (match(list[idx]))
            {
                list.RemoveAt(idx);
                idx--; // the list is 1 item shorter
            }
        }
        return list.AsEnumerable();
    }

It would look much simpler if extension methods support passing by reference ! usage:

var result = string[]{"mike", "john", "ali"}
result = result.Remove(x => x.Username == "mike").ToArray();
Assert.IsTrue(result.Length == 2);

EDIT: ensured that the list looping remains valid even when deleting items by decrementing the index (idx).

Vuejs: v-model array in multiple input

If you were asking how to do it in vue2 and make options to insert and delete it, please, have a look an js fiddle

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    finds: [] _x000D_
  },_x000D_
  methods: {_x000D_
    addFind: function () {_x000D_
      this.finds.push({ value: 'def' });_x000D_
    },_x000D_
    deleteFind: function (index) {_x000D_
      console.log(index);_x000D_
      console.log(this.finds);_x000D_
      this.finds.splice(index, 1);_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
  <h1>Finds</h1>_x000D_
  <div v-for="(find, index) in finds">_x000D_
    <input v-model="find.value">_x000D_
    <button @click="deleteFind(index)">_x000D_
      delete_x000D_
    </button>_x000D_
  </div>_x000D_
  _x000D_
  <button @click="addFind">_x000D_
    New Find_x000D_
  </button>_x000D_
  _x000D_
  <pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Git Symlinks in Windows

so as things have changed with GIT since alot of these answers were posted here is the correct instructions to get symlinks working correctly in windows as of

AUGUST 2018


1. Make sure git is installed with symlink support

During the install of git on windows

2. Tell Bash to create hardlinks instead of symlinks

EDIT -- (git folder)/etc/bash.bashrc

ADD TO BOTTOM - MSYS=winsymlinks:nativestrict

3. Set git config to use symlinks

git config core.symlinks true

or

git clone -c core.symlinks=true <URL>

NOTE: I have tried adding this to the global git config and at the moment it is not working for me so I recommend adding this to each repo...

4. pull the repo

NOTE: Unless you have enabled developer mode in the latest version of Windows 10, you need to run bash as administrator to create symlinks

5. Reset all Symlinks (optional) If you have an existing repo, or are using submodules you may find that the symlinks are not being created correctly so to refresh all the symlinks in the repo you can run these commands.

find -type l -delete
git reset --hard

NOTE: this will reset any changes since last commit so make sure you have committed first

how to reset <input type = "file">

This is the BEST solution:

input.value = ''

if(!/safari/i.test(navigator.userAgent)){
  input.type = ''
  input.type = 'file'
}

Of all the answers here this is the fastest solution. No input clone, no form reset!

I checked it in all browsers (it even has IE8 support).

Which regular expression operator means 'Don't' match this character?

[^] ( within [ ] ) is negation in regular expression whereas ^ is "begining of string"

[^a-z] matches any single character that is not from "a" to "z"

^[a-z] means string starts with from "a" to "z"

Reference

How can I format a decimal to always show 2 decimal places?

>>> print "{:.2f}".format(1.123456)
1.12

You can change 2 in 2f to any number of decimal points you want to show.

EDIT:

From Python3.6, this translates to:

>>> print(f"{1.1234:.2f}")
1.12

Propagation Delay vs Transmission delay

The transmission delay is the amount of time required for the router to push out the packet.

The propagation delay, is the time it takes a bit to propagate from one router to the next.

the transmission and propagation delay are completely different! if denote the length of the packet by L bits, and denote the transmission rate of the link from first router to second router by R bits/sec. then transmission delay will be L/R. and this is depended to transmission rate of link and the length of packet.

then if denote the distance between two routers d and denote the propagation speed s, the propagation delay will be d/s. it is a function of the Distance between the two routers, but has no dependence to the packet's length or the transmission rate of the link.

How to open the second form?

If you want to open Form2 modally (meaning you can't click on Form1 while Form2 is open), you can do this:

using (Form2 f2 = new Form2()) 
{
    f2.ShowDialog(this);
}

If you want to open Form2 non-modally (meaning you can still click on Form1 while Form2 is open), you can create a form-level reference to Form2 like this:

private Form2 _f2;

public void openForm2()
{
    _f2 = new Form2();
    _f2.Show(this); // the "this" is important, as this will keep Form2 open above 
                    // Form1.
}

public void closeForm2()
{
    _f2.Close();
    _f2.Dispose();
}

How can I play sound in Java?

I created a game framework sometime ago to work on Android and Desktop, the desktop part that handle sound maybe can be used as inspiration to what you need.

https://github.com/hamilton-lima/jaga/blob/master/jaga%20desktop/src-desktop/com/athanazio/jaga/desktop/sound/Sound.java

Here is the code for reference.

package com.athanazio.jaga.desktop.sound;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Sound {

    AudioInputStream in;

    AudioFormat decodedFormat;

    AudioInputStream din;

    AudioFormat baseFormat;

    SourceDataLine line;

    private boolean loop;

    private BufferedInputStream stream;

    // private ByteArrayInputStream stream;

    /**
     * recreate the stream
     * 
     */
    public void reset() {
        try {
            stream.reset();
            in = AudioSystem.getAudioInputStream(stream);
            din = AudioSystem.getAudioInputStream(decodedFormat, in);
            line = getLine(decodedFormat);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void close() {
        try {
            line.close();
            din.close();
            in.close();
        } catch (IOException e) {
        }
    }

    Sound(String filename, boolean loop) {
        this(filename);
        this.loop = loop;
    }

    Sound(String filename) {
        this.loop = false;
        try {
            InputStream raw = Object.class.getResourceAsStream(filename);
            stream = new BufferedInputStream(raw);

            // ByteArrayOutputStream out = new ByteArrayOutputStream();
            // byte[] buffer = new byte[1024];
            // int read = raw.read(buffer);
            // while( read > 0 ) {
            // out.write(buffer, 0, read);
            // read = raw.read(buffer);
            // }
            // stream = new ByteArrayInputStream(out.toByteArray());

            in = AudioSystem.getAudioInputStream(stream);
            din = null;

            if (in != null) {
                baseFormat = in.getFormat();

                decodedFormat = new AudioFormat(
                        AudioFormat.Encoding.PCM_SIGNED, baseFormat
                                .getSampleRate(), 16, baseFormat.getChannels(),
                        baseFormat.getChannels() * 2, baseFormat
                                .getSampleRate(), false);

                din = AudioSystem.getAudioInputStream(decodedFormat, in);
                line = getLine(decodedFormat);
            }
        } catch (UnsupportedAudioFileException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (LineUnavailableException e) {
            e.printStackTrace();
        }
    }

    private SourceDataLine getLine(AudioFormat audioFormat)
            throws LineUnavailableException {
        SourceDataLine res = null;
        DataLine.Info info = new DataLine.Info(SourceDataLine.class,
                audioFormat);
        res = (SourceDataLine) AudioSystem.getLine(info);
        res.open(audioFormat);
        return res;
    }

    public void play() {

        try {
            boolean firstTime = true;
            while (firstTime || loop) {

                firstTime = false;
                byte[] data = new byte[4096];

                if (line != null) {

                    line.start();
                    int nBytesRead = 0;

                    while (nBytesRead != -1) {
                        nBytesRead = din.read(data, 0, data.length);
                        if (nBytesRead != -1)
                            line.write(data, 0, nBytesRead);
                    }

                    line.drain();
                    line.stop();
                    line.close();

                    reset();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Ranges of floating point datatype in C?

A 32 bit floating point number has 23 + 1 bits of mantissa and an 8 bit exponent (-126 to 127 is used though) so the largest number you can represent is:

(1 + 1 / 2 + ... 1 / (2 ^ 23)) * (2 ^ 127) = 
(2 ^ 23 + 2 ^ 23 + .... 1) * (2 ^ (127 - 23)) = 
(2 ^ 24 - 1) * (2 ^ 104) ~= 3.4e38

Select first empty cell in column F starting from row 1. (without using offset )

There is another way which ignores all empty cells before a nonempty cell and selects the last empty cell from the end of the first column. Columns should be addressed with their number eg. Col "A" = 1.

With ThisWorkbook.Sheets("sheet1")

        .Cells(.Cells(.Cells.Rows.Count, 1).End(xlUp).Row + 1, 1).select

End With

The next code is exactly as the above but can be understood better.

i = ThisWorkbook.Sheets("sheet1").Cells.Rows.Count

j = ThisWorkbook.Sheets("sheet1").Cells(i, 1).End(xlUp).Row

ThisWorkbook.Sheets("sheet1").Cells(j + 1, 1) = textbox1.value

How to parse a JSON string to an array using Jackson

The other answer is correct, but for completeness, here are other ways:

List<SomeClass> list = mapper.readValue(jsonString, new TypeReference<List<SomeClass>>() { });
SomeClass[] array = mapper.readValue(jsonString, SomeClass[].class);

Python Socket Receive Large Amount of Data

Modifying Adam Rosenfield's code:

import sys


def send_msg(sock, msg):
    size_of_package = sys.getsizeof(msg)
    package = str(size_of_package)+":"+ msg #Create our package size,":",message
    sock.sendall(package)

def recv_msg(sock):
    try:
        header = sock.recv(2)#Magic, small number to begin with.
        while ":" not in header:
            header += sock.recv(2) #Keep looping, picking up two bytes each time

        size_of_package, separator, message_fragment = header.partition(":")
        message = sock.recv(int(size_of_package))
        full_message = message_fragment + message
        return full_message

    except OverflowError:
        return "OverflowError."
    except:
        print "Unexpected error:", sys.exc_info()[0]
        raise

I would, however, heavily encourage using the original approach.

How to upsert (update or insert) in SQL Server 2005

Try to check for existence:

IF NOT EXISTS (SELECT * FROM dbo.Employee WHERE ID = @SomeID)

    INSERT INTO dbo.Employee(Col1, ..., ColN)
    VALUES(Val1, .., ValN)

ELSE

    UPDATE dbo.Employee
    SET Col1 = Val1, Col2 = Val2, ...., ColN = ValN
    WHERE ID = @SomeID

You could easily wrap this into a stored procedure and just call that stored procedure from the outside (e.g. from a programming language like C# or whatever you're using).

Update: either you can just write this entire statement in one long string (doable - but not really very useful) - or you can wrap it into a stored procedure:

CREATE PROCEDURE dbo.InsertOrUpdateEmployee
       @ID INT,
       @Name VARCHAR(50),
       @ItemName VARCHAR(50),  
       @ItemCatName VARCHAR(50),
       @ItemQty DECIMAL(15,2)
AS BEGIN
    IF NOT EXISTS (SELECT * FROM dbo.Table1 WHERE ID = @ID)
       INSERT INTO dbo.Table1(ID, Name, ItemName, ItemCatName, ItemQty)
       VALUES(@ID, @Name, @ItemName, @ItemCatName, @ItemQty)
    ELSE
       UPDATE dbo.Table1
       SET Name = @Name,
           ItemName = @ItemName,
           ItemCatName = @ItemCatName,
           ItemQty = @ItemQty
       WHERE ID = @ID
END

and then just call that stored procedure from your ADO.NET code

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

This is intended behavior.

When you make an HTTP request, the server normally returns code 200 OK. If you set If-Modified-Since, the server may return 304 Not modified (and the response will not have the content). This is supposed to be your cue that the page has not been modified.

The authors of the class have foolishly decided that 304 should be treated as an error and throw an exception. Now you have to clean up after them by catching the exception every time you try to use If-Modified-Since.

How to measure time elapsed on Javascript?

The Date documentation states that :

The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC

Click on start button then on end button. It will show you the number of seconds between the 2 clicks.

The milliseconds diff is in variable timeDiff. Play with it to find seconds/minutes/hours/ or what you need

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = new Date();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = new Date();_x000D_
  var timeDiff = endTime - startTime; //in ms_x000D_
  // strip the ms_x000D_
  timeDiff /= 1000;_x000D_
_x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

OR another way of doing it for modern browser

Using performance.now() which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.

The time origin is a standard time which is considered to be the beginning of the current document's lifetime.

_x000D_
_x000D_
var startTime, endTime;_x000D_
_x000D_
function start() {_x000D_
  startTime = performance.now();_x000D_
};_x000D_
_x000D_
function end() {_x000D_
  endTime = performance.now();_x000D_
  var timeDiff = endTime - startTime; //in ms _x000D_
  // strip the ms _x000D_
  timeDiff /= 1000; _x000D_
  _x000D_
  // get seconds _x000D_
  var seconds = Math.round(timeDiff);_x000D_
  console.log(seconds + " seconds");_x000D_
}
_x000D_
<button onclick="start()">Start</button>_x000D_
<button onclick="end()">End</button>
_x000D_
_x000D_
_x000D_

How to update values using pymongo?

You can use the $set syntax if you want to set the value of a document to an arbitrary value. This will either update the value if the attribute already exists on the document or create it if it doesn't. If you need to set a single value in a dictionary like you describe, you can use the dot notation to access child values.

If p is the object retrieved:

existing = p['d']['a']

For pymongo versions < 3.0

db.ProductData.update({
  '_id': p['_id']
},{
  '$set': {
    'd.a': existing + 1
  }
}, upsert=False, multi=False)

For pymongo versions >= 3.0

db.ProductData.update_one({
  '_id': p['_id']
},{
  '$set': {
    'd.a': existing + 1
  }
}, upsert=False)

However if you just need to increment the value, this approach could introduce issues when multiple requests could be running concurrently. Instead you should use the $inc syntax:

For pymongo versions < 3.0:

db.ProductData.update({
  '_id': p['_id']
},{
  '$inc': {
    'd.a': 1
  }
}, upsert=False, multi=False)

For pymongo versions >= 3.0:

db.ProductData.update_one({
  '_id': p['_id']
},{
  '$inc': {
    'd.a': 1
  }
}, upsert=False)

This ensures your increments will always happen.

Bootstrap 3 unable to display glyphicon properly

Here's the fix that worked for me. Firefox has a file origin policy that causes this. To fix do the following steps:

  1. open about:config in firefox
  2. Find security.fileuri.strict_origin_policy property and change it from ‘true’ to ‘false.’
  3. Voial! you are good to go!

Details: http://stuffandnonsense.co.uk/blog/about/firefoxs_file_uri_origin_policy_and_web_fonts

You will only see this issue when accessing a file using file:/// protocol

HTTP Status 404 - The requested resource (/) is not available

I had the same problem with my localhost project using Eclipse Luna, Maven and Tomcat - the Tomcat homepage would appear fine, however my project would get the 404 error.

After trying many suggested solutions (updating spring .jar file, changing properties of the Tomcat server, add/remove project, change JRE from 1.6 to 7 etc) which did not fix the issue, what worked for me was to just Refresh my project. It seems Eclipse does not automatically refresh the project after a (Maven) build. In Eclipse 3.3.1 there was a 'Refresh Automatically' option under Preferences > General > Workspace however that option doesn't look to be in Luna.

  1. Maven clean-install on the project.
  2. ** Right-click the project and select 'Refresh'. **
  3. Right-click the Eclipse Tomcat server and select 'Clean'.
  4. Right-click > Publish and then start the Tomcat server.

Python variables as keys to dict

why you don't do the opposite :

fruitdict = { 
      'apple':1,
      'banana':'f',
      'carrot':3,
}

locals().update(fruitdict)

Update :

don't use the code above check the comment.

by the way why you don't mark the vars that you want to get i don't know maybe like this:

# All the vars that i want to get are followed by _fruit
apple_fruit = 1
carrot_fruit = 'f'

for var in locals():
    if var.endswith('fruit'):
       you_dict.update({var:locals()[var])

How do I print bold text in Python?

Check out colorama. It doesn't necessarily help with bolding... but you can do colorized output on both Windows and Linux, and control the brightness:

from colorama import *
init(autoreset=True)
print Fore.RED + 'some red text'
print Style.BRIGHT + Fore.RED + 'some bright red text'

Programmatically navigate to another view controller/scene

Swift 4.0.3

 @IBAction func registerNewUserButtonTapped(_ sender: Any) {

        print("---------------------------registerNewUserButtonTapped --------------------------- ");

        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

        let nextViewController = storyBoard.instantiateViewController(withIdentifier: "RegisterNewUserViewController") as! RegisterNewUserViewController
        self.present(nextViewController, animated:true, completion:nil)

    }

Change our Controller Name RegisterNewUserViewController

The apk must be signed with the same certificates as the previous version

Here i get the answer for that question . After searching for too long finally i get to crack the key and password for this . I forget my key and alias also the jks file but fortunately i know the bunch of password what i had put in it . but finding correct combinations for that was toughest task for me .

Solution - Download this - Keytool IUI version 2.4.1 plugin enter image description here

the window will pop up now it show the alias name ..if you jks file is correct .. right click on alias and hit "view certificates chain ".. it will show the SHA1 Key .. match this key with tha key you get while you was uploading the apk in google app store ...

if it match then you are with the right jks file and alias ..

now lucky i have bunch of password to match .. enter image description here

now go to this scrren put the same jks path .. and password(among the password you have ) put any path in "Certificate file"

if the screen shows any error then password is not matching .. if it doesn't show any error then it means you are with correct jks file . correct alias and password() now with that you can upload your apk in play store :)

HTTPS using Jersey Client

For Jersey 2 you'd need to modify the code:

        return ClientBuilder.newBuilder()
            .withConfig(config)
            .hostnameVerifier(new TrustAllHostNameVerifier())
            .sslContext(ctx)
            .build();

https://gist.github.com/JAlexoid/b15dba31e5919586ae51 http://www.panz.in/2015/06/jersey2https.html

Python: List vs Dict for look up table

if data are unique set() will be the most efficient, but of two - dict (which also requires uniqueness, oops :)

How to represent a DateTime in Excel

Excel expects dates and times to be stored as a floating point number whose value depends on the Date1904 setting of the workbook, plus a number format such as "mm/dd/yyyy" or "hh:mm:ss" or "mm/dd/yyyy hh:mm:ss" so that the number is displayed to the user as a date / time.

Using SpreadsheetGear for .NET you can do this: worksheet.Cells["A1"].Value = DateTime.Now;

This will convert the DateTime to a double which is the underlying type which Excel uses for a Date / Time, and then format the cell with a default date and / or time number format automatically depending on the value.

SpreadsheetGear also has IWorkbook.DateTimeToNumber(DateTime) and NumberToDateTime(double) methods which convert from .NET DateTime objects to a double which Excel can use.

I would expect XlsIO to have something similar.

Disclaimer: I own SpreadsheetGear LLC

Regex (grep) for multi-line search needed

Your fundamental problem is that grep works one line at a time - so it cannot find a SELECT statement spread across lines.

Your second problem is that the regex you are using doesn't deal with the complexity of what can appear between SELECT and FROM - in particular, it omits commas, full stops (periods) and blanks, but also quotes and anything that can be inside a quoted string.

I would likely go with a Perl-based solution, having Perl read 'paragraphs' at a time and applying a regex to that. The downside is having to deal with the recursive search - there are modules to do that, of course, including the core module File::Find.

In outline, for a single file:

$/ = "\n\n";    # Paragraphs

while (<>)
{
     if ($_ =~ m/SELECT.*customerName.*FROM/mi)
     {
         printf file name
         go to next file
     }
}

That needs to be wrapped into a sub that is then invoked by the methods of File::Find.

Mockito. Verify method arguments

I have used Mockito.verify in this way

@UnitTest
public class JUnitServiceTest
{
    @Mock
    private MyCustomService myCustomService;


    @Test
    public void testVerifyMethod()
    {
       Mockito.verify(myCustomService, Mockito.never()).mymethod(parameters); // method will never call (an alternative can be pick to use times(0))
       Mockito.verify(myCustomService, Mockito.times(2)).mymethod(parameters); // method will call for 2 times
       Mockito.verify(myCustomService, Mockito.atLeastOnce()).mymethod(parameters); // method will call atleast 1 time
       Mockito.verify(myCustomService, Mockito.atLeast(2)).mymethod(parameters); // method will call atleast 2 times
       Mockito.verify(myCustomService, Mockito.atMost(3)).mymethod(parameters); // method will call at most 3 times
       Mockito.verify(myCustomService, Mockito.only()).mymethod(parameters); //   no other method called except this
    }
}

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

For me, I was receiving this error when connecting to the new IP Address I had configured FileZilla to bind to and saved the configuration. After trying all of the other answers unsuccessfully, I decided to connect to the old IP Address to see what came up; lo and behold it responded.

I restarted the FileZilla Windows Service and it immediately came back listening on the correct IP. Pretty elementary, but it cost me some time today as a noob to FZ.

Hopefully this helps someone out in the same predicament.

How to exclude a directory from ant fileset, based on directories contents

it works for me with a jar target:

<jar jarfile="${server.jar}" basedir="${classes.dir}" excludes="**/client/">
  <manifest>
    <attribute name="Main-Class" value="${mainServer.class}" />
  </manifest>
</jar>

this code include all files in "classes.dir" but exclude the directory "client" from the jar.

Padding In bootstrap

I have not used Bootstrap but I worked on Zurb Foundation. On that I used to add space like this.

<div id="main" class="container" role="main">
    <div class="row">

        <div class="span5 offset1">
            <h2>Welcome</h2>
            <p>Hello and welcome to my website.</p>
        </div>
        <div class="span6">
            Image Here (TODO)
        </div>
    </div>

Visit this link: http://getbootstrap.com/2.3.2/scaffolding.html and read the section: Offsetting columns.

I think I know what you are doing wrong. If you are applying padding to the span6 like this:

<div class="span6" style="padding-left:5px;">
    <h2>Welcome</h2>
    <p>Hello and welcome to my website.</p>
</div>

It is wrong. What you have to do is add padding to the elements inside:

<div class="span6">
    <h2 style="padding-left:5px;">Welcome</h2>
    <p  style="padding-left:5px;">Hello and welcome to my website.</p>
</div>

Enabling refreshing for specific html elements only

try to empty your innerHtml everytime. just like this:

_x000D_
_x000D_
Element.innerHtml="";
_x000D_
_x000D_
_x000D_

Check if Nullable Guid is empty in c#

SomeProperty.HasValue I think it's what you're looking for.

EDIT : btw, you can write System.Guid? instead of Nullable<System.Guid> ;)

Error:attempt to apply non-function

You're missing *s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2 as an attempt to call a function named 0.207 ...

For example:

> 1 + 2*(3)
[1] 7
> 1 + 2 (3)

Error: attempt to apply non-function

Your (unreproducible) expression should read:

censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) + 
                              0.207* (log(DIAM93))^2  -
                              0.0281*(log(DIAM93))^3)

Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...

Manifest merger failed : uses-sdk:minSdkVersion 14

I have the second solution:

  1. unzip https://dl.dropboxusercontent.com/u/16403954/android-21.zip to sdk\platforms\
  2. change build.gradle like

    compileSdkVersion 21
    buildToolsVersion "20.0.0"
    
    defaultConfig {
        applicationId "package.name"
        minSdkVersion 10
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    
  3. add

    <uses-sdk tools:node="replace" /> 
    

    in Manifest with xmlns:tools="schemas.android.com/tools";

  4. Go to sdk\extras\android\m2repository\com\android\support\support-v4\21.0.0-rc1\

unpack support-v4-21.0.0-rc1.aar and edit AndroidManifest.xml like

from

<uses-sdk
        android:minSdkVersion="L"
        android:targetSdkVersion="L" />

to

<uses-sdk
        android:minSdkVersion="4"
        android:targetSdkVersion="21" />

P.S. You can do this with all support libraries that need.

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

In a shameless attempt to steal some votes, SecurityProtocol is an Enum with the [Flags] attribute. So you can do this:

[Net.ServicePointManager]::SecurityProtocol = 
  [Net.SecurityProtocolType]::Tls12 -bor `
  [Net.SecurityProtocolType]::Tls11 -bor `
  [Net.SecurityProtocolType]::Tls

Or since this is PowerShell, you can let it parse a string for you:

[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"

Then you don't technically need to know the TLS version.

I copied and pasted this from a script I created after reading this answer because I didn't want to cycle through all the available protocols to find one that worked. Of course, you could do that if you wanted to.

Final note - I have the original (minus SO edits) statement in my PowerShell profile so it's in every session I start now. It's not totally foolproof since there are still some sites that just fail but I surely see the message in question much less frequently.

How to find children of nodes using BeautifulSoup

"How to find all a which are children of <li class=test> but not any others?"

Given the HTML below (I added another <a> to show te difference between select and select_one):

<div>
  <li class="test">
    <a>link1</a>
    <ul>
      <li>
        <a>link2</a>
      </li>
    </ul>
    <a>link3</a>
  </li>
</div>

The solution is to use child combinator (>) that is placed between two CSS selectors:

>>> soup.select('li.test > a')
[<a>link1</a>, <a>link3</a>]

In case you want to find only the first child:

>>> soup.select_one('li.test > a')
<a>link1</a>

How to convert an NSTimeInterval (seconds) into minutes

pseudo-code:

minutes = floor(326.4/60)
seconds = round(326.4 - minutes * 60)

SQLException: No suitable driver found for jdbc:derby://localhost:1527

I had the same problem when I was writing Java application on Netbeans.Here is the solution:

  1. Find your project in projects selection tab

  2. Right click "Libraries"

  3. Click "Add JAR/Folder..."

  4. Choose "derbyclient.jar"

  5. Click "Open", then you will see "derbyclient.jar" under your "Libraries"

  6. Make sure your URL, user name, pass word is correct, and run your code:)

jquery get all input from specific form

Use HTML Form "elements" attribute:

$.each($("form").elements, function(){ 
    console.log($(this));
    });

Now it's not necessary to provide such names as "input, textarea, select ..." etc.

Output data from all columns in a dataframe in pandas

Use:

pandas.set_option('display.max_columns', 7)

This will force Pandas to display the 7 columns you have. Or more generally:

pandas.set_option('display.max_columns', None)

which will force it to display any number of columns.

Explanation: the default for max_columns is 0, which tells Pandas to display the table only if all the columns can be squeezed into the width of your console.

Alternatively, you can change the console width (in chars) from the default of 80 using e.g:

pandas.set_option('display.width', 200)

How to make an authenticated web request in Powershell?

In some case NTLM authentication still won't work if given the correct credential.

There's a mechanism which will void NTLM auth within WebClient, see here for more information: System.Net.WebClient doesn't work with Windows Authentication

If you're trying above answer and it's still not working, follow the above link to add registry to make the domain whitelisted.

Post this here to save other's time ;)

How to create a new variable in a data.frame based on a condition?

If you have a very limited number of levels, you could try converting y into factor and change its levels.

> xy <- data.frame(x = c(1, 2, 4), y = c(1, 4, 5))
> xy$w <- as.factor(xy$y)
> levels(xy$w) <- c("good", "fair", "bad")
> xy
  x y    w
1 1 1 good
2 2 4 fair
3 4 5  bad

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

xsd:boolean element type accept "true" but not "True". How can I make it accept it?

If you're on Linux, or have cygwin available on Windows, you can run the input XML through a simple sed script that will replace <Active>True</Active> with <Active>true</Active>, like so:

cat <your XML file> | sed 'sX<Active>True</Active>X<Active>true</Active>X' | xmllint --schema -

If you're not, you can still use a non-validating xslt pocessor (xalan, saxon etc.) to run a simple xslt transformation on the input, and only then pipe it to xmllint.

What the xsl should contain something like below, for the example you listed above (the xslt processor should be 2.0 capable):

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="xml" indent="yes"/>
    <xsl:template match="/">
    <xsl:for-each select="XML">
        <xsl:for-each select="Active">
            <xsl:value-of select=" replace(current(), 'True','true')"/>
        </xsl:for-each>
    </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

The entity name must immediately follow the '&' in the entity reference

The parser is expecting some HTML content, so it sees & as the beginning of an entity, like &egrave;.

Use this workaround:

<script type="text/javascript">
// <![CDATA[
Javascript code here
// ]]>
</script>

so you specify that the code is not HTML text but just data to be used as is.

Android Studio with Google Play Services

Follow this article -> http://developer.android.com/google/play-services/setup.html

You should to choose Using Android Studio

enter image description here

Example Gradle file:

Note: Open the build.gradle file inside your application module directory.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 20
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "{applicationId}"
        minSdkVersion 14
        targetSdkVersion 20
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:20.+'
    compile 'com.google.android.gms:play-services:6.1.+'
}

You can find latest version of Google Play Services here: https://developer.android.com/google/play-services/index.html

How can I generate an HTML report for Junit results?

If you could use Ant then you would just use the JUnitReport task as detailed here: http://ant.apache.org/manual/Tasks/junitreport.html, but you mentioned in your question that you're not supposed to use Ant. I believe that task merely transforms the XML report into HTML so it would be feasible to use any XSLT processor to generate a similar report.

Alternatively, you could switch to using TestNG ( http://testng.org/doc/index.html ) which is very similar to JUnit but has a default HTML report as well as several other cool features.

Formatting text in a TextBlock

You can do this in XAML easily enough:

<TextBlock>
  Hello <Bold>my</Bold> faithful <Underline>computer</Underline>.<Italic>You rock!</Italic>
</TextBlock>

Is there a "previous sibling" selector?

Removing the styles of next siblings on hover, so that it looks like only previous siblings have styles added on hover.

_x000D_
_x000D_
ul li {
  color: red;
  cursor: pointer;
}

ul:hover li {
  color: blue;
}

ul:hover li:hover ~ li{
  color: red;
}
_x000D_
<ul>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
</ul>
_x000D_
_x000D_
_x000D_

How to make several plots on a single page using matplotlib?

To answer your main question, you want to use the subplot command. I think changing plt.figure(i) to plt.subplot(4,4,i+1) should work.

Add two numbers and display result in textbox with Javascript

var first_number = parseInt(document.getElementById("Text1").value);
var second_number = parseInt(document.getElementById("Text2").value);

// This is because your method .getElementById has the letter 's': .getElement**s**ById

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

There is another possibility: You may have an error in your .aspx file that does not allow Visual Studio to regenerate the designer.

If you switch to Design View, it will show the control as unable to be rendered. Fixing the control (in my case it was an extra quote in the properties) and recompiling should regenerate the designer.

Java, How to get number of messages in a topic in apache kafka

You may use kafkatool. Please check this link -> http://www.kafkatool.com/download.html

Kafka Tool is a GUI application for managing and using Apache Kafka clusters. It provides an intuitive UI that allows one to quickly view objects within a Kafka cluster as well as the messages stored in the topics of the cluster. enter image description here

Avoid duplicates in INSERT INTO SELECT query in SQL Server

I was facing the same problem recently...
Heres what worked for me in MS SQL server 2017...
The primary key should be set on ID in table 2...
The columns and column properties should be the same of course between both tables. This will work the first time you run the below script. The duplicate ID in table 1, will not insert...

If you run it the second time, you will get a

Violation of PRIMARY KEY constraint error

This is the code:

Insert into Table_2
Select distinct *
from Table_1
where table_1.ID >1

Can we use join for two different database tables?

SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.

Let's suppose you have two databases on the same server - Db1 and Db2. Db1 has a table called Clients with a column ClientId and Db2 has a table called Messages with a column ClientId (let's leave asside why those tables are in different databases).

Now, to perform a join on the above-mentioned tables you will be using this query:

select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId

CSS Input with width: 100% goes outside parent's bound

I tried these solutions but never got a conclusive result. In the end I used proper semantic markup with a fieldset. It saved having to add any width calculations and any box-sizing.

It also allows you to set the form width as you require and the inputs remain within the padding you need for your edges.

In this example I have put a border on the form and fieldset and an opaque background on the legend and fieldset so you can see how they overlap and sit with each other.

<html>
  <head>
  <style>
    form {
      width: 300px;
      margin: 0 auto;
      border: 1px solid;
    }
    fieldset {
      border: 0;
      margin: 0;
      padding: 0 20px 10px;
      border: 1px solid blue;
      background: rgba(0,0,0,.2);
    }
    legend {
      background: rgba(0,0,0,.2);
      width: 100%;
      margin: 0 -20px;
      padding: 2px 20px;
      color: $col1;
      border: 0;
    }
    input[type="email"],
    input[type="password"],
    button {
      width: 100%;
      margin: 0 0 10px;
      padding: 0 10px;
    }
    input[type="email"],
    input[type="password"] {
      line-height: 22px;
      font-size: 16px;
    }
    button {
    line-height: 26px;
    font-size: 20px;
    }
  </style>
  </head>
  <body>
  <form>
      <fieldset>
          <legend>Log in</legend>
          <p>You may need some content here, a message?</p>
          <input type="email" id="email" name="email" placeholder="Email" value=""/>
          <input type="password" id="password" name="password" placeholder="password" value=""/>
          <button type="submit">Login</button>
      </fieldset>
  </form>
  </body>
</html>

PHP file_get_contents() returns "failed to open stream: HTTP request failed!"

<?php

$lurl=get_fcontent("http://ip2.cc/?api=cname&ip=84.228.229.81");
echo"cid:".$lurl[0]."<BR>";


function get_fcontent( $url,  $javascript_loop = 0, $timeout = 5 ) {
    $url = str_replace( "&amp;", "&", urldecode(trim($url)) );

    $cookie = tempnam ("/tmp", "CURLCOOKIE");
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
    curl_setopt( $ch, CURLOPT_ENCODING, "" );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );    # required for https urls
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
    curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
    curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 );
    $content = curl_exec( $ch );
    $response = curl_getinfo( $ch );
    curl_close ( $ch );

    if ($response['http_code'] == 301 || $response['http_code'] == 302) {
        ini_set("user_agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1");

        if ( $headers = get_headers($response['url']) ) {
            foreach( $headers as $value ) {
                if ( substr( strtolower($value), 0, 9 ) == "location:" )
                    return get_url( trim( substr( $value, 9, strlen($value) ) ) );
            }
        }
    }

    if (    ( preg_match("/>[[:space:]]+window\.location\.replace\('(.*)'\)/i", $content, $value) || preg_match("/>[[:space:]]+window\.location\=\"(.*)\"/i", $content, $value) ) && $javascript_loop < 5) {
        return get_url( $value[1], $javascript_loop+1 );
    } else {
        return array( $content, $response );
    }
}


?>

Pycharm and sys.argv arguments

Notice that for some unknown reason, it is not possible to add command line arguments in the PyCharm Edu version. It can be only done in Professional and Community editions.

Get Element value with minidom with Python

you can use something like this.It worked out for me

doc = parse('C:\\eve.xml')
my_node_list = doc.getElementsByTagName("name")
my_n_node = my_node_list[0]
my_child = my_n_node.firstChild
my_text = my_child.data 
print my_text

How to specify font attributes for all elements on an html web page?

If you specify CSS attributes for your body element it should apply to anything within <body></body> so long as you don't override them later in the stylesheet.

What are Keycloak's OAuth2 / OpenID Connect endpoints?

FQDN/auth/realms/{realm_name}/.well-known/openid-configuration

you will see everything here, plus if the identity provider is also Keycloak then feeding this URL will setup everything also true with other identity providers if they support and they already handled it

VBA equivalent to Excel's mod function

Function Remainder(Dividend As Variant, Divisor As Variant) As Variant
    Remainder = Dividend - Divisor * Int(Dividend / Divisor)
End Function

This function always works and is the exact copy of the Excel function.

curl.h no such file or directory

sudo apt-get install curl-devel

sudo apt-get install libcurl-dev

(will install the default alternative)

OR

sudo apt-get install libcurl4-openssl-dev

(the OpenSSL variant)

OR

sudo apt-get install libcurl4-gnutls-dev

(the gnutls variant)

add class with JavaScript

Here is a method adapted from Jquery 2.1.1 that take a dom element instead of a jquery object (so jquery is not needed). Includes type checks and regex expressions:

function addClass(element, value) {
    // Regex terms
    var rclass = /[\t\r\n\f]/g,
        rnotwhite = (/\S+/g);

    var classes,
        cur,
        curClass,
        finalValue,
        proceed = typeof value === "string" && value;

    if (!proceed) return element;

    classes = (value || "").match(rnotwhite) || [];

    cur = element.nodeType === 1
        && (element.className
                ? (" " + element.className + " ").replace(rclass, " ")
                : " "
        );

    if (!cur) return element;

    var j = 0;

    while ((curClass = classes[j++])) {

        if (cur.indexOf(" " + curClass + " ") < 0) {

            cur += curClass + " ";

        }

    }

    // only assign if different to avoid unneeded rendering.
    finalValue = cur.trim();

    if (element.className !== finalValue) {

        element.className = finalValue;

    }

    return element;
};

height style property doesn't work in div elements

I'm told that it's bad practice to overuse it, but you can always add !important after your code to prioritize the css properties value.

.p{height:400px!important;}

Move column by name to front of table in pandas

df.set_index('Mid').reset_index()

seems to be a pretty easy way about this.

Sending email with gmail smtp with codeigniter email library

$config = Array(
    'protocol' => 'smtp',
    'smtp_host' => 'ssl://smtp.googlemail.com',
    'smtp_port' => 465,
    'smtp_user' => 'xxx',
    'smtp_pass' => 'xxx',
    'mailtype'  => 'html', 
    'charset'   => 'iso-8859-1'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");

// Set to, from, message, etc.

$result = $this->email->send();

From the CodeIgniter Forums

How to get everything after last slash in a URL?

First extract the path element from the URL:

from urllib.parse import urlparse
parsed= urlparse('https://www.dummy.example/this/is/PATH?q=/a/b&r=5#asx')

and then you can extract the last segment with string functions:

parsed.path.rpartition('/')[2]

(example resulting to 'PATH')

What Process is using all of my disk IO

You're looking for iotop (assuming you've got kernel >2.6.20 and Python 2.5). Failing that, you're looking into hooking into the filesystem. I recommend the former.

Binding Button click to a method

You have various possibilies. The most simple and the most ugly is:

XAML

<Button Name="cmdCommand" Click="Button_Clicked" Content="Command"/> 

Code Behind

private void Button_Clicked(object sender, RoutedEventArgs e) { 
    FrameworkElement fe=sender as FrameworkElement;
    ((YourClass)fe.DataContext).DoYourCommand();     
} 

Another solution (better) is to provide a ICommand-property on your YourClass. This command will have already a reference to your YourClass-object and therefore can execute an action on this class.

XAML

<Button Name="cmdCommand" Command="{Binding YourICommandReturningProperty}" Content="Command"/>

Because during writing this answer, a lot of other answers were posted, I stop writing more. If you are interested in one of the ways I showed or if you think I have made a mistake, make a comment.

How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?

The project JsonSubTypes implement a generic converter that handle this feature with the helps of attributes.

For the concrete sample provided here is how it works:

    [JsonConverter(typeof(JsonSubtypes))]
    [JsonSubtypes.KnownSubTypeWithProperty(typeof(Employee), "JobTitle")]
    [JsonSubtypes.KnownSubTypeWithProperty(typeof(Artist), "Skill")]
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class Employee : Person
    {
        public string Department { get; set; }
        public string JobTitle { get; set; }
    }

    public class Artist : Person
    {
        public string Skill { get; set; }
    }

    [TestMethod]
    public void Demo()
    {
        string json = "[{\"Department\":\"Department1\",\"JobTitle\":\"JobTitle1\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}," +
                      "{\"Department\":\"Department1\",\"JobTitle\":\"JobTitle1\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}," +
                      "{\"Skill\":\"Painter\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}]";


        var persons = JsonConvert.DeserializeObject<IReadOnlyCollection<Person>>(json);
        Assert.AreEqual("Painter", (persons.Last() as Artist)?.Skill);
    }

Promise Error: Objects are not valid as a React child

You can't just return an array of objects because there's nothing telling React how to render that. You'll need to return an array of components or elements like:

render: function() {
  return (
    <span>
      // This will go through all the elements in arrayFromJson and
      // render each one as a <SomeComponent /> with data from the object
      {this.state.arrayFromJson.map(function(object) {
        return (
          <SomeComponent key={object.id} data={object} />
        );
      })}
    </span>
  );
}