Programs & Examples On #Winforms

WinForms is the informal name given to Windows Forms, a GUI class library in the Microsoft .NET Framework and Mono. Questions in this tag should also be tagged with the target framework ([.net] or [mono]) and should ordinarily be tagged with a programming language tag.

Check if a specific tab page is selected (active)

To check if a specific tab page is the currently selected page of a tab control is easy; just use the SelectedTab property of the tab control:

if (tabControl1.SelectedTab == someTabPage)
{
// Do stuff here...
}

This is more useful if the code is executed based on some event other than the tab page being selected (in which case SelectedIndexChanged would be a better choice).

For example I have an application that uses a timer to regularly poll stuff over TCP/IP connection, but to avoid unnecessary TCP/IP traffic I only poll things that update GUI controls in the currently selected tab page.

Adding Text to DataGridView Row Header

I think it should be:

dataGridView1.Columns[0].HeaderCell.Value = "my text";

Search for value in DataGridView in a column

"MyTable".DefaultView.RowFilter = " LIKE '%" + textBox1.Text + "%'"; this.dataGridView1.DataSource = "MyTable".DefaultView;

How about the relation to the database connections and the Datatable? And how should i set the DefaultView correct?

I use this code to get the data out:

con = new System.Data.SqlServerCe.SqlCeConnection();
con.ConnectionString = "Data Source=C:\\Users\\mhadj\\Documents\\Visual Studio 2015\\Projects\\data_base_test_2\\Sample.sdf";
con.Open();

DataTable dt = new DataTable();

adapt = new System.Data.SqlServerCe.SqlCeDataAdapter("select * from tbl_Record", con);        
adapt.Fill(dt);        
dataGridView1.DataSource = dt;
con.Close();

How do I drag and drop files into an application?

You need to be aware of a gotcha. Any class that you pass around as the DataObject in the drag/drop operation has to be Serializable. So if you try and pass an object, and it is not working, ensure it can be serialized as that is almost certainly the problem. This has caught me out a couple of times!

Execute specified function every X seconds

Use System.Windows.Forms.Timer.

private Timer timer1; 
public void InitTimer()
{
    timer1 = new Timer();
    timer1.Tick += new EventHandler(timer1_Tick);
    timer1.Interval = 2000; // in miliseconds
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    isonline();
}

You can call InitTimer() in Form1_Load().

Single Form Hide on Startup

This example supports total invisibility as well as only NotifyIcon in the System tray and no clicks and much more.

More here: http://code.msdn.microsoft.com/TheNotifyIconExample

How to get full file path from file name?

Directory.GetCurrentDirectory

string dirpath = Directory.GetCurrentDirectory();

Prepend this dirpath to the filename to get the complete path.

As @Dan Puzey indicated in the comments, it would be better to use Path.Combine

Path.Combine(Directory.GetCurrentDirectory(), filename)

Check if TextBox is empty and return MessageBox?

Becasue is a TextBox already initialized would be better to control if there is something in there outside the empty string (which is no null or empty string I am afraid). What I did is just check is there is something different than "", if so do the thing:

 if (TextBox.Text != "") //Something different than ""?
        {
            //Do your stuff
        }
 else
        {
            //Do NOT do your stuff
        }

Change default icon

Go to the Project properties Build the project Locate the .exe file in your favorite file explorer.

Cannot access a disposed object - How to fix?

Another place you could stop the timer is the FormClosing event - this happens before the form is actually closed, so is a good place to stop things before they might access unavailable resources.

How to set combobox default value?

You can do something like this:

    public myform()
    {
         InitializeComponent(); // this will be called in ComboBox ComboBox = new System.Windows.Forms.ComboBox();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'myDataSet.someTable' table. You can move, or remove it, as needed.
        this.myTableAdapter.Fill(this.myDataSet.someTable);
        comboBox1.SelectedItem = null;
        comboBox1.SelectedText = "--select--";           
    }

Get access to parent control from user control - C#

((frmMain)this.Owner).MyListControl.Items.Add("abc");

Make sure to provide access level you want at Modifiers properties other than Private for MyListControl at frmMain

How to make a window always stay on top in .Net?

The way i solved this was by making a system tray icon that had a cancel option.

"Input string was not in a correct format."

If you are not validating explicitly for numbers in the text field, in any case its better to use

int result=0;
if(int.TryParse(textBox1.Text,out result))

Now if the result is success then you can proceed with your calculations.

Check if a record exists in the database

Use the method Int.Parse() instead. It will work.

How do you show animated GIFs on a Windows Form (c#)

Public Class Form1

    Private animatedimage As New Bitmap("C:\MyData\Search.gif")
    Private currentlyanimating As Boolean = False

    Private Sub OnFrameChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

        Me.Invalidate()

    End Sub

    Private Sub AnimateImage()

        If currentlyanimating = True Then
            ImageAnimator.Animate(animatedimage, AddressOf Me.OnFrameChanged)
            currentlyanimating = False
        End If

    End Sub

    Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)

        AnimateImage()
        ImageAnimator.UpdateFrames(animatedimage)
        e.Graphics.DrawImage(animatedimage, New Point((Me.Width / 4) + 40, (Me.Height / 4) + 40))

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        BtnStop.Enabled = False

    End Sub

    Private Sub BtnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStop.Click

        currentlyanimating = False
        ImageAnimator.StopAnimate(animatedimage, AddressOf Me.OnFrameChanged)
        BtnStart.Enabled = True
        BtnStop.Enabled = False

    End Sub

    Private Sub BtnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnStart.Click

        currentlyanimating = True
        AnimateImage()
        BtnStart.Enabled = False
        BtnStop.Enabled = True

    End Sub

End Class

Load a bitmap image into Windows Forms using open file dialog

You can try the following:

private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog fDialog = new OpenFileDialog();
        fDialog.Title = "Select file to be upload";
        fDialog.Filter = "All Files|*.*";
        //  fDialog.Filter = "PDF Files|*.pdf";
        if (fDialog.ShowDialog() == DialogResult.OK)
        {
            textBox1.Text = fDialog.FileName.ToString();
        }
    }

Open Form2 from Form1, close Form1 from Form2

Your question is vague but you could use ShowDialog to display form 2. Then when you close form 2, pass a DialogResult object back to let the user know how the form was closed - if the user clicked the button, then close form 1 as well.

How to change the color of winform DataGridview header?

dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;

Binding Combobox Using Dictionary as the Datasource

        var colors = new Dictionary < string, string > ();
        colors["10"] = "Red";

Binding to Combobox

        comboBox1.DataSource = new BindingSource(colors, null);
        comboBox1.DisplayMember = "Value";
        comboBox1.ValueMember = "Key"; 

Full Source...Dictionary as a Combobox Datasource

Jeryy

How do I make an Event in the Usercontrol and have it handled in the Main Form?

Try mapping it. Try placing this code in your UserControl:

public event EventHandler ValueChanged {
  add { numericUpDown1.ValueChanged += value; }
  remove { numericUpDown1.ValueChanged -= value; }
}

then your UserControl will have the ValueChanged event you normally see with the NumericUpDown control.

Using FileSystemWatcher to monitor a directory

The reason may be that watcher is declared as local variable to a method and it is garbage collected when the method finishes. You should declare it as a class member. Try the following:

FileSystemWatcher watcher;

private void watch()
{
  watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                         | NotifyFilters.FileName | NotifyFilters.DirectoryName;
  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

private void OnChanged(object source, FileSystemEventArgs e)
{
  //Copies file to another directory.
}

How to set column header text for specific column in Datagridview C#

private void datagrid_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    string test = this.datagrid.Columns[e.ColumnIndex].HeaderText;
}

This code will get the HeaderText value.

How to set selected value from Combobox?

Use the SelectedIndex property for the respective employee status in the combo box.

How to call a method daily, at specific time, in C#?

A simple example for one task:

using System;
using System.Timers;

namespace ConsoleApp
{
    internal class Scheduler
    {
        private static readonly DateTime scheduledTime = 
            new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 10, 0, 0);
        private static DateTime dateTimeLastRunTask;

        internal static void CheckScheduledTask()
        {
            if (dateTimeLastRunTask.Date < DateTime.Today && scheduledTime.TimeOfDay < DateTime.Now.TimeOfDay)
            {
                Console.WriteLine("Time to run task");
                dateTimeLastRunTask = DateTime.Now;
            }
            else
            {
                Console.WriteLine("not yet time");
            }
        }
    }

    internal class Program
    {
        private static Timer timer;

        static void Main(string[] args)
        {
            timer = new Timer(5000);
            timer.Elapsed += OnTimer;
            timer.Start();
            Console.ReadLine();
        }

        private static void OnTimer(object source, ElapsedEventArgs e)
        {
            Scheduler.CheckScheduledTask();
        }
    }
}

How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?

A little improvement from Schnapple's version

int nLastColumn = dgv.Columns.Count - 1;
for (int i = 0; i < dgv.Columns.Count; i++)
{
    if (nLastColumn == i)
    {
        dgv.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
    }
    else
    {
        dgv.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
    }
}

for (int i = 0; i < dgv.Columns.Count; i++)
{
    int colw = dgv.Columns[i].Width;
    dgv.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
    dgv.Columns[i].Width = colw;
}

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

MessageBox.Show(
  "your message",
  "window title", 
  MessageBoxButtons.OK, 
  MessageBoxIcon.Asterisk //For Info Asterisk
  MessageBoxIcon.Exclamation //For triangle Warning 
)

Developing C# on Linux

You can also install it using conda (tested on Ubuntu):

conda create --name csharp
conda activate csharp
conda install -c conda-forge mono

How to use ConfigurationManager

I found some answers, but I don't know if it is the right way.This is my solution for now. Fortunatelly it didn´t broke my design mode.

    `
    /// <summary>
    /// set config, if key is not in file, create
    /// </summary>
    /// <param name="key">Nome do parâmetro</param>
    /// <param name="value">Valor do parâmetro</param>
    public static void SetConfig(string key, string value)
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.AppSettings.Settings;
        if (settings[key] == null)
        {
            settings.Add(key, value);
        }
        else
        {
            settings[key].Value = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
    }

    /// <summary>
    /// Get key value, if not found, return null
    /// </summary>
    /// <param name="key"></param>
    /// <returns>null if key is not found, else string with value</returns>
    public static string GetConfig(string key)
    {
        return ConfigurationManager.AppSettings[key];
    }`

How to disable textbox from editing?

The TextBox has a property called ReadOnly. If you set that property to true then the TextBox will still be able to scroll but the user wont be able to change the value.

Automating the InvokeRequired code pattern

Here's the form I've been using in all my code.

private void DoGUISwitch()
{ 
    Invoke( ( MethodInvoker ) delegate {
        object1.Visible = true;
        object2.Visible = false;
    });
} 

I've based this on the blog entry here. I have not had this approach fail me, so I see no reason to complicate my code with a check of the InvokeRequired property.

Hope this helps.

How to make a TextBox accept only alphabetic characters?

Try following code in KeyPress event of textbox

if (char.IsLetter(e.KeyChar) == false  & 
        Convert.ToString(e.KeyChar) != Microsoft.VisualBasic.Constants.vbBack)
            e.Handled = true

Color different parts of a RichTextBox string

I created this Function after researching on the internet since I wanted to print an XML string when you select a row from a data grid view.

static void HighlightPhrase(RichTextBox box, string StartTag, string EndTag, string ControlTag, Color color1, Color color2)
{
    int pos = box.SelectionStart;
    string s = box.Text;
    for (int ix = 0; ; )
    {
        int jx = s.IndexOf(StartTag, ix, StringComparison.CurrentCultureIgnoreCase);
        if (jx < 0) break;
        int ex = s.IndexOf(EndTag, ix, StringComparison.CurrentCultureIgnoreCase);
        box.SelectionStart = jx;
        box.SelectionLength = ex - jx + 1;
        box.SelectionColor = color1;
        
        int bx = s.IndexOf(ControlTag, ix, StringComparison.CurrentCultureIgnoreCase);
        int bxtest = s.IndexOf(StartTag, (ex + 1), StringComparison.CurrentCultureIgnoreCase);
        if (bx == bxtest)
        {
            box.SelectionStart = ex + 1;
            box.SelectionLength = bx - ex + 1;
            box.SelectionColor = color2;
        }
        
        ix = ex + 1;
    }
    box.SelectionStart = pos;
    box.SelectionLength = 0;
}

and this is how you call it

   HighlightPhrase(richTextBox1, "<", ">","</", Color.Red, Color.Black);

How to show text in combobox when no item selected?

One line after form InitializeComponent();

cbo_MyDropBox.Text = "Select a server...";

You only need it once right? All you need to do if a pick is mandatory is check if the box index != -1. Could anyone elaborate why the other answers jump through hoops to get this going?

The only thing I'm missing here is having just this initial text grayed out. If you really want that just use a label in front and turn it off once the index is changed.

How to make a form close when pressing the escape key?

The best way i found is to override the "ProcessDialogKey" function. This way canceling a open control is still possible because the function is only called when no other control uses the pressed Key.

This is the same behaviour as when setting a CancelButton. Using the KeyDown Event fires always and thus the form would close even when it should cancel the edit of an open editor.

protected override bool ProcessDialogKey(Keys keyData)
{
    if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
    {
        this.Close();
        return true;
    }
    return base.ProcessDialogKey(keyData);
}

How can I right-align text in a DataGridView column?

this.dataGridView1.Columns["CustomerName"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; 

How to get values from selected row in DataGrid for Windows Form Application?

You could just use

DataGridView1.CurrentRow.Cells["ColumnName"].Value

How to fit Windows Form to any screen resolution?

You can always tell the window to start in maximized... it should give you the same result... Like this: this.WindowState = FormWindowState.Maximized;

P.S. You could also try (and I'm not recommending this) to subtract the taskbar height.

Changing the default icon in a Windows Forms application

You can change the app icon under project properties. Individual form icons under form properties.

Binding an enum to a WinForms combo box, and then setting it

You can use a list of KeyValuePair values as the datasource for the combobox. You will need a helper method where you can specify the enum type and it returns IEnumerable> where int is the value of enum and string is the name of the enum value. In your combobox, set, DisplayMember property to 'Key' and ValueMember property to 'Value'. Value and Key are public properties of KeyValuePair structure. Then when you set SelectedItem property to an enum value like you are doing, it should work.

How do I add a ToolTip to a control?

ToolTip in C# is very easy to add to almost all UI controls. You don't need to add any MouseHover event for this.

This is how to do it-

  1. Add a ToolTip object to your form. One object is enough for the entire form. ToolTip toolTip = new ToolTip();

  2. Add the control to the tooltip with the desired text.

    toolTip.SetToolTip(Button1,"Click here");

How do I rotate a picture in WinForms

I've written a simple class for rotating image. All you've to do is input image and angle of rotation in Degree. Angle must be between -90 and +90.

public class ImageRotator
{
    private readonly Bitmap image;
    public Image OriginalImage
    {
        get { return image; }
    }


    private ImageRotator(Bitmap image)
    {
        this.image = image;
    }


    private double GetRadian(double degree)
    {
        return degree * Math.PI / (double)180;
    }


    private Size CalculateSize(double angle)
    {
        double radAngle = GetRadian(angle);
        int width = (int)(image.Width * Math.Cos(radAngle) + image.Height * Math.Sin(radAngle));
        int height = (int)(image.Height * Math.Cos(radAngle) + image.Width * Math.Sin(radAngle));
        return new Size(width, height);
    }

    private PointF GetTopCoordinate(double radAngle)
    {
        Bitmap image = CurrentlyViewedMappedImage.BitmapImage;
        double topX = 0;
        double topY = 0;

        if (radAngle > 0)
        {
            topX = image.Height * Math.Sin(radAngle);
        }
        if (radAngle < 0)
        {
            topY = image.Width * Math.Sin(-radAngle);
        }
        return new PointF((float)topX, (float)topY);
    }

    public Bitmap RotateImage(double angle)
    {
        SizeF size = CalculateSize(radAngle);
        Bitmap rotatedBmp = new Bitmap((int)size.Width, (int)size.Height);

        Graphics g = Graphics.FromImage(rotatedBmp);
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        g.CompositingQuality = CompositingQuality.HighQuality;
        g.SmoothingMode = SmoothingMode.HighQuality;
        g.PixelOffsetMode = PixelOffsetMode.HighQuality;

        g.TranslateTransform(topPoint.X, topPoint.Y);
        g.RotateTransform(GetDegree(radAngle));
        g.DrawImage(image, new RectangleF(0, 0, size.Width, size.Height));

        g.Dispose();
        return rotatedBmp;
    }


    public static class Builder
    {
        public static ImageRotator CreateInstance(Image image)
        {
            ImageRotator rotator = new ImageRotator(image as Bitmap);
            return rotator;
        }
    }
}

How to know user has clicked "X" or the "Close" button?

I've done something like this.

private void Form_FormClosing(object sender, FormClosingEventArgs e)
    {
        if ((sender as Form).ActiveControl is Button)
        {
            //CloseButton
        }
        else
        {
            //The X has been clicked
        }
    }

How do I center a window onscreen in C#?

A single line:

this.Location = new Point((Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2,
                          (Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2);

Override standard close (X) button in a Windows Form

One thing these answers lack, and which newbies are probably looking for, is that while it's nice to have an event:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    // do something
}

It's not going to do anything at all unless you register the event. Put this in the class constructor:

this.FormClosing += Form1_FormClosing;

How to select a node of treeview programmatically in c#?

yourNode.Toggle(); //use that function on your node, it toggles it

Using Exit button to close a winform program

Try this:

private void btnExitProgram_Click(object sender, EventArgs e) {
    this.Close();
}

How should you diagnose the error SEHException - External component has thrown an exception

I have come across this error when the app resides on a network share, and the device (laptop, tablet, ...) becomes disconnected from the network while the app is in use. In my case, it was due to a Surface tablet going out of wireless range. No problems after installing a better WAP.

User Control - Custom Properties

You do this via attributes on the properties, like this:

[Description("Test text displayed in the textbox"),Category("Data")] 
public string Text {
  get => myInnerTextBox.Text;
  set => myInnerTextBox.Text = value;
}

The category is the heading under which the property will appear in the Visual Studio Properties box. Here's a more complete MSDN reference, including a list of categories.

How do I disable form resizing for users?

I would set the maximum size, minimum size and remove the gripper icon of the window.

Set properties (MaximumSize, MinimumSize, and SizeGripStyle):

this.MaximumSize = new System.Drawing.Size(500, 550);
this.MinimumSize = new System.Drawing.Size(500, 550);
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;

How to add new line into txt file

Why not do it with one method call:

File.AppendAllLines("file.txt", new[] { DateTime.Now.ToString() });

which will do the newline for you, and allow you to insert multiple lines at once if you want.

How can I make a .NET Windows Forms application that only runs in the System Tray?

  1. Create a new Windows Application with the wizard.
  2. Delete Form1 from the code.
  3. Remove the code in Program.cs starting up the Form1.
  4. Use the NotifyIcon class to create your system tray icon (assign an icon to it).
  5. Add a contextmenu to it.
  6. Or react to NotifyIcon's mouseclick and differenciate between Right and Left click, setting your contextmenu and showing it for which ever button (right/left) was pressed.
  7. Application.Run() to keep the app running with Application.Exit() to quit. Or a bool bRunning = true; while(bRunning){Application.DoEvents(); Thread.Sleep(10);}. Then set bRunning = false; to exit the app.

How to add a form load event (currently not working)

You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:

 public class ProgramViwer : Form{
  public ProgramViwer()
  {
       InitializeComponent();
       Load += new EventHandler(ProgramViwer_Load);
  }
  private void ProgramViwer_Load(object sender, System.EventArgs e)
  {
       formPanel.Controls.Clear();
       formPanel.Controls.Add(wel);
  }
}

SaveFileDialog setting default path and file type?

Here's an example that actually filters for BIN files. Also Windows now want you to save files to user locations, not system locations, so here's an example (you can use intellisense to browse the other options):

            var saveFileDialog = new Microsoft.Win32.SaveFileDialog()
            {
                DefaultExt = "*.xml",
                Filter = "BIN Files (*.bin)|*.bin",
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
            };

            var result = saveFileDialog.ShowDialog();
            if (result != null && result == true)
            {
                // Save the file here
            }

Getting the first and last day of a month, using a given DateTime object

I used this in my script(works for me) but I needed a full date without the need of trimming it to only the date and no time.

public DateTime GetLastDayOfTheMonth()
{
    int daysFromNow = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month) - (int)DateTime.Now.Day;
    return DateTime.Now.AddDays(daysFromNow);
}

Find a row in dataGridView based on column and value

Or you can use like this. This may be faster.

int iFindNo = 14;
int j = dataGridView1.Rows.Count-1;
int iRowIndex = -1;
for (int i = 0; i < Convert.ToInt32(dataGridView1.Rows.Count/2) +1; i++)
{
    if (Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value) == iFindNo)
    {
        iRowIndex = i;
        break;
    }
    if (Convert.ToInt32(dataGridView1.Rows[j].Cells[0].Value) == iFindNo)
    {
        iRowIndex = j;
        break;
    }
    j--;
}
if (iRowIndex != -1)
    MessageBox.Show("Index is " + iRowIndex.ToString());
else
    MessageBox.Show("Index not found." );

How do I pass command-line arguments to a WinForms application?

Consider you need to develop a program through which you need to pass two arguments. First of all, you need to open Program.cs class and add arguments in the Main method as like below and pass these arguments to the constructor of the Windows form.

static class Program
{    
   [STAThread]
   static void Main(string[] args)
   {            
       Application.EnableVisualStyles();
       Application.SetCompatibleTextRenderingDefault(false);
       Application.Run(new Form1(args[0], Convert.ToInt32(args[1])));           
   }
}

In windows form class, add a parameterized constructor which accepts the input values from Program class as like below.

public Form1(string s, int i)
{
    if (s != null && i > 0)
       MessageBox.Show(s + " " + i);
}

To test this, you can open command prompt and go to the location where this exe is placed. Give the file name then parmeter1 parameter2. For example, see below

C:\MyApplication>Yourexename p10 5

From the C# code above, it will prompt a Messagebox with value p10 5.

Filtering DataGridView without changing datasource

I developed a generic statement to apply the filter:

string rowFilter = string.Format("[{0}] = '{1}'", columnName, filterValue);
(myDataGridView.DataSource as DataTable).DefaultView.RowFilter = rowFilter;

The square brackets allow for spaces in the column name.

Additionally, if you want to include multiple values in your filter, you can add the following line for each additional value:

rowFilter += string.Format(" OR [{0}] = '{1}'", columnName, additionalFilterValue);

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

Just add a new form and add buttons and a label. Give the value to be shown and the text of the button, etc. in its constructor, and call it from anywhere you want in the project.

In project -> Add Component -> Windows Form and select a form

Add some label and buttons.

Initialize the value in constructor and call it from anywhere.

public class form1:System.Windows.Forms.Form
{
    public form1()
    {
    }

    public form1(string message,string buttonText1,string buttonText2)
    {
       lblMessage.Text = message;
       button1.Text = buttonText1;
       button2.Text = buttonText2;
    }
}

// Write code for button1 and button2 's click event in order to call 
// from any where in your current project.

// Calling

Form1 frm = new Form1("message to show", "buttontext1", "buttontext2");
frm.ShowDialog();

How to force C# .net app to run only one instance in Windows?

I prefer a mutex solution similar to the following. As this way it re-focuses on the app if it is already loaded

using System.Threading;

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
   bool createdNew = true;
   using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))
   {
      if (createdNew)
      {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new MainForm());
      }
      else
      {
         Process current = Process.GetCurrentProcess();
         foreach (Process process in Process.GetProcessesByName(current.ProcessName))
         {
            if (process.Id != current.Id)
            {
               SetForegroundWindow(process.MainWindowHandle);
               break;
            }
         }
      }
   }
}

Convert json to a C# array?

Yes, Json.Net is what you need. You basically want to deserialize a Json string into an array of objects.

See their examples:

string myJsonString = @"{
  "Name": "Apple",
  "Expiry": "\/Date(1230375600000+1300)\/",
  "Price": 3.99,
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ]
}";

// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);

Show Console in Windows Application?

Easiest way is to start a WinForms application, go to settings and change the type to a console application.

Word wrap for a label in Windows Forms

I would recommend setting AutoEllipsis property of label to true and AutoSize to false. If text length exceeds label bounds, it'll add three dots (...) at the end and automatically set the complete text as a tooltip. So users can see the complete text by hovering over the label.

How do I update the GUI from another thread?

Here's a new look on an age-old issue using a more functional style. If you keep the TaskXM class in all of your projects you only have one line of code to never worry about cross-thread updates again.

public class Example
{
    /// <summary>
    /// No more delegates, background workers, etc. Just one line of code as shown below.
    /// Note it is dependent on the Task Extension method shown next.
    /// </summary>
    public async void Method1()
    {
        // Still on the GUI thread here if the method was called from the GUI thread
        // This code below calls the extension method which spins up a new task and calls back.
        await TaskXM.RunCodeAsync(() =>
        {
            // Running an asynchronous task here
            // Cannot update the GUI thread here, but can do lots of work
        });
        // Can update GUI on this line
    }
}


/// <summary>
/// A class containing extension methods for the Task class
/// </summary>
public static class TaskXM
{
    /// <summary>
    /// RunCodeAsyc is an extension method that encapsulates the Task.run using a callback
    /// </summary>
    /// <param name="Code">The caller is called back on the new Task (on a different thread)</param>
    /// <returns></returns>
    public async static Task RunCodeAsync(Action Code)
    {
        await Task.Run(() =>
        {
            Code();
        });
        return;
    }
}

Which Radio button in the group is checked?

You can use the CheckedChanged event for all your RadioButtons. Sender will be the unchecked and checked RadioButtons.

How to increase the timeout period of web service in asp.net?

you can do this in different ways:

  1. Setting a timeout in the web service caller from code (not 100% sure but I think I have seen this done);
  2. Setting a timeout in the constructor of the web service proxy in the web references;
  3. Setting a timeout in the server side, web.config of the web service application.

see here for more details on the second case:

http://msdn.microsoft.com/en-us/library/ff647786.aspx#scalenetchapt10_topic14

and here for details on the last case:

How to increase the timeout to a web service request?

Create normal zip file programmatically

You can now use the ZipArchive class (System.IO.Compression.ZipArchive), available from .NET 4.5

You have to add System.IO.Compression as a reference.

Example: Generating a zip of PDF files

using (var fileStream = new FileStream(@"C:\temp\temp.zip", FileMode.CreateNew))
{
    using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Create, true))
    {
        foreach (var creditNumber in creditNumbers)
        {
            var pdfBytes = GeneratePdf(creditNumber);
            var fileName = "credit_" + creditNumber + ".pdf";
            var zipArchiveEntry = archive.CreateEntry(fileName, CompressionLevel.Fastest);
            using (var zipStream = zipArchiveEntry.Open())
                zipStream.Write(pdfBytes, 0, pdfBytes.Length);
            }
        }
    }
}

Multiple file extensions in OpenFileDialog

Based on First answer here is the complete image selection options:

Filter = @"|All Image Files|*.BMP;*.bmp;*.JPG;*.JPEG*.jpg;*.jpeg;*.PNG;*.png;*.GIF;*.gif;*.tif;*.tiff;*.ico;*.ICO
           |PNG|*.PNG;*.png
           |JPEG|*.JPG;*.JPEG*.jpg;*.jpeg
           |Bitmap(.BMP,.bmp)|*.BMP;*.bmp                                    
           |GIF|*.GIF;*.gif
           |TIF|*.tif;*.tiff
           |ICO|*.ico;*.ICO";

Find control by name from Windows Forms controls

You can use:

f.Controls[name];

Where f is your form variable. That gives you the control with name name.

Changing datagridview cell color based on condition

Let's say you have to color certain cell (not all cells of the row) by knowing two things:

  1. Name or index of the column.
  2. Value which is gonna be inside of the cell.

In thas case you have to use event CellFormatting

In my case I use like this

private void DgvTrucksMaster_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
     foreach (DataGridViewRow row in dgvTrucksMaster.Rows)
     {
       if (Convert.ToInt32(row.Cells["Decade1Hours"].Value) > 0)
       {
          row.Cells["Decade1Hours"].Style.BackColor = Color.LightGreen;
       }
       else if (Convert.ToInt32(row.Cells["Decade1Hours"].Value) < 0)
       {
          // row.DefaultCellStyle.BackColor = Color.LightSalmon; // Use it in order to colorize all cells of the row

          row.Cells["Decade1Hours"].Style.BackColor = Color.LightSalmon;
       }
     }
}

And result you can see here

enter image description here

So here you can access certain cell of the row in column by its name row.Cells["Decade1Hours"]

How do you know this name? Well in my case i create column of DataGridView like this.

var Decade1Hours = new DataGridViewTextBoxColumn()
{
   Name = "Decade1Hours",
   Width = 50,
   DataPropertyName = "Decade1Hours",
   ReadOnly = true,
   DefaultCellStyle = new DataGridViewCellStyle()
       {
        Alignment = DataGridViewContentAlignment.MiddleCenter,
        ForeColor = System.Drawing.Color.Black,
        Font = new Font(font, FontStyle.Bold),
        Format = "n2"
      },
   HeaderCell = new DataGridViewColumnHeaderCell()
      {
          Style = new DataGridViewCellStyle()
               {
                 Alignment = DataGridViewContentAlignment.MiddleCenter,
                 BackColor = System.Drawing.Color.Blue
               }
       }
};
Decade1Hours.HeaderText = "???.1";
dgvTrucksMaster.Columns.Add(Decade1Hours);

And well... you you need for instance colorize some of the cells in the row like ##1 4 5 and 8 you have to use cell index (it starts from 0).

And code will lok like

 private void DgvTrucksMaster_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
  foreach (DataGridViewRow row in dgvTrucksMaster.Rows)
  {
    if (Convert.ToInt32(row.Cells[1].Value) > 0 )
    {
      row.Cells[1].Style.BackColor = Color.LightGreen;
    }
  }
}

Set form backcolor to custom color

With Winforms you can use Form.BackColor to do this.
From within the Form's code:

BackColor = Color.LightPink;

If you mean a WPF Window you can use the Background property.
From within the Window's code:

Background = Brushes.LightPink;

Change the Textbox height?

The following code added in your constructor after calling InitializeComponent() will make it possible to programmatically set your text box to the correct height without a) changing the Multiline property, b) having to hardcode a height, or c) mucking with the Designer-generated code. It still isn't necessarily as clean or nice as doing it in a custom control, but it's fairly simple and robust:

if (txtbox.BorderStyle == BorderStyle.None)
{
    txtbox.BorderStyle = BorderStyle.FixedSingle;
    var heightWithBorder = txtbox.ClientRectangle.Height;
    txtbox.BorderStyle = BorderStyle.None;
    txtbox.AutoSize = false;
    txtbox.Height = heightWithBorder;
}

I decided to make it cleaner and easier to use by putting it in a static class and make it an extension method on TextBox:

public static class TextBoxExtensions
{
    public static void CorrectHeight(this TextBox txtbox)
    {
        if (txtbox.BorderStyle == BorderStyle.None)
        {
            txtbox.BorderStyle = BorderStyle.FixedSingle;
            var heightWithBorder = txtbox.ClientRectangle.Height;
            txtbox.BorderStyle = BorderStyle.None;
            txtbox.AutoSize = false;
            txtbox.Height = heightWithBorder;
        }
    }
}

How can I send a file document to the printer and have it print?

The easy way:

var pi=new ProcessStartInfo("C:\file.docx");
pi.UseShellExecute = true;
pi.Verb = "print";
var process =  System.Diagnostics.Process.Start(pi);

How do I change a PictureBox's image?

Assign a new Image object to your PictureBox's Image property. To load an Image from a file, you may use the Image.FromFile method. In your particular case, assuming the current directory is one under bin, this should load the image bin/Pics/image1.jpg, for example:

pictureBox1.Image = Image.FromFile("../Pics/image1.jpg");

Additionally, if these images are static and to be used only as resources in your application, resources would be a much better fit than files.

Only allow specific characters in textbox

Intercept the KeyPressed event is in my opinion a good solid solution. Pay attention to trigger code characters (e.KeyChar lower then 32) if you use a RegExp.

But in this way is still possible to inject characters out of range whenever the user paste text from the clipboard. Unfortunately I did not found correct clipboard events to fix this.

So a waterproof solution is to intercept TextBox.TextChanged. Here is sometimes the original out of range character visible, for a short time. I recommend to implement both.

using System.Text.RegularExpressions;

private void Form1_Shown(object sender, EventArgs e)
{
    filterTextBoxContent(textBox1);
}


string pattern = @"[^0-9^+^\-^/^*^(^)]";

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if(e.KeyChar >= 32 && Regex.Match(e.KeyChar.ToString(), pattern).Success) { e.Handled = true; }
}

private void textBox1_TextChanged(object sender, EventArgs e)
{
    filterTextBoxContent(textBox1);
}

private bool filterTextBoxContent(TextBox textBox)
{
    string text = textBox.Text;

    MatchCollection matches = Regex.Matches(text, pattern);
    bool matched = false;

    int selectionStart = textBox.SelectionStart;
    int selectionLength = textBox.SelectionLength;

    int leftShift = 0;
    foreach (Match match in matches)
    {
        if (match.Success && match.Captures.Count > 0)
        {
            matched = true;
            Capture capture = match.Captures[0];

            int captureLength = capture.Length;
            int captureStart = capture.Index - leftShift;
            int captureEnd = captureStart + captureLength;

            int selectionEnd = selectionStart + selectionLength;

            text = text.Substring(0, captureStart) + text.Substring(captureEnd, text.Length - captureEnd);

            textBox.Text = text;

            int boundSelectionStart = selectionStart < captureStart ? -1 : (selectionStart < captureEnd ? 0 : 1);
            int boundSelectionEnd = selectionEnd < captureStart ? -1 : (selectionEnd < captureEnd ? 0 : 1);

            if (boundSelectionStart == -1)
            {
                if (boundSelectionEnd == 0)
                {
                    selectionLength -= selectionEnd - captureStart;
                }
                else if (boundSelectionEnd == 1)
                {
                    selectionLength -= captureLength;
                }
            }
            else if (boundSelectionStart == 0)
            {
                if (boundSelectionEnd == 0)
                {
                    selectionStart = captureStart;
                    selectionLength = 0;
                }
                else if (boundSelectionEnd == 1)
                {
                    selectionStart = captureStart;
                    selectionLength -= captureEnd - selectionStart;
                }
            }
            else if (boundSelectionStart == 1)
            {
                selectionStart -= captureLength;
            }

            leftShift++;
        }
    }

    textBox.SelectionStart = selectionStart;
    textBox.SelectionLength = selectionLength;

    return matched;
}

Datagridview: How to set a cell in editing mode?

I know this question is pretty old, but figured I'd share some demo code this question helped me with.

  • Create a Form with a Button and a DataGridView
  • Register a Click event for button1
  • Register a CellClick event for DataGridView1
  • Set DataGridView1's property EditMode to EditProgrammatically
  • Paste the following code into Form1:
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 WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        DataTable m_dataTable;
        DataTable table { get { return m_dataTable; } set { m_dataTable = value; } }

        private const string m_nameCol = "Name";
        private const string m_choiceCol = "Choice";

        public Form1()
        {
            InitializeComponent();
        }

        class Options
        {
            public int m_Index { get; set; }
            public string m_Text { get; set; }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            table = new DataTable();
            table.Columns.Add(m_nameCol);
            table.Rows.Add(new object[] { "Foo" });
            table.Rows.Add(new object[] { "Bob" });
            table.Rows.Add(new object[] { "Timn" });
            table.Rows.Add(new object[] { "Fred" });

            dataGridView1.DataSource = table;

            if (!dataGridView1.Columns.Contains(m_choiceCol))
            {
                DataGridViewTextBoxColumn txtCol = new DataGridViewTextBoxColumn();
                txtCol.Name = m_choiceCol;
                dataGridView1.Columns.Add(txtCol);
            }

            List<Options> oList = new List<Options>();
            oList.Add(new Options() { m_Index = 0, m_Text = "None" });
            for (int i = 1; i < 10; i++)
            {
                oList.Add(new Options() { m_Index = i, m_Text = "Op" + i });
            }

            for (int i = 0; i < dataGridView1.Rows.Count - 1; i += 2)
            {
                DataGridViewComboBoxCell c = new DataGridViewComboBoxCell();

                //Setup A
                c.DataSource = oList;
                c.Value = oList[0].m_Text;
                c.ValueMember = "m_Text";
                c.DisplayMember = "m_Text";
                c.ValueType = typeof(string);

                ////Setup B
                //c.DataSource = oList;
                //c.Value = 0;
                //c.ValueMember = "m_Index";
                //c.DisplayMember = "m_Text";
                //c.ValueType = typeof(int);

                //Result is the same A or B
                dataGridView1[m_choiceCol, i] = c;
            }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                if (dataGridView1.CurrentCell.ColumnIndex == dataGridView1.Columns.IndexOf(dataGridView1.Columns[m_choiceCol]))
                {
                    DataGridViewCell cell = dataGridView1[m_choiceCol, e.RowIndex];
                    dataGridView1.CurrentCell = cell;
                    dataGridView1.BeginEdit(true);
                }
            }
        }
    }
}

Note that the column index numbers can change from multiple button presses of button one, so I always refer to the columns by name not index value. I needed to incorporate David Hall's answer into my demo that already had ComboBoxes so his answer worked really well.

How do I write a backslash (\) in a string?

Just escape the "\" by using + "\\Tasks" or use a verbatim string like @"\Tasks"

How to programmatically set cell value in DataGridView?

If you don't want to modify the databound object from some reason (for example you want to show some view in your grid, but you don't want it as a part of the datasource object), you might want to do this:

1.Add column manually:

    DataGridViewColumn c = new DataGridViewColumn();
    DataGridViewCell cell = new DataGridViewTextBoxCell();

    c.CellTemplate = cell;
    c.HeaderText = "added";
    c.Name = "added";
    c.Visible = true;
dgv.Columns.Insert(0, c); 

2.In the DataBindingComplete event do something like this:

foreach (DataGridViewRow row in dgv.Rows)
{if (row.Cells[7].Value.ToString()=="1")
row.Cells[0].Value = "number one"; }

(just a stupid example)

but remember IT HAS to be in the DataBindingComplete, otherwise value will remain blank

How do I get the SelectedItem or SelectedIndex of ListView in vb.net?

VB6: Listview1.selecteditem

VB10: Listview1.FocusedItem.Text

How do you change the text in the Titlebar in Windows Forms?

All the answers that include creating an new object from Form class are absolutely creating new form. But you can use Text property of ActiveForm subclass in Form class. For example:

        public Form1()
    {
        InitializeComponent();
        Form1.ActiveForm.Text = "Your Title";
    }

How do I show a console output/window in a forms application?

If you are not worrying about opening a console on-command, you can go into the properties for your project and change it to Console Application

screenshot of changing the project type.

This will still show your form as well as popping up a console window. You can't close the console window, but it works as an excellent temporary logger for debugging.

Just remember to turn it back off before you deploy the program.

Easiest way to change font and font size

You can also create a varible and then assign it for a text. It is cool because you can assign it two or more texts.

To assign a variable do that

public partial class Sayfa1 : Form

   Font Normal = new Font("Segoe UI", 9, FontStyle.Bold);

    public Sayfa1()

This varible is not assigned to any text yet.To do it write the name of the text(Look proporties -> (Name)) then write ".Font" then call the name of your font variable.

lupusToolStripMenuItem.Font = Normal;

Now you have a text assigned to a Normal font. I hope I could be helpful.

Winforms TableLayoutPanel adding rows programmatically

It's a weird design, but the TableLayoutPanel.RowCount property doesn't reflect the count of the RowStyles collection, and similarly for the ColumnCount property and the ColumnStyles collection.

What I've found I needed in my code was to manually update RowCount/ColumnCount after making changes to RowStyles/ColumnStyles.

Here's an example of code I've used:

    /// <summary>
    /// Add a new row to our grid.
    /// </summary>
    /// The row should autosize to match whatever is placed within.
    /// <returns>Index of new row.</returns>
    public int AddAutoSizeRow()
    {
        Panel.RowStyles.Add(new RowStyle(SizeType.AutoSize));
        Panel.RowCount = Panel.RowStyles.Count;
        mCurrentRow = Panel.RowCount - 1;
        return mCurrentRow;
    }

Other thoughts

  • I've never used DockStyle.Fill to make a control fill a cell in the Grid; I've done this by setting the Anchors property of the control.

  • If you're adding a lot of controls, make sure you call SuspendLayout and ResumeLayout around the process, else things will run slow as the entire form is relaid after each control is added.

Detect WebBrowser complete page loading

You can use the event ProgressChanged ; the last time it is raised will indicate that the document is fully rendered:

this.webBrowser.ProgressChanged += new
WebBrowserProgressChangedEventHandler(webBrowser_ProgressChanged);

Show a child form in the centre of Parent form in C#

    protected override void OnLoad(EventArgs e) {
        base.OnLoad(e);

        CenterToParent();
    }

How do I implement a progress bar in C#?

When you perform operations on Background thread and you want to update UI, you can not call or set anything from background thread. In case of WPF you need Dispatcher.BeginInvoke and in case of WinForms you need Invoke method.

WPF:

// assuming "this" is the window containing your progress bar..
// following code runs in background worker thread...
for(int i=0;i<count;i++)
{
    DoSomething();
    this.Dispatcher.BeginInvoke((Action)delegate(){
         this.progressBar.Value = (int)((100*i)/count);
    });
}

WinForms:

// assuming "this" is the window containing your progress bar..
// following code runs in background worker thread...
for(int i=0;i<count;i++)
{
    DoSomething();
    this.Invoke(delegate(){
         this.progressBar.Value = (int)((100*i)/count);
    });
}

for WinForms delegate may require some casting or you may need little help there, dont remember the exact syntax now.

How do I group Windows Form radio buttons?

Look at placing your radio buttons in a GroupBox.

Sort dataGridView columns in C# ? (Windows Form)

Use Datatable.Default.Sort property and then bind it to the datagridview.

How do I make a WinForms app go Full Screen

A tested and simple solution

I've been looking for an answer for this question in SO and some other sites, but one gave an answer was very complex to me and some others answers simply doesn't work correctly, so after a lot code testing I solved this puzzle.

Note: I'm using Windows 8 and my taskbar isn't on auto-hide mode.

I discovered that setting the WindowState to Normal before performing any modifications will stop the error with the not covered taskbar.

The code

I created this class that have two methods, the first enters in the "full screen mode" and the second leaves the "full screen mode". So you just need to create an object of this class and pass the Form you want to set full screen as an argument to the EnterFullScreenMode method or to the LeaveFullScreenMode method:

class FullScreen
{
    public void EnterFullScreenMode(Form targetForm)
    {
        targetForm.WindowState = FormWindowState.Normal;
        targetForm.FormBorderStyle = FormBorderStyle.None;
        targetForm.WindowState = FormWindowState.Maximized;
    }

    public void LeaveFullScreenMode(Form targetForm)
    {
        targetForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
        targetForm.WindowState = FormWindowState.Normal;
    }
}

Usage example

    private void fullScreenToolStripMenuItem_Click(object sender, EventArgs e)
    {
        FullScreen fullScreen = new FullScreen();

        if (fullScreenMode == FullScreenMode.No)  // FullScreenMode is an enum
        {
            fullScreen.EnterFullScreenMode(this);
            fullScreenMode = FullScreenMode.Yes;
        }
        else
        {
            fullScreen.LeaveFullScreenMode(this);
            fullScreenMode = FullScreenMode.No;
        }
    }

I have placed this same answer on another question that I'm not sure if is a duplicate or not of this one. (Link to the other question: How to display a Windows Form in full screen on top of the taskbar?)

Disable resizing of a Windows Forms form

There is far more efficient answer: just put the following instructions in the Form_Load:

Me.MinimumSize = New Size(Width, Height)
Me.MaximumSize = Me.MinimumSize

Get the cell value of a GridView row

Try changing your code to

// Get the currently selected row using the SelectedRow property.
GridViewRow row = dgCustomer.SelectedRow;

// And you respective cell's value
TextBox1.Text = row.Cells[1].Text

UPDATE: (based on my comment) If all what you are trying to get is the primary key value for the selected row then an alternate approach is to set

datakeynames="yourprimarykey"

for the gridview definition which can be accessed from the code behind like below.

TextBox1.Text = CustomersGridView.SelectedValue.ToString();

Get path to execution directory of Windows Forms application

Application.Current results in an appdomain http://msdn.microsoft.com/en-us/library/system.appdomain_members.aspx

Also this should give you the location of the assembly

AppDomain.CurrentDomain.BaseDirectory

I seem to recall there being multiple ways of getting the location of the application. but this one worked for me in the past atleast (it's been a while since i've done winforms programming :/)

How to use WinForms progress bar?

Since .NET 4.5 you can use combination of async and await with Progress for sending updates to UI thread:

private void Calculate(int i)
{
    double pow = Math.Pow(i, i);
}

public void DoWork(IProgress<int> progress)
{
    // This method is executed in the context of
    // another thread (different than the main UI thread),
    // so use only thread-safe code
    for (int j = 0; j < 100000; j++)
    {
        Calculate(j);

        // Use progress to notify UI thread that progress has
        // changed
        if (progress != null)
            progress.Report((j + 1) * 100 / 100000);
    }
}

private async void button1_Click(object sender, EventArgs e)
{
    progressBar1.Maximum = 100;
    progressBar1.Step = 1;

    var progress = new Progress<int>(v =>
    {
        // This lambda is executed in context of UI thread,
        // so it can safely update form controls
        progressBar1.Value = v;
    });

    // Run operation in another thread
    await Task.Run(() => DoWork(progress));

    // TODO: Do something after all calculations
}

Tasks are currently the preferred way to implement what BackgroundWorker does.

Tasks and Progress are explained in more detail here:

How do I put text on ProgressBar?

I have used this simple code, and it works!

for (int i = 0; i < N * N; i++)
     {
        Thread.Sleep(50);
        progressBar1.BeginInvoke(new Action(() => progressBar1.Value = i));
        progressBar1.CreateGraphics().DrawString(i.ToString() + "%", new Font("Arial",
        (float)10.25, FontStyle.Bold),
        Brushes.Red, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
     }

It just has one simple problem and this is it: when progress bar start to rising, percentage some times hide, and then appear again. I did't write it myself.I found it here: text on progressbar in c#

I used this code, and it does work.

Which passwordchar shows a black dot (•) in a winforms textbox?

Instead of copy/paste a unicode character or setting it in the code-behind you could also change the properties of the TextBox. Simply set "UseSystemPasswordChar" to True and everytghing will be done for you by the Framework. Or in code-behind:

this.txtPassword.UseSystemPasswordChar = true;

Add a property to a JavaScript object using a variable as the name?

With the advent of ES2015 Object.assign and computed property names the OP's code boils down to:

var obj = Object.assign.apply({}, $(itemsFromDom).map((i, el) => ({[el.id]: el.value})));

Submit form on pressing Enter with AngularJS

If you want to call function without form you can use my ngEnter directive:

Javascript:

angular.module('yourModuleName').directive('ngEnter', function() {
        return function(scope, element, attrs) {
            element.bind("keydown keypress", function(event) {
                if(event.which === 13) {
                    scope.$apply(function(){
                        scope.$eval(attrs.ngEnter, {'event': event});
                    });

                    event.preventDefault();
                }
            });
        };
    });

HTML:

<div ng-app="" ng-controller="MainCtrl">
    <input type="text" ng-enter="doSomething()">    
</div>

I submit others awesome directives on my twitter and my gist account.

How to programmatically modify WCF app.config endpoint address setting?

SomeServiceClient client = new SomeServiceClient();

var endpointAddress = client.Endpoint.Address; //gets the default endpoint address

EndpointAddressBuilder newEndpointAddress = new EndpointAddressBuilder(endpointAddress);
                newEndpointAddress.Uri = new Uri("net.tcp://serverName:8000/SomeServiceName/");
                client = new SomeServiceClient("EndpointConfigurationName", newEndpointAddress.ToEndpointAddress());

I did it like this. The good thing is it still picks up the rest of your endpoint binding settings from the config and just replaces the URI.

If two cells match, return value from third

=IF(ISNA(INDEX(B:B,MATCH(C2,A:A,0))),"",INDEX(B:B,MATCH(C2,A:A,0)))

Will return the answer you want and also remove the #N/A result that would appear if you couldn't find a result due to it not appearing in your lookup list.

Ross

What is the boundary in multipart/form-data?

Is the ??? free to be defined by the user?

Yes.

or is it supplied by the HTML?

No. HTML has nothing to do with that. Read below.

Is it possible for me to define the ??? as abcdefg?

Yes.

If you want to send the following data to the web server:

name = John
age = 12

using application/x-www-form-urlencoded would be like this:

name=John&age=12

As you can see, the server knows that parameters are separated by an ampersand &. If & is required for a parameter value then it must be encoded.

So how does the server know where a parameter value starts and ends when it receives an HTTP request using multipart/form-data?

Using the boundary, similar to &.

For example:

--XXX
Content-Disposition: form-data; name="name"

John
--XXX
Content-Disposition: form-data; name="age"

12
--XXX--

In that case, the boundary value is XXX. You specify it in the Content-Type header so that the server knows how to split the data it receives.

So you need to:

  • Use a value that won't appear in the HTTP data sent to the server.

  • Be consistent and use the same value everywhere in the request message.

How can I pipe stderr, and not stdout?

I just came up with a solution for sending stdout to one command and stderr to another, using named pipes.

Here goes.

mkfifo stdout-target
mkfifo stderr-target
cat < stdout-target | command-for-stdout &
cat < stderr-target | command-for-stderr &
main-command 1>stdout-target 2>stderr-target

It's probably a good idea to remove the named pipes afterward.

How to make Unicode charset in cmd.exe by default?

Open an elevated Command Prompt (run cmd as administrator). query your registry for available TT fonts to the console by:

    REG query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont"

You'll see an output like :

    0    REG_SZ    Lucida Console
    00    REG_SZ    Consolas
    936    REG_SZ    *???
    932    REG_SZ    *MS ????

Now we need to add a TT font that supports the characters you need like Courier New, we do this by adding zeros to the string name, so in this case the next one would be "000" :

    REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont" /v 000 /t REG_SZ /d "Courier New"

Now we implement UTF-8 support:

    REG ADD HKCU\Console /v CodePage /t REG_DWORD /d 65001 /f

Set default font to "Courier New":

    REG ADD HKCU\Console /v FaceName /t REG_SZ /d "Courier New" /f

Set font size to 20 :

    REG ADD HKCU\Console /v FontSize /t REG_DWORD /d 20 /f

Enable quick edit if you like :

    REG ADD HKCU\Console /v QuickEdit /t REG_DWORD /d 1 /f

Working with dictionaries/lists in R

Yes, the list type is a good approximation. You can use names() on your list to set and retrieve the 'keys':

> foo <- vector(mode="list", length=3)
> names(foo) <- c("tic", "tac", "toe")
> foo[[1]] <- 12; foo[[2]] <- 22; foo[[3]] <- 33
> foo
$tic
[1] 12

$tac
[1] 22

$toe
[1] 33

> names(foo)
[1] "tic" "tac" "toe"
> 

How to check type of object in Python?

use isinstance(v, type_name) or type(v) is type_name or type(v) == type_name,

where type_name can be one of the following:

  • None
  • bool
  • int
  • float
  • complex
  • str
  • list
  • tuple
  • set
  • dict

and, of course,

  • custom types (classes)

Mongoimport of json file

Import JSON/CSV file in MongoDB

  • wait wait
  • first check mongoimport.exe file in your bin folder(C:\Program Files\MongoDB\Server\4.4\bin) if it is not then download mongodb database tools(https://www.mongodb.com/try/download/database-tools)
  • copy extracted(unzip) files(inside unzipped bin) to bin folder(C:\Program Files\MongoDB\Server\4.4\bin)
  • copy your json file to bin folder(C:\Program Files\MongoDB\Server\4.4\bin)
  • Now open your commond prompt change its directory to bin
cd "C:\Program Files\MongoDB\Server\4.4\bin"
  • Now copy this on your commnad prompt
mongoimport -d tymongo -c test --type json --file restaurants.json
  • where d- database(tymongo-database name), c-collection(test-collection name)

FOR CSV FILE

 mongoimport -d tymongo -c test --type csv --file database2.csv --headerline

How can I make a multipart/form-data POST request using Java?

These are the Maven dependencies I have.

Java Code:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

FileBody uploadFilePart = new FileBody(uploadFile);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("upload-file", uploadFilePart);
httpPost.setEntity(reqEntity);

HttpResponse response = httpclient.execute(httpPost);

Maven Dependencies in pom.xml:

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.0.1</version>
  <scope>compile</scope>
</dependency>
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpmime</artifactId>
  <version>4.0.1</version>
  <scope>compile</scope>
</dependency>

Using variables inside strings

Use the following methods

1: Method one

var count = 123;
var message = $"Rows count is: {count}";

2: Method two

var count = 123;
var message = "Rows count is:" + count;

3: Method three

var count = 123;
var message = string.Format("Rows count is:{0}", count);

4: Method four

var count = 123;
var message = @"Rows
                count
                is:{0}" + count;

5: Method five

var count = 123;
var message = $@"Rows 
                 count 
                 is: {count}";

Is this the proper way to do boolean test in SQL?

In SQL Server you would generally use. I don't know about other database engines.

select * from users where active = 0

Oracle JDBC intermittent Connection Issue

Just to clarify - at least from what we found on our side! It is an issue with the setup of the randomizer for Linux in the JDK distribution - and we found it in Java6, not sure about Java7. The syntax for linux for the randomizer is file:///dev/urandom, but the entry in the file is (probably left/copied from Windows) as file:/dev/urandom. So then Java probably falls back on the default, which happens to be /dev/random. And which doesn't work on a headless machine!!!

Can I pass an array as arguments to a method with variable arguments in Java?

It's ok to pass an array - in fact it amounts to the same thing

String.format("%s %s", "hello", "world!");

is the same as

String.format("%s %s", new Object[] { "hello", "world!"});

It's just syntactic sugar - the compiler converts the first one into the second, since the underlying method is expecting an array for the vararg parameter.

See

Import / Export database with SQL Server Server Management Studio

Right click the database itself, Tasks -> Generate Scripts...

Then follow the wizard.

For SSMS2008+, if you want to also export the data, on the "Set Scripting Options" step, select the "Advanced" button and change "Types of data to script" from "Schema Only" to "Data Only" or "Schema and Data".

How do I use System.getProperty("line.separator").toString()?

The problem

You must NOT assume that an arbitrary input text file uses the "correct" platform-specific newline separator. This seems to be the source of your problem; it has little to do with regex.

To illustrate, on the Windows platform, System.getProperty("line.separator") is "\r\n" (CR+LF). However, when you run your Java code on this platform, you may very well have to deal with an input file whose line separator is simply "\n" (LF). Maybe this file was originally created in Unix platform, and then transferred in binary (instead of text) mode to Windows. There could be many scenarios where you may run into these kinds of situations, where you must parse a text file as input which does not use the current platform's newline separator.

(Coincidentally, when a Windows text file is transferred to Unix in binary mode, many editors would display ^M which confused some people who didn't understand what was going on).

When you are producing a text file as output, you should probably prefer the platform-specific newline separator, but when you are consuming a text file as input, it's probably not safe to make the assumption that it correctly uses the platform specific newline separator.


The solution

One way to solve the problem is to use e.g. java.util.Scanner. It has a nextLine() method that can return the next line (if one exists), correctly handling any inconsistency between the platform's newline separator and the input text file.

You can also combine 2 Scanner, one to scan the file line by line, and another to scan the tokens of each line. Here's a simple usage example that breaks each line into a List<String>. The entire file therefore becomes a List<List<String>>.

This is probably a better approach than reading the entire file into one huge String and then split into lines (which are then split into parts).

    String text
        = "row1\tblah\tblah\tblah\n"
        + "row2\t1\t2\t3\t4\r\n"
        + "row3\tA\tB\tC\r"
        + "row4";

    System.out.println(text);
    //  row1    blah    blah    blah
    //  row2    1   2   3   4
    //  row3    A   B   C
    //  row4

    List<List<String>> input = new ArrayList<List<String>>();

    Scanner sc = new Scanner(text);
    while (sc.hasNextLine()) {
        Scanner lineSc = new Scanner(sc.nextLine()).useDelimiter("\t");
        List<String> line = new ArrayList<String>();
        while (lineSc.hasNext()) {
            line.add(lineSc.next());
        }
        input.add(line);
    }
    System.out.println(input);
    // [[row1, blah, blah, blah], [row2, 1, 2, 3, 4], [row3, A, B, C], [row4]]

See also

  • Effective Java 2nd Edition, Item 25: Prefer lists to arrays

Related questions

Adding IN clause List to a JPA Query

The proper JPA query format would be:

el.name IN :inclList

If you're using an older version of Hibernate as your provider you have to write:

el.name IN (:inclList)

but that is a bug (HHH-5126) (EDIT: which has been resolved by now).

How Best to Compare Two Collections in Java and Act on Them?

I think the easiest way to do that is by using apache collections api - CollectionUtils.subtract(list1,list2) as long the lists are of the same type.

Beginner question: returning a boolean value from a function in Python

Ignoring the refactoring issues, you need to understand functions and return values. You don't need a global at all. Ever. You can do this:

def rps():
    # Code to determine if player wins
    if player_wins:
        return True

    return False

Then, just assign a value to the variable outside this function like so:

player_wins = rps()

It will be assigned the return value (either True or False) of the function you just called.


After the comments, I decided to add that idiomatically, this would be better expressed thus:

 def rps(): 
     # Code to determine if player wins, assigning a boolean value (True or False)
     # to the variable player_wins.

     return player_wins

 pw = rps()

This assigns the boolean value of player_wins (inside the function) to the pw variable outside the function.

how to change attribute "hidden" in jquery

A. Wolff was leading you in the right direction. There are several attributes where you should not be setting a string value. You must toggle it with a boolean true or false.

.attr("hidden", false) will remove the attribute the same as using .removeAttr("hidden").

.attr("hidden", "false") is incorrect and the tag remains hidden.

You should not be setting hidden, checked, selected, or several others to any string value to toggle it.

How do I find the index of a character in a string in Ruby?

You can use this

"abcdefg".index('c')   #=> 2

Android RelativeLayout programmatically Set "centerInParent"

I have done for

1. centerInParent

2. centerHorizontal

3. centerVertical

with true and false.

private void addOrRemoveProperty(View view, int property, boolean flag){
    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
    if(flag){
        layoutParams.addRule(property);
    }else {
        layoutParams.removeRule(property);
    }
    view.setLayoutParams(layoutParams);
}

How to call method:

centerInParent - true

addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, true);

centerInParent - false

addOrRemoveProperty(mView, RelativeLayout.CENTER_IN_PARENT, false);

centerHorizontal - true

addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, true);

centerHorizontal - false

addOrRemoveProperty(mView, RelativeLayout.CENTER_HORIZONTAL, false);

centerVertical - true

addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, true);

centerVertical - false

addOrRemoveProperty(mView, RelativeLayout.CENTER_VERTICAL, false);

Hope this would help you.

Fill drop down list on selection of another drop down list

enter image description here

enter image description here

enter image description here

Model:

namespace MvcApplicationrazor.Models
{
    public class CountryModel
    {
        public List<State> StateModel { get; set; }
        public SelectList FilteredCity { get; set; }
    }
    public class State
    {
        public int Id { get; set; }
        public string StateName { get; set; }
    }
    public class City
    {
        public int Id { get; set; }
        public int StateId { get; set; }
        public string CityName { get; set; }
    }
}   

Controller:

public ActionResult Index()
        {
            CountryModel objcountrymodel = new CountryModel();
            objcountrymodel.StateModel = new List<State>();
            objcountrymodel.StateModel = GetAllState();
            return View(objcountrymodel);
        }


        //Action result for ajax call
        [HttpPost]
        public ActionResult GetCityByStateId(int stateid)
        {
            List<City> objcity = new List<City>();
            objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
            SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
            return Json(obgcity);
        }
        // Collection for state
        public List<State> GetAllState()
        {
            List<State> objstate = new List<State>();
            objstate.Add(new State { Id = 0, StateName = "Select State" });
            objstate.Add(new State { Id = 1, StateName = "State 1" });
            objstate.Add(new State { Id = 2, StateName = "State 2" });
            objstate.Add(new State { Id = 3, StateName = "State 3" });
            objstate.Add(new State { Id = 4, StateName = "State 4" });
            return objstate;
        }
        //collection for city
        public List<City> GetAllCity()
        {
            List<City> objcity = new List<City>();
            objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
            objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
            objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
            objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
            objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
            objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
            return objcity;
        }

View:

@model MvcApplicationrazor.Models.CountryModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
    function GetCity(_stateId) {
        var procemessage = "<option value='0'> Please wait...</option>";
        $("#ddlcity").html(procemessage).show();
        var url = "/Test/GetCityByStateId/";

        $.ajax({
            url: url,
            data: { stateid: _stateId },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value='0'>Select City</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $("#ddlcity").html(markup).show();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });

    }
</script>
<h4>
 MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
    @Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
    <br />
    <br />
    <select id="ddlcity" name="ddlcity" style="width: 200px">

    </select>

    <br /><br />
  }

why should I make a copy of a data frame in pandas

The primary purpose is to avoid chained indexing and eliminate the SettingWithCopyWarning.

Here chained indexing is something like dfc['A'][0] = 111

The document said chained indexing should be avoided in Returning a view versus a copy. Here is a slightly modified example from that document:

In [1]: import pandas as pd

In [2]: dfc = pd.DataFrame({'A':['aaa','bbb','ccc'],'B':[1,2,3]})

In [3]: dfc
Out[3]:
    A   B
0   aaa 1
1   bbb 2
2   ccc 3

In [4]: aColumn = dfc['A']

In [5]: aColumn[0] = 111
SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

In [6]: dfc
Out[6]:
    A   B
0   111 1
1   bbb 2
2   ccc 3

Here the aColumn is a view and not a copy from the original DataFrame, so modifying aColumn will cause the original dfc be modified too. Next, if we index the row first:

In [7]: zero_row = dfc.loc[0]

In [8]: zero_row['A'] = 222
SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

In [9]: dfc
Out[9]:
    A   B
0   111 1
1   bbb 2
2   ccc 3

This time zero_row is a copy, so the original dfc is not modified.

From these two examples above, we see it's ambiguous whether or not you want to change the original DataFrame. This is especially dangerous if you write something like the following:

In [10]: dfc.loc[0]['A'] = 333
SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

In [11]: dfc
Out[11]:
    A   B
0   111 1
1   bbb 2
2   ccc 3

This time it didn't work at all. Here we wanted to change dfc, but we actually modified an intermediate value dfc.loc[0] that is a copy and is discarded immediately. It’s very hard to predict whether the intermediate value like dfc.loc[0] or dfc['A'] is a view or a copy, so it's not guaranteed whether or not original DataFrame will be updated. That's why chained indexing should be avoided, and pandas generates the SettingWithCopyWarning for this kind of chained indexing update.

Now is the use of .copy(). To eliminate the warning, make a copy to express your intention explicitly:

In [12]: zero_row_copy = dfc.loc[0].copy()

In [13]: zero_row_copy['A'] = 444 # This time no warning

Since you are modifying a copy, you know the original dfc will never change and you are not expecting it to change. Your expectation matches the behavior, then the SettingWithCopyWarning disappears.

Note, If you do want to modify the original DataFrame, the document suggests you use loc:

In [14]: dfc.loc[0,'A'] = 555

In [15]: dfc
Out[15]:
    A   B
0   555 1
1   bbb 2
2   ccc 3

The #include<iostream> exists, but I get an error: identifier "cout" is undefined. Why?

cout is in std namespace, you shall use std::cout in your code. And you shall not add using namespace std; in your header file, it's bad to mix your code with std namespace, especially don't add it in header file.

Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property

  1. Download gecko driver from the seleniumhq website (Now it is on GitHub and you can download it from Here) .
    1. You will have a zip (or tar.gz) so extract it.
    2. After extraction you will have geckodriver.exe file (appropriate executable in linux).
    3. Create Folder in C: named SeleniumGecko (Or appropriate)
    4. Copy and Paste geckodriver.exe to SeleniumGecko
    5. Set the path for gecko driver as below

.

System.setProperty("webdriver.gecko.driver","C:\\geckodriver-v0.10.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();

How to stop a vb script running in windows

in your code, just after 'do while' statement, add this line..

`Wscript.sleep 10000`

This will let your script sleep for 10 secs and let your system take rest. Else your processor will be running this script million times a second and this will definitely load your processor.

To kill it, just goto taskmanager and kill wscript.exe or if it is not found, you will find cscript.exe, kill it pressing delete button. These would be present in process tab of your taskmanager.

Once you add that line in code, I dont think you need to kill this process. It will not load your CPU.

Have a great day.

How to remove undefined and null values from an object using lodash?

The correct answer is:

_.omitBy({ a: null, b: 1, c: undefined, d: false }, _.isNil)

That results in:

{b: 1, d: false}

The alternative given here by other people:

_.pickBy({ a: null, b: 1, c: undefined, d: false }, _.identity);

Will remove also false values which is not desired here.

Running conda with proxy

Or you can use the command line below from version 4.4.x.

conda config --set proxy_servers.http http://id:pw@address:port
conda config --set proxy_servers.https https://id:pw@address:port

How can I open a website in my web browser using Python?

As the instructions state, using the open() function does work, and opens the default web browser - usually I would say: "why wouldn't I want to use Firefox?!" (my default and favorite browser)

import webbrowser as wb
wb.open_new_tab('http://www.google.com')

The above should work for the computer's default browser. However, what if you want to to open in Google Chrome?

The proper way to do this is:

import webbrowser as wb
wb.get('chrome %s').open_new_tab('http://www.google.com')

To be honest, I'm not really sure that I know the difference between 'chrome' and 'google-chrome', but apparently there is some since they've made the two different type names in the webbrowser documentation.

However, doing this didn't work right off the bat for me. Every time, I would get the error:

Traceback (most recent call last):
File "C:\Python34\programs\a_temp_testing.py", line 3, in <module>
wb.get('google-chrome')
File "C:\Python34\lib\webbrowser.py", line 51, in get
raise Error("could not locate runnable browser")
webbrowser.Error: could not locate runnable browser

To solve this, I had to add the folder for chrome.exe to System PATH. My chrome.exe executable file is found at:

C:\Program Files (x86)\Google\Chrome\Application

You should check whether it is here or not for yourself.

To add this to your Environment Variables System PATH, right click on your Windows icon and go to System. System Control Panel applet (Start - Settings - Control Panel - System). Change advanced settings, or the advanced tab, and select the button there called Environment Varaibles.

Once you click on Environment Variables here, another window will pop up. Scroll through the items, select PATH, and click edit.

Once you're in here, click New to add the folder path to your chrome.exe file. Like I said above, mine was found at:

C:\Program Files (x86)\Google\Chrome\Application

Click save and exit out of there. Then make sure you reboot your computer.

Hope this helps!

How to change environment's font size?

  1. Open VS Code
  2. Type command CTRL + SHFT + P
  3. Type Settings
  4. Settings file will open.
  5. Now under User > Text Editor > Font, find Font Size
  6. Enter your desired font size

That's it.

Python send POST with header

To make POST request instead of GET request using urllib2, you need to specify empty data, for example:

import urllib2
req = urllib2.Request("http://am.domain.com:8080/openam/json/realms/root/authenticate?authIndexType=Module&authIndexValue=LDAP")
req.add_header('X-OpenAM-Username', 'demo')
req.add_data('')
r = urllib2.urlopen(req)

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

How to get first two characters of a string in oracle query?

Easy:

SELECT SUBSTR(OrderNo, 1, 2) FROM shipment;

Adding calculated column(s) to a dataframe in pandas

For the second part of your question, you can also use shift, for example:

df['t-1'] = df['t'].shift(1)

t-1 would then contain the values from t one row above.

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html

MySQL, Concatenate two columns

You can use the CONCAT function like this:

SELECT CONCAT(`SUBJECT`, ' ', `YEAR`) FROM `table`

Update:

To get that result you can try this:

SET @rn := 0;

SELECT CONCAT(`SUBJECT`,'-',`YEAR`,'-',LPAD(@rn := @rn+1,3,'0'))
FROM `table`

Wampserver icon not going green fully, mysql services not starting up?

simplest this to do is find what other service is using the same service id as mysql does in windows.

When i looked through the list of services running on my pc (even after a restart...i still had the problem)

I quickly realised i had webmatrix installed on my computer previous to wamp server...webmatrix installed its own copy of mysql and set it to automatically startup another instance each time i logged in.

As soon as the other instance of mysql associated with web matrix was stopped (and changed from automatic startup to manual) my problem with WAMP mysql was solved.

C++ - Decimal to binary converting

HOPE YOU LIKE THIS SIMPLE CODE OF CONVERSION FROM DECIMAL TO BINARY


  #include<iostream>
    using namespace std;
    int main()
    {
        int input,rem,res,count=0,i=0;
        cout<<"Input number: ";
        cin>>input;`enter code here`
        int num=input;
        while(input > 0)
        {
            input=input/2;  
            count++;
        }

        int arr[count];

        while(num > 0)
        {
            arr[i]=num%2;
            num=num/2;  
            i++;
        }
        for(int i=count-1 ; i>=0 ; i--)
        {
            cout<<" " << arr[i]<<" ";
        }



        return 0;
    }

How to log as much information as possible for a Java Exception?

You can also use Apache's ExceptionUtils.

Example:

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;


public class Test {

    static Logger logger = Logger.getLogger(Test.class);

    public static void main(String[] args) {

        try{
            String[] avengers = null;
            System.out.println("Size: "+avengers.length);
        } catch (NullPointerException e){
            logger.info(ExceptionUtils.getFullStackTrace(e));
        }
    }

}

Console output:

java.lang.NullPointerException
    at com.aimlessfist.avengers.ironman.Test.main(Test.java:11)

Can I have multiple Xcode versions installed?

Whatever advice path you go down, make a copy of your project folder, and rename the external most one to reflect what XCode version it is being opened in. Your choice on whether you want it to update syntax or not, but the main reason for all this bovver is your storyboard will be altered just by looking. It may be resolved by the time a new reader coming across this in the future, or

What does "dereferencing" a pointer mean?

Reviewing the basic terminology

It's usually good enough - unless you're programming assembly - to envisage a pointer containing a numeric memory address, with 1 referring to the second byte in the process's memory, 2 the third, 3 the fourth and so on....

  • What happened to 0 and the first byte? Well, we'll get to that later - see null pointers below.
  • For a more accurate definition of what pointers store, and how memory and addresses relate, see "More about memory addresses, and why you probably don't need to know" at the end of this answer.

When you want to access the data/value in the memory that the pointer points to - the contents of the address with that numerical index - then you dereference the pointer.

Different computer languages have different notations to tell the compiler or interpreter that you're now interested in the pointed-to object's (current) value - I focus below on C and C++.

A pointer scenario

Consider in C, given a pointer such as p below...

const char* p = "abc";

...four bytes with the numerical values used to encode the letters 'a', 'b', 'c', and a 0 byte to denote the end of the textual data, are stored somewhere in memory and the numerical address of that data is stored in p. This way C encodes text in memory is known as ASCIIZ.

For example, if the string literal happened to be at address 0x1000 and p a 32-bit pointer at 0x2000, the memory content would be:

Memory Address (hex)    Variable name    Contents
1000                                     'a' == 97 (ASCII)
1001                                     'b' == 98
1002                                     'c' == 99
1003                                     0
...
2000-2003               p                1000 hex

Note that there is no variable name/identifier for address 0x1000, but we can indirectly refer to the string literal using a pointer storing its address: p.

Dereferencing the pointer

To refer to the characters p points to, we dereference p using one of these notations (again, for C):

assert(*p == 'a');  // The first character at address p will be 'a'
assert(p[1] == 'b'); // p[1] actually dereferences a pointer created by adding
                     // p and 1 times the size of the things to which p points:
                     // In this case they're char which are 1 byte in C...
assert(*(p + 1) == 'b');  // Another notation for p[1]

You can also move pointers through the pointed-to data, dereferencing them as you go:

++p;  // Increment p so it's now 0x1001
assert(*p == 'b');  // p == 0x1001 which is where the 'b' is...

If you have some data that can be written to, then you can do things like this:

int x = 2;
int* p_x = &x;  // Put the address of the x variable into the pointer p_x
*p_x = 4;       // Change the memory at the address in p_x to be 4
assert(x == 4); // Check x is now 4

Above, you must have known at compile time that you would need a variable called x, and the code asks the compiler to arrange where it should be stored, ensuring the address will be available via &x.

Dereferencing and accessing a structure data member

In C, if you have a variable that is a pointer to a structure with data members, you can access those members using the -> dereferencing operator:

typedef struct X { int i_; double d_; } X;
X x;
X* p = &x;
p->d_ = 3.14159;  // Dereference and access data member x.d_
(*p).d_ *= -1;    // Another equivalent notation for accessing x.d_

Multi-byte data types

To use a pointer, a computer program also needs some insight into the type of data that is being pointed at - if that data type needs more than one byte to represent, then the pointer normally points to the lowest-numbered byte in the data.

So, looking at a slightly more complex example:

double sizes[] = { 10.3, 13.4, 11.2, 19.4 };
double* p = sizes;
assert(p[0] == 10.3);  // Knows to look at all the bytes in the first double value
assert(p[1] == 13.4);  // Actually looks at bytes from address p + 1 * sizeof(double)
                       // (sizeof(double) is almost always eight bytes)
++p;                   // Advance p by sizeof(double)
assert(*p == 13.4);    // The double at memory beginning at address p has value 13.4
*(p + 2) = 29.8;       // Change sizes[3] from 19.4 to 29.8
                       // Note earlier ++p and + 2 here => sizes[3]

Pointers to dynamically allocated memory

Sometimes you don't know how much memory you'll need until your program is running and sees what data is thrown at it... then you can dynamically allocate memory using malloc. It is common practice to store the address in a pointer...

int* p = (int*)malloc(sizeof(int)); // Get some memory somewhere...
*p = 10;            // Dereference the pointer to the memory, then write a value in
fn(*p);             // Call a function, passing it the value at address p
(*p) += 3;          // Change the value, adding 3 to it
free(p);            // Release the memory back to the heap allocation library

In C++, memory allocation is normally done with the new operator, and deallocation with delete:

int* p = new int(10); // Memory for one int with initial value 10
delete p;

p = new int[10];      // Memory for ten ints with unspecified initial value
delete[] p;

p = new int[10]();    // Memory for ten ints that are value initialised (to 0)
delete[] p;

See also C++ smart pointers below.

Losing and leaking addresses

Often a pointer may be the only indication of where some data or buffer exists in memory. If ongoing use of that data/buffer is needed, or the ability to call free() or delete to avoid leaking the memory, then the programmer must operate on a copy of the pointer...

const char* p = asprintf("name: %s", name);  // Common but non-Standard printf-on-heap

// Replace non-printable characters with underscores....
for (const char* q = p; *q; ++q)
    if (!isprint(*q))
        *q = '_';

printf("%s\n", p); // Only q was modified
free(p);

...or carefully orchestrate reversal of any changes...

const size_t n = ...;
p += n;
...
p -= n;  // Restore earlier value...
free(p);

C++ smart pointers

In C++, it's best practice to use smart pointer objects to store and manage the pointers, automatically deallocating them when the smart pointers' destructors run. Since C++11 the Standard Library provides two, unique_ptr for when there's a single owner for an allocated object...

{
    std::unique_ptr<T> p{new T(42, "meaning")};
    call_a_function(p);
    // The function above might throw, so delete here is unreliable, but...
} // p's destructor's guaranteed to run "here", calling delete

...and shared_ptr for share ownership (using reference counting)...

{
    auto p = std::make_shared<T>(3.14, "pi");
    number_storage1.may_add(p); // Might copy p into its container
    number_storage2.may_add(p); // Might copy p into its container    } // p's destructor will only delete the T if neither may_add copied it

Null pointers

In C, NULL and 0 - and additionally in C++ nullptr - can be used to indicate that a pointer doesn't currently hold the memory address of a variable, and shouldn't be dereferenced or used in pointer arithmetic. For example:

const char* p_filename = NULL; // Or "= 0", or "= nullptr" in C++
int c;
while ((c = getopt(argc, argv, "f:")) != -1)
    switch (c) {
      case f: p_filename = optarg; break;
    }
if (p_filename)  // Only NULL converts to false
    ...   // Only get here if -f flag specified

In C and C++, just as inbuilt numeric types don't necessarily default to 0, nor bools to false, pointers are not always set to NULL. All these are set to 0/false/NULL when they're static variables or (C++ only) direct or indirect member variables of static objects or their bases, or undergo zero initialisation (e.g. new T(); and new T(x, y, z); perform zero-initialisation on T's members including pointers, whereas new T; does not).

Further, when you assign 0, NULL and nullptr to a pointer the bits in the pointer are not necessarily all reset: the pointer may not contain "0" at the hardware level, or refer to address 0 in your virtual address space. The compiler is allowed to store something else there if it has reason to, but whatever it does - if you come along and compare the pointer to 0, NULL, nullptr or another pointer that was assigned any of those, the comparison must work as expected. So, below the source code at the compiler level, "NULL" is potentially a bit "magical" in the C and C++ languages...

More about memory addresses, and why you probably don't need to know

More strictly, initialised pointers store a bit-pattern identifying either NULL or a (often virtual) memory address.

The simple case is where this is a numeric offset into the process's entire virtual address space; in more complex cases the pointer may be relative to some specific memory area, which the CPU may select based on CPU "segment" registers or some manner of segment id encoded in the bit-pattern, and/or looking in different places depending on the machine code instructions using the address.

For example, an int* properly initialised to point to an int variable might - after casting to a float* - access memory in "GPU" memory quite distinct from the memory where the int variable is, then once cast to and used as a function pointer it might point into further distinct memory holding machine opcodes for the program (with the numeric value of the int* effectively a random, invalid pointer within these other memory regions).

3GL programming languages like C and C++ tend to hide this complexity, such that:

  • If the compiler gives you a pointer to a variable or function, you can dereference it freely (as long as the variable's not destructed/deallocated meanwhile) and it's the compiler's problem whether e.g. a particular CPU segment register needs to be restored beforehand, or a distinct machine code instruction used

  • If you get a pointer to an element in an array, you can use pointer arithmetic to move anywhere else in the array, or even to form an address one-past-the-end of the array that's legal to compare with other pointers to elements in the array (or that have similarly been moved by pointer arithmetic to the same one-past-the-end value); again in C and C++, it's up to the compiler to ensure this "just works"

  • Specific OS functions, e.g. shared memory mapping, may give you pointers, and they'll "just work" within the range of addresses that makes sense for them

  • Attempts to move legal pointers beyond these boundaries, or to cast arbitrary numbers to pointers, or use pointers cast to unrelated types, typically have undefined behaviour, so should be avoided in higher level libraries and applications, but code for OSes, device drivers, etc. may need to rely on behaviour left undefined by the C or C++ Standard, that is nevertheless well defined by their specific implementation or hardware.

PHP Parse error: syntax error, unexpected T_PUBLIC

You can remove public keyword from your functions, because, you have to define a class in order to declare public, private or protected function

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

To clarify for anyone who is looking for what is the difference between the 3 on a simpler level. You can expose your service with minimal ClusterIp (within k8s cluster) or larger exposure with NodePort (within cluster external to k8s cluster) or LoadBalancer (external world or whatever you defined in your LB).

ClusterIp exposure < NodePort exposure < LoadBalancer exposure

  • ClusterIp
    Expose service through k8s cluster with ip/name:port
  • NodePort
    Expose service through Internal network VM's also external to k8s ip/name:port
  • LoadBalancer
    Expose service through External world or whatever you defined in your LB.

log4j: Log output of a specific class to a specific appender

An example:

log4j.rootLogger=ERROR, logfile

log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.datePattern='-'dd'.log'
log4j.appender.logfile.File=log/radius-prod.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n

log4j.logger.foo.bar.Baz=DEBUG, myappender
log4j.additivity.foo.bar.Baz=false

log4j.appender.myappender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myappender.datePattern='-'dd'.log'
log4j.appender.myappender.File=log/access-ext-dmz-prod.log
log4j.appender.myappender.layout=org.apache.log4j.PatternLayout
log4j.appender.myappender.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n

node.js + mysql connection pooling

I am using this base class connection with mysql:

"base.js"

var mysql   = require("mysql");

var pool = mysql.createPool({
    connectionLimit : 10,
    host: Config.appSettings().database.host,
    user: Config.appSettings().database.username,
    password: Config.appSettings().database.password,
    database: Config.appSettings().database.database
});


var DB = (function () {

    function _query(query, params, callback) {
        pool.getConnection(function (err, connection) {
            if (err) {
                connection.release();
                callback(null, err);
                throw err;
            }

            connection.query(query, params, function (err, rows) {
                connection.release();
                if (!err) {
                    callback(rows);
                }
                else {
                    callback(null, err);
                }

            });

            connection.on('error', function (err) {
                connection.release();
                callback(null, err);
                throw err;
            });
        });
    };

    return {
        query: _query
    };
})();

module.exports = DB;

Just use it like that:

var DB = require('../dal/base.js');

DB.query("select * from tasks", null, function (data, error) {
   callback(data, error);
});

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

Bootstrap 3 Glyphicons CDN

If you only want to have glyphicons icons without any additional css you can create a css file and put the code below and include it into main css file.

I have to create this extra file as link below was messing with my site styles too.

//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css

Instead to using it directly I created a css file bootstrap-glyphicons.css

_x000D_
_x000D_
@font-face{font-family:'Glyphicons Halflings';src:url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot');src:url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.woff') format('woff'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.ttf') format('truetype'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:normal;line-height:1;-webkit-font-smoothing:antialiased;}_x000D_
.glyphicon-asterisk:before{content:"\2a";}_x000D_
.glyphicon-plus:before{content:"\2b";}_x000D_
.glyphicon-euro:before{content:"\20ac";}_x000D_
.glyphicon-minus:before{content:"\2212";}_x000D_
.glyphicon-cloud:before{content:"\2601";}_x000D_
.glyphicon-envelope:before{content:"\2709";}_x000D_
.glyphicon-pencil:before{content:"\270f";}_x000D_
.glyphicon-glass:before{content:"\e001";}_x000D_
.glyphicon-music:before{content:"\e002";}_x000D_
.glyphicon-search:before{content:"\e003";}_x000D_
.glyphicon-heart:before{content:"\e005";}_x000D_
.glyphicon-star:before{content:"\e006";}_x000D_
.glyphicon-star-empty:before{content:"\e007";}_x000D_
.glyphicon-user:before{content:"\e008";}_x000D_
.glyphicon-film:before{content:"\e009";}_x000D_
.glyphicon-th-large:before{content:"\e010";}_x000D_
.glyphicon-th:before{content:"\e011";}_x000D_
.glyphicon-th-list:before{content:"\e012";}_x000D_
.glyphicon-ok:before{content:"\e013";}_x000D_
.glyphicon-remove:before{content:"\e014";}_x000D_
.glyphicon-zoom-in:before{content:"\e015";}_x000D_
.glyphicon-zoom-out:before{content:"\e016";}_x000D_
.glyphicon-off:before{content:"\e017";}_x000D_
.glyphicon-signal:before{content:"\e018";}_x000D_
.glyphicon-cog:before{content:"\e019";}_x000D_
.glyphicon-trash:before{content:"\e020";}_x000D_
.glyphicon-home:before{content:"\e021";}_x000D_
.glyphicon-file:before{content:"\e022";}_x000D_
.glyphicon-time:before{content:"\e023";}_x000D_
.glyphicon-road:before{content:"\e024";}_x000D_
.glyphicon-download-alt:before{content:"\e025";}_x000D_
.glyphicon-download:before{content:"\e026";}_x000D_
.glyphicon-upload:before{content:"\e027";}_x000D_
.glyphicon-inbox:before{content:"\e028";}_x000D_
.glyphicon-play-circle:before{content:"\e029";}_x000D_
.glyphicon-repeat:before{content:"\e030";}_x000D_
.glyphicon-refresh:before{content:"\e031";}_x000D_
.glyphicon-list-alt:before{content:"\e032";}_x000D_
.glyphicon-flag:before{content:"\e034";}_x000D_
.glyphicon-headphones:before{content:"\e035";}_x000D_
.glyphicon-volume-off:before{content:"\e036";}_x000D_
.glyphicon-volume-down:before{content:"\e037";}_x000D_
.glyphicon-volume-up:before{content:"\e038";}_x000D_
.glyphicon-qrcode:before{content:"\e039";}_x000D_
.glyphicon-barcode:before{content:"\e040";}_x000D_
.glyphicon-tag:before{content:"\e041";}_x000D_
.glyphicon-tags:before{content:"\e042";}_x000D_
.glyphicon-book:before{content:"\e043";}_x000D_
.glyphicon-print:before{content:"\e045";}_x000D_
.glyphicon-font:before{content:"\e047";}_x000D_
.glyphicon-bold:before{content:"\e048";}_x000D_
.glyphicon-italic:before{content:"\e049";}_x000D_
.glyphicon-text-height:before{content:"\e050";}_x000D_
.glyphicon-text-width:before{content:"\e051";}_x000D_
.glyphicon-align-left:before{content:"\e052";}_x000D_
.glyphicon-align-center:before{content:"\e053";}_x000D_
.glyphicon-align-right:before{content:"\e054";}_x000D_
.glyphicon-align-justify:before{content:"\e055";}_x000D_
.glyphicon-list:before{content:"\e056";}_x000D_
.glyphicon-indent-left:before{content:"\e057";}_x000D_
.glyphicon-indent-right:before{content:"\e058";}_x000D_
.glyphicon-facetime-video:before{content:"\e059";}_x000D_
.glyphicon-picture:before{content:"\e060";}_x000D_
.glyphicon-map-marker:before{content:"\e062";}_x000D_
.glyphicon-adjust:before{content:"\e063";}_x000D_
.glyphicon-tint:before{content:"\e064";}_x000D_
.glyphicon-edit:before{content:"\e065";}_x000D_
.glyphicon-share:before{content:"\e066";}_x000D_
.glyphicon-check:before{content:"\e067";}_x000D_
.glyphicon-move:before{content:"\e068";}_x000D_
.glyphicon-step-backward:before{content:"\e069";}_x000D_
.glyphicon-fast-backward:before{content:"\e070";}_x000D_
.glyphicon-backward:before{content:"\e071";}_x000D_
.glyphicon-play:before{content:"\e072";}_x000D_
.glyphicon-pause:before{content:"\e073";}_x000D_
.glyphicon-stop:before{content:"\e074";}_x000D_
.glyphicon-forward:before{content:"\e075";}_x000D_
.glyphicon-fast-forward:before{content:"\e076";}_x000D_
.glyphicon-step-forward:before{content:"\e077";}_x000D_
.glyphicon-eject:before{content:"\e078";}_x000D_
.glyphicon-chevron-left:before{content:"\e079";}_x000D_
.glyphicon-chevron-right:before{content:"\e080";}_x000D_
.glyphicon-plus-sign:before{content:"\e081";}_x000D_
.glyphicon-minus-sign:before{content:"\e082";}_x000D_
.glyphicon-remove-sign:before{content:"\e083";}_x000D_
.glyphicon-ok-sign:before{content:"\e084";}_x000D_
.glyphicon-question-sign:before{content:"\e085";}_x000D_
.glyphicon-info-sign:before{content:"\e086";}_x000D_
.glyphicon-screenshot:before{content:"\e087";}_x000D_
.glyphicon-remove-circle:before{content:"\e088";}_x000D_
.glyphicon-ok-circle:before{content:"\e089";}_x000D_
.glyphicon-ban-circle:before{content:"\e090";}_x000D_
.glyphicon-arrow-left:before{content:"\e091";}_x000D_
.glyphicon-arrow-right:before{content:"\e092";}_x000D_
.glyphicon-arrow-up:before{content:"\e093";}_x000D_
.glyphicon-arrow-down:before{content:"\e094";}_x000D_
.glyphicon-share-alt:before{content:"\e095";}_x000D_
.glyphicon-resize-full:before{content:"\e096";}_x000D_
.glyphicon-resize-small:before{content:"\e097";}_x000D_
.glyphicon-exclamation-sign:before{content:"\e101";}_x000D_
.glyphicon-gift:before{content:"\e102";}_x000D_
.glyphicon-leaf:before{content:"\e103";}_x000D_
.glyphicon-eye-open:before{content:"\e105";}_x000D_
.glyphicon-eye-close:before{content:"\e106";}_x000D_
.glyphicon-warning-sign:before{content:"\e107";}_x000D_
.glyphicon-plane:before{content:"\e108";}_x000D_
.glyphicon-random:before{content:"\e110";}_x000D_
.glyphicon-comment:before{content:"\e111";}_x000D_
.glyphicon-magnet:before{content:"\e112";}_x000D_
.glyphicon-chevron-up:before{content:"\e113";}_x000D_
.glyphicon-chevron-down:before{content:"\e114";}_x000D_
.glyphicon-retweet:before{content:"\e115";}_x000D_
.glyphicon-shopping-cart:before{content:"\e116";}_x000D_
.glyphicon-folder-close:before{content:"\e117";}_x000D_
.glyphicon-folder-open:before{content:"\e118";}_x000D_
.glyphicon-resize-vertical:before{content:"\e119";}_x000D_
.glyphicon-resize-horizontal:before{content:"\e120";}_x000D_
.glyphicon-hdd:before{content:"\e121";}_x000D_
.glyphicon-bullhorn:before{content:"\e122";}_x000D_
.glyphicon-certificate:before{content:"\e124";}_x000D_
.glyphicon-thumbs-up:before{content:"\e125";}_x000D_
.glyphicon-thumbs-down:before{content:"\e126";}_x000D_
.glyphicon-hand-right:before{content:"\e127";}_x000D_
.glyphicon-hand-left:before{content:"\e128";}_x000D_
.glyphicon-hand-up:before{content:"\e129";}_x000D_
.glyphicon-hand-down:before{content:"\e130";}_x000D_
.glyphicon-circle-arrow-right:before{content:"\e131";}_x000D_
.glyphicon-circle-arrow-left:before{content:"\e132";}_x000D_
.glyphicon-circle-arrow-up:before{content:"\e133";}_x000D_
.glyphicon-circle-arrow-down:before{content:"\e134";}_x000D_
.glyphicon-globe:before{content:"\e135";}_x000D_
.glyphicon-tasks:before{content:"\e137";}_x000D_
.glyphicon-filter:before{content:"\e138";}_x000D_
.glyphicon-fullscreen:before{content:"\e140";}_x000D_
.glyphicon-dashboard:before{content:"\e141";}_x000D_
.glyphicon-heart-empty:before{content:"\e143";}_x000D_
.glyphicon-link:before{content:"\e144";}_x000D_
.glyphicon-phone:before{content:"\e145";}_x000D_
.glyphicon-usd:before{content:"\e148";}_x000D_
.glyphicon-gbp:before{content:"\e149";}_x000D_
.glyphicon-sort:before{content:"\e150";}_x000D_
.glyphicon-sort-by-alphabet:before{content:"\e151";}_x000D_
.glyphicon-sort-by-alphabet-alt:before{content:"\e152";}_x000D_
.glyphicon-sort-by-order:before{content:"\e153";}_x000D_
.glyphicon-sort-by-order-alt:before{content:"\e154";}_x000D_
.glyphicon-sort-by-attributes:before{content:"\e155";}_x000D_
.glyphicon-sort-by-attributes-alt:before{content:"\e156";}_x000D_
.glyphicon-unchecked:before{content:"\e157";}_x000D_
.glyphicon-expand:before{content:"\e158";}_x000D_
.glyphicon-collapse-down:before{content:"\e159";}_x000D_
.glyphicon-collapse-up:before{content:"\e160";}_x000D_
.glyphicon-log-in:before{content:"\e161";}_x000D_
.glyphicon-flash:before{content:"\e162";}_x000D_
.glyphicon-log-out:before{content:"\e163";}_x000D_
.glyphicon-new-window:before{content:"\e164";}_x000D_
.glyphicon-record:before{content:"\e165";}_x000D_
.glyphicon-save:before{content:"\e166";}_x000D_
.glyphicon-open:before{content:"\e167";}_x000D_
.glyphicon-saved:before{content:"\e168";}_x000D_
.glyphicon-import:before{content:"\e169";}_x000D_
.glyphicon-export:before{content:"\e170";}_x000D_
.glyphicon-send:before{content:"\e171";}_x000D_
.glyphicon-floppy-disk:before{content:"\e172";}_x000D_
.glyphicon-floppy-saved:before{content:"\e173";}_x000D_
.glyphicon-floppy-remove:before{content:"\e174";}_x000D_
.glyphicon-floppy-save:before{content:"\e175";}_x000D_
.glyphicon-floppy-open:before{content:"\e176";}_x000D_
.glyphicon-credit-card:before{content:"\e177";}_x000D_
.glyphicon-transfer:before{content:"\e178";}_x000D_
.glyphicon-cutlery:before{content:"\e179";}_x000D_
.glyphicon-header:before{content:"\e180";}_x000D_
.glyphicon-compressed:before{content:"\e181";}_x000D_
.glyphicon-earphone:before{content:"\e182";}_x000D_
.glyphicon-phone-alt:before{content:"\e183";}_x000D_
.glyphicon-tower:before{content:"\e184";}_x000D_
.glyphicon-stats:before{content:"\e185";}_x000D_
.glyphicon-sd-video:before{content:"\e186";}_x000D_
.glyphicon-hd-video:before{content:"\e187";}_x000D_
.glyphicon-subtitles:before{content:"\e188";}_x000D_
.glyphicon-sound-stereo:before{content:"\e189";}_x000D_
.glyphicon-sound-dolby:before{content:"\e190";}_x000D_
.glyphicon-sound-5-1:before{content:"\e191";}_x000D_
.glyphicon-sound-6-1:before{content:"\e192";}_x000D_
.glyphicon-sound-7-1:before{content:"\e193";}_x000D_
.glyphicon-copyright-mark:before{content:"\e194";}_x000D_
.glyphicon-registration-mark:before{content:"\e195";}_x000D_
.glyphicon-cloud-download:before{content:"\e197";}_x000D_
.glyphicon-cloud-upload:before{content:"\e198";}_x000D_
.glyphicon-tree-conifer:before{content:"\e199";}_x000D_
.glyphicon-tree-deciduous:before{content:"\e200";}_x000D_
.glyphicon-briefcase:before{content:"\1f4bc";}_x000D_
.glyphicon-calendar:before{content:"\1f4c5";}_x000D_
.glyphicon-pushpin:before{content:"\1f4cc";}_x000D_
.glyphicon-paperclip:before{content:"\1f4ce";}_x000D_
.glyphicon-camera:before{content:"\1f4f7";}_x000D_
.glyphicon-lock:before{content:"\1f512";}_x000D_
.glyphicon-bell:before{content:"\1f514";}_x000D_
.glyphicon-bookmark:before{content:"\1f516";}_x000D_
.glyphicon-fire:before{content:"\1f525";}_x000D_
.glyphicon-wrench:before{content:"\1f527";}
_x000D_
_x000D_
_x000D_

And imported the created css file into my main css file which enable me to just import the glyphicons only. Hope this help

@import url("bootstrap-glyphicons.css");

Convert Json String to C# Object List

You can use json2csharp.com to Convert your json to object model

  • Go to json2csharp.com
  • Past your JSON in the Box.
  • Clik on Generate.
  • You will get C# Code for your object model
  • Deserialize by var model = JsonConvert.DeserializeObject<RootObject>(json); using NewtonJson

Here, It will generate something like this:

public class MatrixModel
{
    public class Option
    {
        public string text { get; set; }
        public string selectedMarks { get; set; }
    }

    public class Model
    {
        public List<Option> options { get; set; }
        public int maxOptions { get; set; }
        public int minOptions { get; set; }
        public bool isAnswerRequired { get; set; }
        public string selectedOption { get; set; }
        public string answerText { get; set; }
        public bool isRangeType { get; set; }
        public string from { get; set; }
        public string to { get; set; }
        public string mins { get; set; }
        public string secs { get; set; }
    }

    public class Question
    {
        public int QuestionId { get; set; }
        public string QuestionText { get; set; }
        public int TypeId { get; set; }
        public string TypeName { get; set; }
        public Model Model { get; set; }
    }

    public class RootObject
    {
        public Question Question { get; set; }
        public string CheckType { get; set; }
        public string S1 { get; set; }
        public string S2 { get; set; }
        public string S3 { get; set; }
        public string S4 { get; set; }
        public string S5 { get; set; }
        public string S6 { get; set; }
        public string S7 { get; set; }
        public string S8 { get; set; }
        public string S9 { get; set; }
        public string S10 { get; set; }
        public string ScoreIfNoMatch { get; set; }
    }
}

Then you can deserialize as:

var model = JsonConvert.DeserializeObject<List<MatrixModel.RootObject>>(json);

How to find whether a ResultSet is empty or not in Java?

Calculates the size of the java.sql.ResultSet:

int size = 0;
if (rs != null) {
    rs.beforeFirst();
    rs.last();
    size = rs.getRow();
}

(Source)

Getting random numbers in Java

The first solution is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random():

double random = Math.random() * 49 + 1;

or

int random = (int)(Math.random() * 50 + 1);

Convert String (UTF-16) to UTF-8 in C#

    private static string Utf16ToUtf8(string utf16String)
    {
        /**************************************************************
         * Every .NET string will store text with the UTF16 encoding, *
         * known as Encoding.Unicode. Other encodings may exist as    *
         * Byte-Array or incorrectly stored with the UTF16 encoding.  *
         *                                                            *
         * UTF8 = 1 bytes per char                                    *
         *    ["100" for the ansi 'd']                                *
         *    ["206" and "186" for the russian '?']                   *
         *                                                            *
         * UTF16 = 2 bytes per char                                   *
         *    ["100, 0" for the ansi 'd']                             *
         *    ["186, 3" for the russian '?']                          *
         *                                                            *
         * UTF8 inside UTF16                                          *
         *    ["100, 0" for the ansi 'd']                             *
         *    ["206, 0" and "186, 0" for the russian '?']             *
         *                                                            *
         * We can use the convert encoding function to convert an     *
         * UTF16 Byte-Array to an UTF8 Byte-Array. When we use UTF8   *
         * encoding to string method now, we will get a UTF16 string. *
         *                                                            *
         * So we imitate UTF16 by filling the second byte of a char   *
         * with a 0 byte (binary 0) while creating the string.        *
         **************************************************************/

        // Get UTF16 bytes and convert UTF16 bytes to UTF8 bytes
        byte[] utf16Bytes = Encoding.Unicode.GetBytes(utf16String);
        byte[] utf8Bytes = Encoding.Convert(Encoding.Unicode, Encoding.UTF8, utf16Bytes);
        char[] chars = (char[])Array.CreateInstance(typeof(char), utf8Bytes.Length);

        for (int i = 0; i < utf8Bytes.Length; i++)
        {
            chars[i] = BitConverter.ToChar(new byte[2] { utf8Bytes[i], 0 }, 0);
        }

        // Return UTF8
        return new String(chars);
    }

In the original post author concatenated strings. Every sting operation will result in string recreation in .Net. String is effectively a reference type. As a result, the function provided will be visibly slow. Don't do that. Use array of chars instead, write there directly and then convert result to string. In my case of processing 500 kb of text difference is almost 5 minutes.

How to resize JLabel ImageIcon?

And what about it?:

ImageIcon imageIcon = new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT));
label.setIcon(imageIcon);

From: Resize a picture to fit a JLabel

C# Reflection: How to get class reference from string?

You will want to use the Type.GetType method.

Here is a very simple example:

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        Type t = Type.GetType("Foo");
        MethodInfo method 
             = t.GetMethod("Bar", BindingFlags.Static | BindingFlags.Public);

        method.Invoke(null, null);
    }
}

class Foo
{
    public static void Bar()
    {
        Console.WriteLine("Bar");
    }
}

I say simple because it is very easy to find a type this way that is internal to the same assembly. Please see Jon's answer for a more thorough explanation as to what you will need to know about that. Once you have retrieved the type my example shows you how to invoke the method.

Counting number of words in a file

import java.io.BufferedReader;
import java.io.FileReader;

public class CountWords {

    public static void main (String args[]) throws Exception {

       System.out.println ("Counting Words");       
       FileReader fr = new FileReader ("c:\\Customer1.txt");        
       BufferedReader br = new BufferedReader (fr);     
       String line = br.readLin ();
       int count = 0;
       while (line != null) {
          String []parts = line.split(" ");
          for( String w : parts)
          {
            count++;        
          }
          line = br.readLine();
       }         
       System.out.println(count);
    }
}

javascript check for not null

If you want to be able to include 0 as a valid value:

if (!!val || val === 0) { ... }

Numbering rows within groups in a data frame

Here is a small improvement trick that allows sort 'val' inside the groups:

# 1. Data set
set.seed(100)
df <- data.frame(
  cat = c(rep("aaa", 5), rep("ccc", 5), rep("bbb", 5)), 
  val = runif(15))             

# 2. 'dplyr' approach
df %>% 
  arrange(cat, val) %>% 
  group_by(cat) %>% 
  mutate(id = row_number())

Django - how to create a file and save it to a model's FileField?

It's good practice to use a context manager or call close() in case of exceptions during the file saving process. Could happen if your storage backend is down, etc.

Any overwrite behavior should be configured in your storage backend. For example S3Boto3Storage has a setting AWS_S3_FILE_OVERWRITE. If you're using FileSystemStorage you can write a custom mixin.

You might also want to call the model's save method instead of the FileField's save method if you want any custom side-effects to happen, like last-updated timestamps. If that's the case, you can also set the name attribute of the file to the name of the file - which is relative to MEDIA_ROOT. It defaults to the full path of the file which can cause problems if you don't set it - see File.__init__() and File.name.

Here's an example where self is the model instance where my_file is the FileField / ImageFile, calling save() on the whole model instance instead of just FileField:

import os
from django.core.files import File

with open(filepath, 'rb') as fi:
    self.my_file = File(fi, name=os.path.basename(fi.name))
    self.save()

Troubleshooting BadImageFormatException

When I faced this issue the following solved it for me:

I was calling a OpenCV dll from inside another exe, my dll did not contained the already needed opencv dlls like highgui, features2d, and etc available in the folder of my exe file. I copied all these to the directory of my exe project and it suddenly worked.

How to remove a file from the index in git?

According to my humble opinion and my work experience with git, staging area is not the same as index. I may be wrong of course, but as I said, my experience in using git and my logic tell me, that index is a structure that follows your changes to your working area(local repository) that are not excluded by ignoring settings and staging area is to keep files that are already confirmed to be committed, aka files in index on which add command was run on. You don't notice and realize that "slight" difference, because you use git commit -a -m "comment" adding indexed and cached files to stage area and committing in one command or using IDEs like IDEA for that too often. And cache is that what keeps changes in indexed files. If you want to remove file from index that has not been added to staging area before, options proposed before match for you, but... If you have done that already, you will need to use

Git restore --staged <file>

And, please, don't ask me where I was 10 years ago... I missed you, this answer is for further generations)

How to get the pure text without HTML element using JavaScript?

function get_content(){
 var returnInnerHTML = document.getElementById('A').innerHTML + document.getElementById('B').innerHTML + document.getElementById('A').innerHTML;
 document.getElementById('txt').innerHTML = returnInnerHTML;
}

That should do it.

How to manage startActivityForResult on Android?

Complementing the answer from @Nishant,the best way to return the activity result is:

Intent returnIntent = getIntent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();

I was having problem with

new Intent();

Then I found out that the correct way is using

getIntent();

to get the current intent

Python unittest passing arguments

This is my solution:

# your test class
class TestingClass(unittest.TestCase):
    
    # This will only run once for all the tests within this class
    @classmethod
    def setUpClass(cls) -> None:
       if len(sys.argv) > 1:
          cls.email = sys.argv[1]

    def testEmails(self):
        assertEqual(self.email, "[email protected]")


if __name__ == "__main__":
    unittest.main()

you could have a runner.py file with something like this:

# your runner.py
loader = unittest.TestLoader()
tests = loader.discover('.') # note that this will find all your tests, you can also provide the name of the package e.g. `loader.discover('tests')
runner = unittest.TextTestRunner(verbose=3)
result = runner.run(tests


with the above code, you should be to run your tests with runner.py [email protected]

JUnit 5: How to assert an exception is thrown?

You can use assertThrows(). My example is taken from the docs http://junit.org/junit5/docs/current/user-guide/

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

....

@Test
void exceptionTesting() {
    Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
        throw new IllegalArgumentException("a message");
    });
    assertEquals("a message", exception.getMessage());
}

Pointers in Python?

The following code emulates exactly the behavior of pointers in C:

from collections import deque # more efficient than list for appending things
pointer_storage = deque()
pointer_address = 0

class new:    
    def __init__(self):
        global pointer_storage    
        global pointer_address

        self.address = pointer_address
        self.val = None        
        pointer_storage.append(self)
        pointer_address += 1


def get_pointer(address):
    return pointer_storage[address]

def get_address(p):
    return p.address

null = new() # create a null pointer, whose address is 0    

Here are examples of use:

p = new()
p.val = 'hello'
q = new()
q.val = p
r = new()
r.val = 33

p = get_pointer(3)
print(p.val, flush = True)
p.val = 43
print(get_pointer(3).val, flush = True)

But it's now time to give a more professional code, including the option of deleting pointers, that I've just found in my personal library:

# C pointer emulation:

from collections import deque # more efficient than list for appending things
from sortedcontainers import SortedList #perform add and discard in log(n) times


class new:      
    # C pointer emulation:
    # use as : p = new()
    #          p.val             
    #          p.val = something
    #          p.address
    #          get_address(p) 
    #          del_pointer(p) 
    #          null (a null pointer)

    __pointer_storage__ = SortedList(key = lambda p: p.address)
    __to_delete_pointers__ = deque()
    __pointer_address__ = 0 

    def __init__(self):      

        self.val = None 

        if new.__to_delete_pointers__:
            p = new.__to_delete_pointers__.pop()
            self.address = p.address
            new.__pointer_storage__.discard(p) # performed in log(n) time thanks to sortedcontainers
            new.__pointer_storage__.add(self)  # idem

        else:
            self.address = new.__pointer_address__
            new.__pointer_storage__.add(self)
            new.__pointer_address__ += 1


def get_pointer(address):
    return new.__pointer_storage__[address]


def get_address(p):
    return p.address


def del_pointer(p):
    new.__to_delete_pointers__.append(p)

null = new() # create a null pointer, whose address is 0

How to keep form values after post

If you are looking to just repopulate the fields with the values that were posted in them, then just echo the post value back into the field, like so:

<input type="text" name="myField1" value="<?php echo isset($_POST['myField1']) ? $_POST['myField1'] : '' ?>" />

How to position a div in bottom right corner of a browser?

This snippet works in IE7 at least

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Test</title>
<style>
  #foo {
    position: fixed;
    bottom: 0;
    right: 0;
  }
</style>
</head>
<body>
  <div id="foo">Hello World</div>
</body>
</html>

Android: How to detect double-tap?

To detect the type of gesture tap one can implement something inline with this: ( here projectText is an EditText )

    projectText.setOnTouchListener(new View.OnTouchListener() {
        private GestureDetector gestureDetector = new GestureDetector(activity, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onDoubleTap(MotionEvent e) {
                projectText.setInputType(InputType.TYPE_CLASS_TEXT);
                activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
                return super.onDoubleTap(e);
            }
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                    projectText.setInputType(InputType.TYPE_NULL); // disable soft input
                    final int itemPosition = getLayoutPosition();
                    if(!projects.get(itemPosition).getProjectId().equals("-1"))
                        listener.selectedClick(projects.get(itemPosition));

                return super.onSingleTapUp(e);
            }

        });

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            gestureDetector.onTouchEvent(event);
            return false; //true stops propagation of the event
        }

    });

How can I detect the touch event of an UIImageView?

To add a touch event to a UIImageView, use the following in your .m file:

UITapGestureRecognizer *newTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myTapMethod)];

[myImageView setUserInteractionEnabled:YES];

[myImageView addGestureRecognizer:newTap];


-(void)myTapMethod{
    // Treat image tap
}

How to change visibility of layout programmatically

this is a programatical approach:

 view.setVisibility(View.GONE); //For GONE
 view.setVisibility(View.INVISIBLE); //For INVISIBLE
 view.setVisibility(View.VISIBLE); //For VISIBLE

Listening for variable changes in JavaScript

AngularJS (I know this is not JQuery, but that might help. [Pure JS is good in theory only]):

$scope.$watch('data', function(newValue) { ..

where "data" is name of your variable in the scope.

There is a link to doc.

What is a NullReferenceException, and how do I fix it?

It means that the variable in question is pointed at nothing. I could generate this like so:

SqlConnection connection = null;
connection.Open();

That will throw the error because while I've declared the variable "connection", it's not pointed to anything. When I try to call the member "Open", there's no reference for it to resolve, and it will throw the error.

To avoid this error:

  1. Always initialize your objects before you try to do anything with them.
  2. If you're not sure whether the object is null, check it with object == null.

JetBrains' Resharper tool will identify every place in your code that has the possibility of a null reference error, allowing you to put in a null check. This error is the number one source of bugs, IMHO.

Best way to do Version Control for MS Excel

Working upon @Demosthenex work, @Tmdean and @Jon Crowell invaluable comments! (+1 them)

I save module files in git\ dir beside workbook location. Change that to your liking.

This will NOT track changes to Workbook code. So it's up to you to synchronize them.

Sub SaveCodeModules()

'This code Exports all VBA modules
Dim i As Integer, name As String

With ThisWorkbook.VBProject
    For i = .VBComponents.count To 1 Step -1
        If .VBComponents(i).Type <> vbext_ct_Document Then
            If .VBComponents(i).CodeModule.CountOfLines > 0 Then
                name = .VBComponents(i).CodeModule.name
                .VBComponents(i).Export Application.ThisWorkbook.Path & _
                                            "\git\" & name & ".vba"
            End If
        End If
    Next i
End With

End Sub

Sub ImportCodeModules()
Dim i As Integer
Dim ModuleName As String

With ThisWorkbook.VBProject
    For i = .VBComponents.count To 1 Step -1

        ModuleName = .VBComponents(i).CodeModule.name

        If ModuleName <> "VersionControl" Then
            If .VBComponents(i).Type <> vbext_ct_Document Then
                .VBComponents.Remove .VBComponents(ModuleName)
                .VBComponents.Import Application.ThisWorkbook.Path & _
                                         "\git\" & ModuleName & ".vba"
            End If
        End If
    Next i
End With

End Sub

And then in Workbook module:

Private Sub Workbook_Open()

    ImportCodeModules

End Sub

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

    SaveCodeModules

End Sub

'readline/readline.h' file not found

This command helped me on linux mint when i had exact same problem

gcc filename.c -L/usr/include -lreadline -o filename

You could use alias if you compile it many times Forexample:

alias compilefilename='gcc filename.c -L/usr/include -lreadline -o filename'

What is the difference between `sorted(list)` vs `list.sort()`?

sorted() returns a new sorted list, leaving the original list unaffected. list.sort() sorts the list in-place, mutating the list indices, and returns None (like all in-place operations).

sorted() works on any iterable, not just lists. Strings, tuples, dictionaries (you'll get the keys), generators, etc., returning a list containing all elements, sorted.

  • Use list.sort() when you want to mutate the list, sorted() when you want a new sorted object back. Use sorted() when you want to sort something that is an iterable, not a list yet.

  • For lists, list.sort() is faster than sorted() because it doesn't have to create a copy. For any other iterable, you have no choice.

  • No, you cannot retrieve the original positions. Once you called list.sort() the original order is gone.

Firebase onMessageReceived not called when app in background

this method handleIntent() has been depreciated, so handling a notification can be done as below:

  1. Foreground State: The click of the notification will go to the pending Intent's activity which you are providing while creating a notification pro-grammatically as it generally created with data payload of the notification.

  2. Background/Killed State - Here, the system itself creates a notification based on notification payload and clicking on that notification will take you to the launcher activity of the application where you can easily fetch Intent data in any of your life-cycle methods.

How to display Woocommerce Category image?

From the WooCommerce page:

// WooCommerce – display category image on category archive

add_action( 'woocommerce_archive_description', 'woocommerce_category_image', 2 );
function woocommerce_category_image() {
    if ( is_product_category() ){
      global $wp_query;
      $cat = $wp_query->get_queried_object();
      $thumbnail_id = get_woocommerce_term_meta( $cat->term_id, 'thumbnail_id', true );
      $image = wp_get_attachment_url( $thumbnail_id );
      if ( $image ) {
          echo '<img src="' . $image . '" alt="" />';
      }
  }
}

Why do python lists have pop() but not push()

Push and Pop make sense in terms of the metaphor of a stack of plates or trays in a cafeteria or buffet, specifically the ones in type of holder that has a spring underneath so the top plate is (more or less... in theory) in the same place no matter how many plates are under it.

If you remove a tray, the weight on the spring is a little less and the stack "pops" up a little, if you put the plate back, it "push"es the stack down. So if you think about the list as a stack and the last element as being on top, then you shouldn't have much confusion.

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

There is this bug which looks suspiciously similar: https://hibernate.atlassian.net/browse/HHH-9940.

And the code to reproduce it: https://github.com/abenneke/sandbox/tree/master/hibernate-null-collection/src/test

There are 2 possible fixes to this:

  • the collection is initialized with an empty collection (instead of null)

  • orphanRemoval is set to false

Example - was:

@OneToMany(cascade = CascadeType.REMOVE,
        mappedBy = "jobEntity", orphanRemoval = true)
private List<JobExecutionEntity> jobExecutionEntities;

became:

@OneToMany(cascade = CascadeType.REMOVE,
        mappedBy = "jobEntity")
private List<JobExecutionEntity> jobExecutionEntities;

setHintTextColor() in EditText

This is like default hint color, worked for me:

editText.setHintTextColor(Color.GRAY);

Replace a value if null or undefined in JavaScript

I spotted half of the problem: I can't use the 'indexer' notation to objects (my_object[0]). Is there a way to bypass it?

No; an object literal, as the name implies, is an object, and not an array, so you cannot simply retrieve a property based on an index, since there is no specific order of their properties. The only way to retrieve their values is by using the specific name:

var someVar = options.filters.firstName; //Returns 'abc'

Or by iterating over them using the for ... in loop:

for(var p in options.filters) {
    var someVar = options.filters[p]; //Returns the property being iterated
}

how to determine size of tablespace oracle 11g

The following query can be used to detemine tablespace and other params:

select df.tablespace_name "Tablespace",
       totalusedspace "Used MB",
       (df.totalspace - tu.totalusedspace) "Free MB",
       df.totalspace "Total MB",
       round(100 * ( (df.totalspace - tu.totalusedspace)/ df.totalspace)) "Pct. Free"
  from (select tablespace_name,
               round(sum(bytes) / 1048576) TotalSpace
          from dba_data_files 
         group by tablespace_name) df,
       (select round(sum(bytes)/(1024*1024)) totalusedspace,
               tablespace_name
          from dba_segments 
         group by tablespace_name) tu
 where df.tablespace_name = tu.tablespace_name 
   and df.totalspace <> 0;

Source: https://community.oracle.com/message/1832920

For your case if you want to know the partition name and it's size just run this query:

select owner,
       segment_name,
       partition_name,
       segment_type,
       bytes / 1024/1024 "MB" 
  from dba_segments 
 where owner = <owner_name>;

Reinitialize Slick js after successful ajax call

Note: I am not sure if this is correct but you can give it a try and see if this works.

There is a unslick method which de-initializes the carousel, so you might try using that before re-initializing it.

$.ajax({
    type: 'get',
    url: '/public/index',
    dataType: 'script',
    data: data_send,
    success: function() {
        $('.skills_section').unslick();  // destroy the previous instance
        slickCarousel();
      }
});

Hope this helps.

Convert string to hex-string in C#

var result = string.Join("", input.Select(c => ((int)c).ToString("X2")));

OR

var result  =string.Join("", 
                input.Select(c=> String.Format("{0:X2}", Convert.ToInt32(c))));

Python: Binding Socket: "Address already in use"

You need to set the allow_reuse_address before binding. Instead of the SimpleHTTPServer run this snippet:

Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler, bind_and_activate=False)
httpd.allow_reuse_address = True
httpd.server_bind()
httpd.server_activate()
httpd.serve_forever()

This prevents the server from binding before we got a chance to set the flags.

Serialize form data to JSON

If you do not care about repetitive form elements with the same name, then you can do:

var data = $("form.login").serializeArray();
var formData = _.object(_.pluck(data, 'name'), _.pluck(data, 'value'));

I am using Underscore.js here.

Accessing Imap in C#

MailSystem.NET contains all your need for IMAP4. It's free & open source.

(I'm involved in the project)

Regex pattern to match at least 1 number and 1 character in a string

Why not first apply the whole test, and then add individual tests for characters and numbers? Anyway, if you want to do it all in one regexp, use positive lookahead:

/^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

If you want to use valueChangeListener, you need to submit the form every time a new option is chosen. Something like this:

<p:selectOneMenu value="#{mymb.employee}" onchange="submit()"
                 valueChangeListener="#{mymb.handleChange}" >
    <f:selectItems value="#{mymb.employeesList}" var="emp"
                   itemLabel="#{emp.employeeName}" itemValue="#{emp.employeeID}" />
</p:selectOneMenu>

public void handleChange(ValueChangeEvent event){  
    System.out.println("New value: " + event.getNewValue());
}

Or else, if you want to use <p:ajax>, it should look like this:

<p:selectOneMenu value="#{mymb.employee}" >
    <p:ajax listener="#{mymb.handleChange}" />
    <f:selectItems value="#{mymb.employeesList}" var="emp"
                   itemLabel="#{emp.employeeName}" itemValue="#{emp.employeeID}" />
</p:selectOneMenu>

private String employeeID;

public void handleChange(){  
    System.out.println("New value: " + employee);
}

One thing to note is that in your example code, I saw that the value attribute of your <p:selectOneMenu> is #{mymb.employeesList} which is the same as the value of <f:selectItems>. The value of your <p:selectOneMenu> should be similar to my examples above which point to a single employee, not a list of employees.

Oracle REPLACE() function isn't handling carriage-returns & line-feeds

If the data in your database is POSTED from HTML form TextArea controls, different browsers use different New Line characters:

Firefox separates lines with CHR(10) only

Internet Explorer separates lines with CHR(13) + CHR(10)

Apple (pre-OSX) separates lines with CHR(13) only

So you may need something like:

set col_name = replace(replace(col_name, CHR(13), ''), CHR(10), '')

What are the use cases for selecting CHAR over VARCHAR in SQL?

CHAR takes up less storage space than VARCHAR if all your data values in that field are the same length. Now perhaps in 2009 a 800GB database is the same for all intents and purposes as a 810GB if you converted the VARCHARs to CHARs, but for short strings (1 or 2 characters), CHAR is still a industry "best practice" I would say.

Now if you look at the wide variety of data types most databases provide even for integers alone (bit, tiny, int, bigint), there ARE reasons to choose one over the other. Simply choosing bigint every time is actually being a bit ignorant of the purposes and uses of the field. If a field simply represents a persons age in years, a bigint is overkill. Now it's not necessarily "wrong", but it's not efficient.

But its an interesting argument, and as databases improve over time, it could be argued CHAR vs VARCHAR does get less relevant.

Prevent the keyboard from displaying on activity start

Add these two properties to your parent layout (ex: Linear Layout, Relative Layout)

android:focusable="false"
android:focusableInTouchMode="false" 

It will do the trick :)

How do you change the datatype of a column in SQL Server?

The syntax to modify a column in an existing table in SQL Server (Transact-SQL) is:

ALTER TABLE table_name
    ALTER COLUMN column_name column_type;

For example:

ALTER TABLE employees
    ALTER COLUMN last_name VARCHAR(75) NOT NULL;

This SQL Server ALTER TABLE example will modify the column called last_name to be a data type of VARCHAR(75) and force the column to not allow null values.

see here

Iterating through a list to render multiple widgets in Flutter?

when you return some thing, the code exits out of the loop with what ever you are returning.so, in your code, in the first iteration, name is "one". so, as soon as it reaches return new Text(name), code exits the loop with return new Text("one"). so, try to print it or use asynchronous returns.

iptables LOG and DROP in one rule

Although already over a year old, I stumbled across this question a couple of times on other Google search and I believe I can improve on the previous answer for the benefit of others.

Short answer is you cannot combine both action in one line, but you can create a chain that does what you want and then call it in a one liner.

Let's create a chain to log and accept:

iptables -N LOG_ACCEPT

And let's populate its rules:

iptables -A LOG_ACCEPT -j LOG --log-prefix "INPUT:ACCEPT:" --log-level 6
iptables -A LOG_ACCEPT -j ACCEPT

Now let's create a chain to log and drop:

iptables -N LOG_DROP

And let's populate its rules:

iptables -A LOG_DROP -j LOG --log-prefix "INPUT:DROP: " --log-level 6
iptables -A LOG_DROP -j DROP

Now you can do all actions in one go by jumping (-j) to you custom chains instead of the default LOG / ACCEPT / REJECT / DROP:

iptables -A <your_chain_here> <your_conditions_here> -j LOG_ACCEPT
iptables -A <your_chain_here> <your_conditions_here> -j LOG_DROP

How can you determine a point is between two other points on a line segment?

Here's another approach:

  • Lets assume the two points be A (x1,y1) and B (x2,y2)
  • The equation of the line passing through those points is (x-x1)/(y-y1)=(x2-x1)/(y2-y1) .. (just making equating the slopes)

Point C (x3,y3) will lie between A & B if:

  • x3,y3 satisfies the above equation.
  • x3 lies between x1 & x2 and y3 lies between y1 & y2 (trivial check)

How to convert a Java String to an ASCII byte array?

In my string I have Thai characters (TIS620 encoded) and German umlauts. The answer from agiles put me on the right path. Instead of .getBytes() I use now

  int len = mString.length(); // Length of the string
  byte[] dataset = new byte[len];
  for (int i = 0; i < len; ++i) {
     char c = mString.charAt(i);
     dataset[i]= (byte) c;
  }

Add Favicon with React and Webpack

Use the file-loader for that:

{
    test: /\.(svg|png|gif|jpg|ico)$/,
    include: path.resolve(__dirname, path),
    use: {
        loader: 'file-loader',
        options: {
            context: 'src/assets',
            name: 'root[path][name].[ext]'
        }
    }
}

What's the difference between 'git merge' and 'git rebase'?

Personally I don't find the standard diagramming technique very helpful - the arrows always seem to point the wrong way for me. (They generally point towards the "parent" of each commit, which ends up being backwards in time, which is weird).

To explain it in words:

  • When you rebase your branch onto their branch, you tell Git to make it look as though you checked out their branch cleanly, then did all your work starting from there. That makes a clean, conceptually simple package of changes that someone can review. You can repeat this process again when there are new changes on their branch, and you will always end up with a clean set of changes "on the tip" of their branch.
  • When you merge their branch into your branch, you tie the two branch histories together at this point. If you do this again later with more changes, you begin to create an interleaved thread of histories: some of their changes, some of my changes, some of their changes. Some people find this messy or undesirable.

For reasons I don't understand, GUI tools for Git have never made much of an effort to present merge histories more cleanly, abstracting out the individual merges. So if you want a "clean history", you need to use rebase.

I seem to recall having read blog posts from programmers who only use rebase and others that never use rebase.

Example

I'll try explaining this with a just-words example. Let's say other people on your project are working on the user interface, and you're writing documentation. Without rebase, your history might look something like:

Write tutorial
Merge remote-tracking branch 'origin/master' into fixdocs
Bigger buttons
Drop down list
Extend README
Merge remote-tracking branch 'origin/master' into fixdocs
Make window larger
Fix a mistake in howto.md

That is, merges and UI commits in the middle of your documentation commits.

If you rebased your code onto master instead of merging it, it would look like this:

Write tutorial
Extend README
Fix a mistake in howto.md
Bigger buttons
Drop down list
Make window larger

All of your commits are at the top (newest), followed by the rest of the master branch.

(Disclaimer: I'm the author of the "10 things I hate about Git" post referred to in another answer)

JUnit test for System.out.println()

Based on @dfa's answer and another answer that shows how to test System.in, I would like to share my solution to give an input to a program and test its output.

As a reference, I use JUnit 4.12.

Let's say we have this program that simply replicates input to output:

import java.util.Scanner;

public class SimpleProgram {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print(scanner.next());
        scanner.close();
    }
}

To test it, we can use the following class:

import static org.junit.Assert.*;

import java.io.*;

import org.junit.*;

public class SimpleProgramTest {
    private final InputStream systemIn = System.in;
    private final PrintStream systemOut = System.out;

    private ByteArrayInputStream testIn;
    private ByteArrayOutputStream testOut;

    @Before
    public void setUpOutput() {
        testOut = new ByteArrayOutputStream();
        System.setOut(new PrintStream(testOut));
    }

    private void provideInput(String data) {
        testIn = new ByteArrayInputStream(data.getBytes());
        System.setIn(testIn);
    }

    private String getOutput() {
        return testOut.toString();
    }

    @After
    public void restoreSystemInputOutput() {
        System.setIn(systemIn);
        System.setOut(systemOut);
    }

    @Test
    public void testCase1() {
        final String testString = "Hello!";
        provideInput(testString);

        SimpleProgram.main(new String[0]);

        assertEquals(testString, getOutput());
    }
}

I won't explain much, because I believe the code is readable and I cited my sources.

When JUnit runs testCase1(), it is going to call the helper methods in the order they appear:

  1. setUpOutput(), because of the @Before annotation
  2. provideInput(String data), called from testCase1()
  3. getOutput(), called from testCase1()
  4. restoreSystemInputOutput(), because of the @After annotation

I didn't test System.err because I didn't need it, but it should be easy to implement, similar to testing System.out.

Force browser to download image files on click

Try this:

<a class="button" href="http://www.glamquotes.com/wp-content/uploads/2011/11/smile.jpg" download="smile.jpg">Download image</a>

missing FROM-clause entry for table

SELECT 
   AcId, AcName, PldepPer, RepId, CustCatg, HardCode, BlockCust, CrPeriod, CrLimit, 
   BillLimit, Mode, PNotes, gtab82.memno 
FROM
   VCustomer AS v1
INNER JOIN   
   gtab82 ON gtab82.memacid = v1.AcId 
WHERE (AcGrCode = '204' OR CreDebt = 'True') 
AND Masked = 'false'
ORDER BY AcName

You typically only use an alias for a table name when you need to prefix a column with the table name due to duplicate column names in the joined tables and the table name is long or when the table is joined to itself. In your case you use an alias for VCustomer but only use it in the ON clause for uncertain reasons. You may want to review that aspect of your code.

Docker can't connect to docker daemon

I had the same problem - "Can't connect to docker daemon." (except I didn't get any 'file not found' errors on trying to start the server.)

'ps' showed that "/usr/bin/docker -d" was still running

I realised that I'd never actually succeeded in running the server myself though. Every attempt had produced

...
2014/03/24 21:57:29 pid file found, ensure docker is not running or delete /var/run/docker.pid

So I belatedly realised that installing docker had maybe registered the daemon with upstart, which had started it for me. Hence, trying to kill the daemon to manually restart it fails (operation not permitted). So I did a

sudo kill -9 <PID>

on the daemon process. Another daemon immediately took its place, and this new one DOES now let my CLI client connect:

$ sudo docker info
Containers: 0
Images: 0
Driver: aufs
 Root Dir: /var/lib/docker/aufs
 Dirs: 0
WARNING: No memory limit support
WARNING: No swap limit support

Can I get image from canvas element and use it in img src tag?

Do this. Add this to the bottom of your doc just before you close the body tag.

<script>
    function canvasToImg() {
      var canvas = document.getElementById("yourCanvasID");
      var ctx=canvas.getContext("2d");
      //draw a red box
      ctx.fillStyle="#FF0000";
      ctx.fillRect(10,10,30,30);

      var url = canvas.toDataURL();

      var newImg = document.createElement("img"); // create img tag
      newImg.src = url;
      document.body.appendChild(newImg); // add to end of your document
    }

    canvasToImg(); //execute the function
</script>

Of course somewhere in your doc you need the canvas tag that it will grab.

<canvas id="yourCanvasID" />

Collections.sort with multiple fields

Here is a full example comparing 2 fields in an object, one String and one int, also using Collator to sort.

public class Test {

    public static void main(String[] args) {

        Collator myCollator;
        myCollator = Collator.getInstance(Locale.US);

        List<Item> items = new ArrayList<Item>();

        items.add(new Item("costrels", 1039737, ""));
        items.add(new Item("Costs", 1570019, ""));
        items.add(new Item("costs", 310831, ""));
        items.add(new Item("costs", 310832, ""));

        Collections.sort(items, new Comparator<Item>() {
            @Override
            public int compare(final Item record1, final Item record2) {
                int c;
                //c = record1.item1.compareTo(record2.item1); //optional comparison without Collator                
                c = myCollator.compare(record1.item1, record2.item1);
                if (c == 0) 
                {
                    return record1.item2 < record2.item2 ? -1
                            :  record1.item2 > record2.item2 ? 1
                            : 0;
                }
                return c;
            }
        });     

        for (Item item : items)
        {
            System.out.println(item.item1);
            System.out.println(item.item2);
        }       

    }

    public static class Item
    {
        public String item1;
        public int item2;
        public String item3;

        public Item(String item1, int item2, String item3)
        {
            this.item1 = item1;
            this.item2 = item2;
            this.item3 = item3;
        }       
    }

}

Output:

costrels 1039737

costs 310831

costs 310832

Costs 1570019

JavaScript: remove event listener

I think you may need to define the handler function ahead of time, like so:

var myHandler = function(event) {
    click++; 
    if(click == 50) { 
        this.removeEventListener('click', myHandler);
    } 
}
canvas.addEventListener('click', myHandler);

This will allow you to remove the handler by name from within itself.

How to add and remove classes in Javascript without jQuery

Another approach to add the class to element using pure JavaScript

For adding class:

document.getElementById("div1").classList.add("classToBeAdded");

For removing class:

document.getElementById("div1").classList.remove("classToBeRemoved");

Note: but not supported in IE <= 9 or Safari <=5.0

How do you view ALL text from an ntext or nvarchar(max) in SSMS?

PowerShell Alternative

This is an old post and I read through the answers. Still, I found it a bit too painful to output multi-line large text fields unaltered from SSMS. I ended up writing a small C# program for my needs, but got to thinking it could probably be done using the command line. Turns out, it is fairly easy to do so with PowerShell.

Start by installing the SqlServer module from an administrative PowerShell.

Install-Module -Name SqlServer

Use Invoke-Sqlcmd to run your query:

$Rows = Invoke-Sqlcmd -Query "select BigColumn from SomeTable where Id = 123" `
    -As DataRows -MaxCharLength 1000000 -ConnectionString $ConnectionString

This will return an array of rows that you can output to the console as follows:

$Rows[0].BigColumn

Or output to a file as follows:

$Rows[0].BigColumn | Out-File -FilePath .\output.txt -Encoding UTF8

The result is a beautiful un-truncated text written to a file for viewing/editing. I am sure there is a similar command to save back the text to SQL Server, although that seems like a different question.

EDIT: It turns out that there was an answer by @dvlsc that described this approach as a secondary solution. I think because it was listed as a secondary answer, is the reason I missed it in the first place. I am going to leave my answer which focuses on the PowerShell approach, but wanted to at least give credit where it was due.

CRC32 C or C++ implementation

The SNIPPETS C Source Code Archive has a CRC32 implementation that is freely usable:

/* Copyright (C) 1986 Gary S. Brown.  You may use this program, or
   code or tables extracted from it, as desired without restriction.*/

(Unfortunately, c.snippets.org seems to have died. Fortunately, the Wayback Machine has it archived.)

In order to be able to compile the code, you'll need to add typedefs for BYTE as an unsigned 8-bit integer and DWORD as an unsigned 32-bit integer, along with the header files crc.h & sniptype.h.

The only critical item in the header is this macro (which could just as easily go in CRC_32.c itself:

#define UPDC32(octet, crc) (crc_32_tab[((crc) ^ (octet)) & 0xff] ^ ((crc) >> 8))

How to embed a Facebook page's feed into my website

For website developers, another option you have is to follow a working Facebook Graph API tutorial such as this one.

But if you need a quick solution where you can customize and embed a Facebook page feed instantly, you should use website plugins such as this one.

Here's a step by step guide:

  1. Get a Free Key or Paid Key.
  2. Go to this login page and use the key to login.
  3. Once logged in, click “+ Create Custom Feed” button.
  4. On the pop up, name your custom Facebook page feed.
  5. On the drop-down, select “Facebook Page Feed On Your Website” option.
  6. Enter your Facebook Page ID.
  7. Click the “Proceed” button. This will show you the customization options.
  8. Click the “ Embed On Website” button located on the upper-right corner of the screen.
  9. On the pop up, copy the embed code by clicking the “Copy Code” button.
  10. Paste the embed code on your website.

Visit the tutorial link to see a live demo there as well.

Zabbix server is not running: the information displayed may not be current

I was using a special character in my DB password - wrapping the DBPassword option in /etc/zabbix/zabbix_server.conf and doing sudo service zabbix-server restart got me back up and running.

Not Working DBPassword=MyString?

Working DBPassword='MyString?'

Java Replace Character At Specific Position Of String?

If you need to re-use a string, then use StringBuffer:

String str = "hi";
StringBuffer sb = new StringBuffer(str);
while (...) {
    sb.setCharAt(1, 'k');
}

EDIT:

Note that StringBuffer is thread-safe, while using StringBuilder is faster, but not thread-safe.

How do I get the RootViewController from a pushed controller?

Here I came up with universal method to navigate from any place to root.

  1. You create a new Class file with this class, so that it's accessible from anywhere in your project:

    import UIKit
    
    class SharedControllers
    {
        static func navigateToRoot(viewController: UIViewController)
        {
            var nc = viewController.navigationController
    
            // If this is a normal view with NavigationController, then we just pop to root.
            if nc != nil
            {
                nc?.popToRootViewControllerAnimated(true)
                return
            }
    
            // Most likely we are in Modal view, so we will need to search for a view with NavigationController.
            let vc = viewController.presentingViewController
    
            if nc == nil
            {
                nc = viewController.presentingViewController?.navigationController
            }
    
            if nc == nil
            {
                nc = viewController.parentViewController?.navigationController
            }
    
            if vc is UINavigationController && nc == nil
            {
                nc = vc as? UINavigationController
            }
    
            if nc != nil
            {
                viewController.dismissViewControllerAnimated(false, completion:
                    {
                        nc?.popToRootViewControllerAnimated(true)
                })
            }
        }
    }
    
  2. Usage from anywhere in your project:

    {
        ...
        SharedControllers.navigateToRoot(self)
        ...
    }
    

Angular cookies

Yeah, here is one ng2-cookies

Usage:

import { Cookie } from 'ng2-cookies/ng2-cookies';

Cookie.setCookie('cookieName', 'cookieValue');
Cookie.setCookie('cookieName', 'cookieValue', 10 /*days from now*/);
Cookie.setCookie('cookieName', 'cookieValue', 10, '/myapp/', 'mydomain.com');

let myCookie = Cookie.getCookie('cookieName');

Cookie.deleteCookie('cookieName');

SQL- Ignore case while searching for a string

Like this.

SELECT DISTINCT COL_NAME FROM myTable WHERE COL_NAME iLIKE '%Priceorder%'

In postgresql.

Select DataFrame rows between two dates

Keeping the solution simple and pythonic, I would suggest you to try this.

In case if you are going to do this frequently the best solution would be to first set the date column as index which will convert the column in DateTimeIndex and use the following condition to slice any range of dates.

import pandas as pd

data_frame = data_frame.set_index('date')

df = data_frame[(data_frame.index > '2017-08-10') & (data_frame.index <= '2017-08-15')]

htaccess "order" Deny, Allow, Deny

Just use order allow,deny instead and remove the deny from all line.

How do I return to an older version of our code in Subversion?

Jon Skeet's answer is pretty much the solution in a nutshell, however if you are like me, you might want an explanation. The Subversion manual calls this a

Cherry-Pick Merge

From the man pages.

  1. This form is called a 'cherry-pick' merge: '-r N:M' refers to the difference in the history of the source branch between revisions N and M.

    A 'reverse range' can be used to undo changes. For example, when source and target refer to the same branch, a previously committed revision can be 'undone'. In a reverse range, N is greater than M in '-r N:M', or the '-c' option is used with a negative number: '-c -M' is equivalent to '-r M:'. Undoing changes like this is also known as performing a 'reverse merge'.


  • If the source is a file, then differences are applied to that file (useful for reverse-merging earlier changes). Otherwise, if the source is a directory, then the target defaults to '.'.

    In normal usage the working copy should be up to date, at a single revision, with no local modifications and no switched subtrees.

Example:

svn merge -r 2983:289 path/to/file

This will replace the local copy[2983] (which, according to the quote above, should be in sync with the server--your responsibility) with the revision 289 from the server. The change happens locally, which means if you have a clean checkout, then the changes can be inspected before committing them.

Floating point vs integer calculations on modern hardware

The floating point version will be much slower, if there is no remainder operation. Since all the adds are sequential, the cpu will not be able to parallelise the summation. The latency will be critical. FPU add latency is typically 3 cycles, while integer add is 1 cycle. However, the divider for the remainder operator will probably the critical part, as it is not fully pipelined on modern cpu's. so, assuming the divide/remainder instruction will consume the bulk of the time, the difference due to add latency will be small.

Adding author name in Eclipse automatically to existing files

Shift + Alt + J will help you add author name in existing file.

To add author name automatically,
go to Preferences --> --> Code Style --> Code Templates

Preferences -- Java -- Code Style -- Code Templates

in case you don't find above option in new versions of Eclipse - install it from https://marketplace.eclipse.org/content/jautodoc

SQL providerName in web.config

System.Data.SqlClient is the .NET Framework Data Provider for SQL Server. ie .NET library for SQL Server.

I don't know where providerName=SqlServer comes from. Could you be getting this confused with the provider keyword in your connection string? (I know I was :) )

In the web.config you should have the System.Data.SqlClient as the value of the providerName attribute. It is the .NET Framework Data Provider you are using.

<connectionStrings>
   <add 
      name="LocalSqlServer" 
      connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" 
      providerName="System.Data.SqlClient"
   />
</connectionStrings>

See http://msdn.microsoft.com/en-US/library/htw9h4z3(v=VS.80).aspx

RequiredIf Conditional Validation Attribute

I had the same problem yesterday, but I did it in a very clean way which works for both client side and server side validation.

Condition: Based on the value of other property in the model, you want to make another property required. Here is the code:

public class RequiredIfAttribute : RequiredAttribute
{
  private String PropertyName { get; set; }
  private Object DesiredValue { get; set; }

  public RequiredIfAttribute(String propertyName, Object desiredvalue)
  {
    PropertyName = propertyName;
    DesiredValue = desiredvalue;
  }

  protected override ValidationResult IsValid(object value, ValidationContext context)
  {
    Object instance = context.ObjectInstance;
    Type type = instance.GetType();
    Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
    if (proprtyvalue.ToString() == DesiredValue.ToString())
    {
      ValidationResult result = base.IsValid(value, context);
      return result;
    }
    return ValidationResult.Success;
  }
}

PropertyName is the property on which you want to make your condition
DesiredValue is the particular value of the PropertyName (property) for which your other property has to be validated for required

Say you have the following:

public enum UserType
{
  Admin,
  Regular
}

public class User
{
  public UserType UserType {get;set;}

  [RequiredIf("UserType",UserType.Admin,
              ErrorMessageResourceName="PasswordRequired", 
              ErrorMessageResourceType = typeof(ResourceString))]
  public string Password { get; set; }
}

At last but not the least, register adapter for your attribute so that it can do client side validation (I put it in global.asax, Application_Start)

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(RequiredIfAttribute),
                                                      typeof(RequiredAttributeAdapter));

EDITED

Some people was complaining that the client side fires no matter what or it does not work. So I modified the above code to do conditional client side validation with Javascript as well. For this case you don't need to register adapter

 public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
    {
        private String PropertyName { get; set; }
        private Object DesiredValue { get; set; }
        private readonly RequiredAttribute _innerAttribute;

        public RequiredIfAttribute(String propertyName, Object desiredvalue)
        {
            PropertyName = propertyName;
            DesiredValue = desiredvalue;
            _innerAttribute = new RequiredAttribute();
        }

        protected override ValidationResult IsValid(object value, ValidationContext context)
        {
            var dependentValue = context.ObjectInstance.GetType().GetProperty(PropertyName).GetValue(context.ObjectInstance, null);

            if (dependentValue.ToString() == DesiredValue.ToString())
            {
                if (!_innerAttribute.IsValid(value))
                {
                    return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });
                }
            }
            return ValidationResult.Success;
        }

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ErrorMessage = ErrorMessageString,
                ValidationType = "requiredif",
            };
            rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName);
            rule.ValidationParameters["desiredvalue"] = DesiredValue is bool ? DesiredValue.ToString().ToLower() : DesiredValue;

            yield return rule;
        }
    }

And finally the javascript ( bundle it and renderit...put it in its own script file)

$.validator.unobtrusive.adapters.add('requiredif', ['dependentproperty', 'desiredvalue'], function (options) {
    options.rules['requiredif'] = options.params;
    options.messages['requiredif'] = options.message;
});

$.validator.addMethod('requiredif', function (value, element, parameters) {
    var desiredvalue = parameters.desiredvalue;
    desiredvalue = (desiredvalue == null ? '' : desiredvalue).toString();
    var controlType = $("input[id$='" + parameters.dependentproperty + "']").attr("type");
    var actualvalue = {}
    if (controlType == "checkbox" || controlType == "radio") {
        var control = $("input[id$='" + parameters.dependentproperty + "']:checked");
        actualvalue = control.val();
    } else {
        actualvalue = $("#" + parameters.dependentproperty).val();
    }
    if ($.trim(desiredvalue).toLowerCase() === $.trim(actualvalue).toLocaleLowerCase()) {
        var isValid = $.validator.methods.required.call(this, value, element, parameters);
        return isValid;
    }
    return true;
});

You need obviously the unobstrusive validate jQuery to be included as requirement

How to set css style to asp.net button?

You can use CssClass attribute and pass a value as a css class name

<asp:Button CssClass="button" Text="Submit" runat="server"></asp:Button>` 

.button
{
     //write more styles
}

Measuring function execution time in R

You can use MATLAB-style tic-toc functions, if you prefer. See this other SO question

Stopwatch function in R

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare();

I got this error in a JobService from the following code:

    BluetoothLeScanner bluetoothLeScanner = getBluetoothLeScanner();
    if (BluetoothAdapter.STATE_ON == getBluetoothAdapter().getState() && null != bluetoothLeScanner) {
        // ...
    } else {
        Logger.debug(TAG, "BluetoothAdapter isn't on so will attempting to turn on and will retry starting scanning in a few seconds");
        getBluetoothAdapter().enable();
        (new Handler()).postDelayed(new Runnable() {
            @Override
            public void run() {
                startScanningBluetooth();
            }
        }, 5000);
    }

The service crashed:

2019-11-21 11:49:45.550 729-763/? D/BluetoothManagerService: MESSAGE_ENABLE(0): mBluetooth = null

    --------- beginning of crash
2019-11-21 11:49:45.556 8629-8856/com.locuslabs.android.sdk E/AndroidRuntime: FATAL EXCEPTION: Timer-1
    Process: com.locuslabs.android.sdk, PID: 8629
    java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
        at android.os.Handler.<init>(Handler.java:203)
        at android.os.Handler.<init>(Handler.java:117)
        at com.locuslabs.sdk.ibeacon.BeaconScannerJobService.startScanningBluetoothAndBroadcastAnyBeaconsFoundAndUpdatePersistentNotification(BeaconScannerJobService.java:120)
        at com.locuslabs.sdk.ibeacon.BeaconScannerJobService.access$500(BeaconScannerJobService.java:36)
        at com.locuslabs.sdk.ibeacon.BeaconScannerJobService$2$1.run(BeaconScannerJobService.java:96)
        at java.util.TimerThread.mainLoop(Timer.java:555)
        at java.util.TimerThread.run(Timer.java:505)

So I changed from Handler to Timer as follows:

   (new Timer()).schedule(new TimerTask() {
                @Override
                public void run() {
                    startScanningBluetooth();
                }
            }, 5000);

Now the code doesn't throw the RuntimeException anymore.

How can I copy the content of a branch to a new local branch?

git branch copyOfMyBranch MyBranch

This avoids the potentially time-consuming and unnecessary act of checking out a branch. Recall that a checkout modifies the "working tree", which could take a long time if it is large or contains large files (images or videos, for example).

Why is enum class preferred over plain enum?

Because, as said in other answers, class enum are not implicitly convertible to int/bool, it also helps to avoid buggy code like:

enum MyEnum {
  Value1,
  Value2,
};
...
if (var == Value1 || Value2) // Should be "var == Value2" no error/warning

Adding a new entry to the PATH variable in ZSH

OPTION 1: Add this line to ~/.zshrc:

export "PATH=$HOME/pear/bin:$PATH"

After that you need to run source ~/.zshrc in order your changes to take affect OR close this window and open a new one

OPTION 2: execute it inside the terminal console to add this path only to the current terminal window session. When you close the window/session, it will be lost.

Angular - ui-router get previous state

I use resolve to save the current state data before moving to the new state:

angular.module('MyModule')
.config(['$stateProvider', function ($stateProvider) {
    $stateProvider
        .state('mystate', {
            templateUrl: 'mytemplate.html',
            controller: ["PreviousState", function (PreviousState) {
                if (PreviousState.Name == "mystate") {
                    // ...
                }
            }],
            resolve: {
                PreviousState: ["$state", function ($state) {
                    var currentStateData = {
                        Name: $state.current.name,
                        Params: $state.params,
                        URL: $state.href($state.current.name, $state.params)
                    };
                    return currentStateData;
                }]
            }
        });
}]);

How to get height of <div> in px dimension

Use height():

var result = $("#myDiv").height();
alert(result);

This will give you the unit-less computed height in pixels. "px" will be stripped from the result. I.e. if the height is 400px, the result will be 400, but the result will be in pixels.

If you want to do it without jQuery, you can use plain JavaScript:

var result = document.getElementById("myDiv").offsetHeight;

python pip - install from local dir

All you need to do is run

pip install /opt/mypackage

and pip will search /opt/mypackage for a setup.py, build a wheel, then install it.

The problem with using the -e flag for pip install as suggested in the comments and this answer is that this requires that the original source directory stay in place for as long as you want to use the module. It's great if you're a developer working on the source, but if you're just trying to install a package, it's the wrong choice.

Alternatively, you don't even need to download the repo from Github at all. pip supports installing directly from git repos using a variety of protocols including HTTP, HTTPS, and SSH, among others. See the docs I linked to for examples.

How to add multiple columns to pandas dataframe in one assignment?

I am not comfortable using "Index" and so on...could come up as below

df.columns
Index(['A123', 'B123'], dtype='object')

df=pd.concat([df,pd.DataFrame(columns=list('CDE'))])

df.rename(columns={
    'C':'C123',
    'D':'D123',
    'E':'E123'
},inplace=True)


df.columns
Index(['A123', 'B123', 'C123', 'D123', 'E123'], dtype='object')

Capture characters from standard input without waiting for enter to be pressed

Here's a version that doesn't shell out to the system (written and tested on macOS 10.14)

#include <unistd.h>
#include <termios.h>
#include <stdio.h>
#include <string.h>

char* getStr( char* buffer , int maxRead ) {
  int  numRead  = 0;
  char ch;

  struct termios old = {0};
  struct termios new = {0};
  if( tcgetattr( 0 , &old ) < 0 )        perror( "tcgetattr() old settings" );
  if( tcgetattr( 0 , &new ) < 0 )        perror( "tcgetaart() new settings" );
  cfmakeraw( &new );
  if( tcsetattr( 0 , TCSADRAIN , &new ) < 0 ) perror( "tcssetattr makeraw new" );

  for( int i = 0 ; i < maxRead ; i++)  {
    ch = getchar();
    switch( ch )  {
      case EOF: 
      case '\n':
      case '\r':
        goto exit_getStr;
        break;

      default:
        printf( "%1c" , ch );
        buffer[ numRead++ ] = ch;
        if( numRead >= maxRead )  {
          goto exit_getStr;
        }
        break;
    }
  }

exit_getStr:
  if( tcsetattr( 0 , TCSADRAIN , &old) < 0)   perror ("tcsetattr reset to old" );
  printf( "\n" );   
  return buffer;
}


int main( void ) 
{
  const int maxChars = 20;
  char      stringBuffer[ maxChars+1 ];
  memset(   stringBuffer , 0 , maxChars+1 ); // initialize to 0

  printf( "enter a string: ");
  getStr( stringBuffer , maxChars );
  printf( "you entered: [%s]\n" , stringBuffer );
}

How can I get a Dialog style activity window to fill the screen?

This would be helpful for someone like me. Create custom dialog style:

<style name="MyDialog" parent="Theme.AppCompat.Light.Dialog">
    <item name="windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowIsFloating">false</item>
</style>

In AndroidManifest.xml file set theme for wanted activity:

<activity
        android:name=".CustomDialog"
        ...
        android:theme="@style/MyDialog"/>

That is all, no need to call methods programaticaly.

Redirect form to different URL based on select option element

Just use a onchnage Event for select box.

<select id="selectbox" name="" onchange="javascript:location.href = this.value;">
    <option value="https://www.yahoo.com/" selected>Option1</option>
    <option value="https://www.google.co.in/">Option2</option>
    <option value="https://www.gmail.com/">Option3</option>

</select>

And if selected option to be loaded at the page load then add some javascript code

<script type="text/javascript">
    window.onload = function(){
        location.href=document.getElementById("selectbox").value;
    }       
</script>

for jQuery: Remove the onchange event from <select> tag

jQuery(function () {
    // remove the below comment in case you need chnage on document ready
    // location.href=jQuery("#selectbox").val(); 
    jQuery("#selectbox").change(function () {
        location.href = jQuery(this).val();
    })
})

Create Hyperlink in Slack

Recently it became possible (but with an odd workaround).

To do this you must first create text with the desired hyperlink in an editor that supports rich text formatting. This can be an advanced text editor, web browser, email client, web-development IDE, etc.). Then copypaste the text from the editor or rendered HTML from browser (or other). E.g. in the example below I copypasted the head of this StackOverflow page. As you may see, the hyperlink have been copied correctly and is clickable in the message (checked on Mac Desktop, browser, and iOS apps).

Message in Slack

On Mac

I was able to compose the desired link in the native Pages app as shown below. When you are done, copypaste your text into Slack app. This is the probably easiest way on Mac OS.

Link creation in Pages

On Windows

I have a strong suspicion that MS Word will do the same trick, but unfortunately I don't have an installed instance to check.

Universal

Create text in an online editor, such as Google Documents. Use Insert -> Link, modify the text and web URL, then copypaste into Slack.

enter image description here

Killing a process using Java

You can kill a (SIGTERM) a windows process that was started from Java by calling the destroy method on the Process object. You can also kill any child Processes (since Java 9).

The following code starts a batch file, waits for ten seconds then kills all sub-processes and finally kills the batch process itself.

ProcessBuilder pb = new ProcessBuilder("cmd /c my_script.bat"));
Process p = pb.start();
p.waitFor(10, TimeUnit.SECONDS);

p.descendants().forEach(ph -> {
    ph.destroy();
});

p.destroy();

How to do relative imports in Python?

Here is the solution which works for me:

I do the relative imports as from ..sub2 import mod2 and then, if I want to run mod1.py then I go to the parent directory of app and run the module using the python -m switch as python -m app.sub1.mod1.

The real reason why this problem occurs with relative imports, is that relative imports works by taking the __name__ property of the module. If the module is being directly run, then __name__ is set to __main__ and it doesn't contain any information about package structure. And, thats why python complains about the relative import in non-package error.

So, by using the -m switch you provide the package structure information to python, through which it can resolve the relative imports successfully.

I have encountered this problem many times while doing relative imports. And, after reading all the previous answers, I was still not able to figure out how to solve it, in a clean way, without needing to put boilerplate code in all files. (Though some of the comments were really helpful, thanks to @ncoghlan and @XiongChiamiov)

Hope this helps someone who is fighting with relative imports problem, because going through PEP is really not fun.

How to make lists contain only distinct element in Python?

one-liner and preserve order

list(OrderedDict.fromkeys([2,1,1,3]))

although you'll need

from collections import OrderedDict

What is a 'Closure'?

Here's a real world example of why Closures kick ass... This is straight out of my Javascript code. Let me illustrate.

Function.prototype.delay = function(ms /*[, arg...]*/) {
  var fn = this,
      args = Array.prototype.slice.call(arguments, 1);

  return window.setTimeout(function() {
      return fn.apply(fn, args);
  }, ms);
};

And here's how you would use it:

var startPlayback = function(track) {
  Player.play(track);  
};
startPlayback(someTrack);

Now imagine you want the playback to start delayed, like for example 5 seconds later after this code snippet runs. Well that's easy with delay and it's closure:

startPlayback.delay(5000, someTrack);
// Keep going, do other things

When you call delay with 5000ms, the first snippet runs, and stores the passed in arguments in it's closure. Then 5 seconds later, when the setTimeout callback happens, the closure still maintains those variables, so it can call the original function with the original parameters.
This is a type of currying, or function decoration.

Without closures, you would have to somehow maintain those variables state outside the function, thus littering code outside the function with something that logically belongs inside it. Using closures can greatly improve the quality and readability of your code.

iOS 6 apps - how to deal with iPhone 5 screen size?

You need to add a 640x1136 pixels PNG image ([email protected]) as a 4 inch default splash image of your project, and it will use extra spaces (without efforts on simple table based applications, games will require more efforts).

I've created a small UIDevice category in order to deal with all screen resolutions. You can get it here, but the code is as follows:

File UIDevice+Resolutions.h:

enum {
    UIDeviceResolution_Unknown           = 0,
    UIDeviceResolution_iPhoneStandard    = 1,    // iPhone 1,3,3GS Standard Display  (320x480px)
    UIDeviceResolution_iPhoneRetina4    = 2,    // iPhone 4,4S Retina Display 3.5"  (640x960px)
    UIDeviceResolution_iPhoneRetina5     = 3,    // iPhone 5 Retina Display 4"       (640x1136px)
    UIDeviceResolution_iPadStandard      = 4,    // iPad 1,2,mini Standard Display   (1024x768px)
    UIDeviceResolution_iPadRetina        = 5     // iPad 3 Retina Display            (2048x1536px)
}; typedef NSUInteger UIDeviceResolution;

@interface UIDevice (Resolutions)

- (UIDeviceResolution)resolution;

NSString *NSStringFromResolution(UIDeviceResolution resolution);

@end

File UIDevice+Resolutions.m:

#import "UIDevice+Resolutions.h"

@implementation UIDevice (Resolutions)

- (UIDeviceResolution)resolution
{
    UIDeviceResolution resolution = UIDeviceResolution_Unknown;
    UIScreen *mainScreen = [UIScreen mainScreen];
    CGFloat scale = ([mainScreen respondsToSelector:@selector(scale)] ? mainScreen.scale : 1.0f);
    CGFloat pixelHeight = (CGRectGetHeight(mainScreen.bounds) * scale);

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone){
        if (scale == 2.0f) {
            if (pixelHeight == 960.0f)
                resolution = UIDeviceResolution_iPhoneRetina4;
            else if (pixelHeight == 1136.0f)
                resolution = UIDeviceResolution_iPhoneRetina5;

        } else if (scale == 1.0f && pixelHeight == 480.0f)
            resolution = UIDeviceResolution_iPhoneStandard;

    } else {
        if (scale == 2.0f && pixelHeight == 2048.0f) {
            resolution = UIDeviceResolution_iPadRetina;

        } else if (scale == 1.0f && pixelHeight == 1024.0f) {
            resolution = UIDeviceResolution_iPadStandard;
        }
    }

    return resolution;
 }

 @end

This is how you need to use this code.

1) Add the above UIDevice+Resolutions.h & UIDevice+Resolutions.m files to your project

2) Add the line #import "UIDevice+Resolutions.h" to your ViewController.m

3) Add this code to check what versions of device you are dealing with

int valueDevice = [[UIDevice currentDevice] resolution];

    NSLog(@"valueDevice: %d ...", valueDevice);

    if (valueDevice == 0)
    {
        //unknow device - you got me!
    }
    else if (valueDevice == 1)
    {
        //standard iphone 3GS and lower
    }
    else if (valueDevice == 2)
    {
        //iphone 4 & 4S
    }
    else if (valueDevice == 3)
    {
        //iphone 5
    }
    else if (valueDevice == 4)
    {
        //ipad 2
    }
    else if (valueDevice == 5)
    {
        //ipad 3 - retina display
    }

Use IntelliJ to generate class diagram

Try Ctrl+Alt+U

Also check if the UML plugin is activated (settings -> plugin, settings can be opened by Ctrl+Alt+S

Find a value in DataTable

A DataTable or DataSet object will have a Select Method that will return a DataRow array of results based on the query passed in as it's parameter.

Looking at your requirement your filterexpression will have to be somewhat general to make this work.

myDataTable.Select("columnName1 like '%" + value + "%'");

Converting an integer to a string in PHP

You can simply use the following:

$intVal = 5;
$strVal = trim($intVal);

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

Two possible answers:

1- You did not include spring-beans and spring-context jars in your lib. If you are using maven (which will help a lot) those two lines will be enough

<dependency>
 <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
   <version>3.1.0.RELEASE</version>
</dependency>
<dependency>
 <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
   <version>3.1.0.RELEASE</version>
</dependency>

2- The necessary jars are in your classpath but are not deployed on tomcat.

Create a List that contain each Line of a File

f.readlines() returns a list that contains each line as an item in the list

if you want eachline to be split(",") you can use list comprehensions

[ list.split(",") for line in file ]

Does --disable-web-security Work In Chrome Anymore?

The new tag for recent Chrome and Chromium browsers is :

--disable-web-security --user-data-dir=c:\my\data

How to set the width of a RaisedButton in Flutter?

As said in documentation here

Raised buttons have a minimum size of 88.0 by 36.0 which can be overidden with ButtonTheme.

You can do it like that

ButtonTheme(
  minWidth: 200.0,
  height: 100.0,
  child: RaisedButton(
    onPressed: () {},
    child: Text("test"),
  ),
);

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

Strip off URL parameter with PHP

This is to complement Marc B's answer with an example, while it may look quite long, it's a safe way to remove a parameter. In this example we remove page_number

<?php
$x = 'http://url.com/search/?location=london&page_number=1';

$parsed = parse_url($x);
$query = $parsed['query'];

parse_str($query, $params);

unset($params['page_number']);
$string = http_build_query($params);
var_dump($string);

batch file - counting number of files in folder and storing in a variable

FOR /f "delims=" %%i IN ('attrib.exe ./*.* ^| find /v "File not found - " ^| find /c /v ""') DO SET myVar=%%i
ECHO %myVar%

This is based on the (much) earlier post that points out that the count would be wrong for an empty directory if you use DIR rather than attrib.exe.

For anyone else who got stuck on the syntax for putting the command in a FOR loop, enclose the command in single quotes (assuming it doesn't contain them) and escape pipes with ^.

Algorithm to detect overlapping periods

Simple check to see if two time periods overlap:

bool overlap = a.start < b.end && b.start < a.end;

or in your code:

bool overlap = tStartA < tEndB && tStartB < tEndA;

(Use <= instead of < if you change your mind about wanting to say that two periods that just touch each other overlap.)

Is a view faster than a simple query?

My understanding is that a while back, a view would be faster because SQL Server could store an execution plan and then just use it instead of trying to figure one out on the fly. I think the performance gains nowadays is probably not as great as it once was, but I would have to guess there would be some marginal improvement to use the view.

How to convert FileInputStream to InputStream?

FileInputStream is an inputStream.

FileInputStream fis = new FileInputStream("c://filename");
InputStream is = fis;
fis.close();  
return is;

Of course, this will not do what you want it to do; the stream you return has already been closed. Just return the FileInputStream and be done with it. The calling code should close it.

Android Emulator: Installation error: INSTALL_FAILED_VERSION_DOWNGRADE

It may be a problem with the Google Play Services dependencies rather than an actual app version issue.

Sometimes, it is NOT the case that:

a) there is an existing version of the app installed, newer or not b) there is an existing version of the app installed on another user account on the device

So the error message is just bogus.

In my case, I had:

implementation 'com.google.android.gms:play-services-maps:16.0.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.google.android.gms:play-services-gcm:16.0.0'

But when I tried

implementation 'com.google.android.gms:play-services-maps:17.0.0'
implementation 'com.google.android.gms:play-services-location:17.0.0'
implementation 'com.google.android.gms:play-services-gcm:17.0.0'

I got androidX related errors, as I had not yet upgraded to androidX and was not ready to do so. I found that using the latest 16.x.y versions work and I don't get the error message any more. Furthermore, I could wait till later when I am ready, to upgrade to androidX.

implementation 'com.google.android.gms:play-services-maps:16.+'
implementation 'com.google.android.gms:play-services-location:16.+'
implementation 'com.google.android.gms:play-services-gcm:16.+'

Function pointer as parameter

You need to declare disconnectFunc as a function pointer, not a void pointer. You also need to call it as a function (with parentheses), and no "*" is needed.

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

Right click the project in the Explorer: Build Path -> Order and Export -> Select JRE System Library [jdk] and click Bottom button.

How to update a menu item shown in the ActionBar?

For clarity, I thought that a direct example of grabbing onto a resource can be shown from the following that I think contributes to the response for this question with a quick direct example.

private MenuItem menuItem_;

@Override
public boolean onCreateOptionsMenu(Menu menuF) 
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_layout, menuF);
    menuItem_ = menuF.findItem(R.id.menu_item_identifier);
    return true;
}

In this case you hold onto a MenuItem reference at the beginning and then change the state of it (for icon state changes for example) at a later given point in time.

Passing arguments to require (when loading module)

Yes. In your login module, just export a single function that takes the db as its argument. For example:

module.exports = function(db) {
  ...
};

Using OR in SQLAlchemy

This has been really helpful. Here is my implementation for any given table:

def sql_replace(self, tableobject, dictargs):

    #missing check of table object is valid
    primarykeys = [key.name for key in inspect(tableobject).primary_key]

    filterargs = []
    for primkeys in primarykeys:
        if dictargs[primkeys] is not None:
            filterargs.append(getattr(db.RT_eqmtvsdata, primkeys) == dictargs[primkeys])
        else:
            return

    query = select([db.RT_eqmtvsdata]).where(and_(*filterargs))

    if self.r_ExecuteAndErrorChk2(query)[primarykeys[0]] is not None:
        # update
        filter = and_(*filterargs)
        query = tableobject.__table__.update().values(dictargs).where(filter)
        return self.w_ExecuteAndErrorChk2(query)

    else:
        query = tableobject.__table__.insert().values(dictargs)
        return self.w_ExecuteAndErrorChk2(query)

# example usage
inrow = {'eqmtvs_id': eqmtvsid, 'datetime': dtime, 'param_id': paramid}

self.sql_replace(tableobject=db.RT_eqmtvsdata, dictargs=inrow)

How to align an image dead center with bootstrap

You could change the CSS of the previous solution as below:

.container, .row { text-align: center; }

This should center all the elements in the parent div as well.

How to clear a textbox once a button is clicked in WPF?

Give your textbox a name and then use TextBoxName.Text = String.Empty;

How to get different colored lines for different plots in a single figure?

Matplotlib does this by default.

E.g.:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)
plt.show()

Basic plot demonstrating color cycling

And, as you may already know, you can easily add a legend:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)

plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x'], loc='upper left')

plt.show()

Basic plot with legend

If you want to control the colors that will be cycled through:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

plt.gca().set_color_cycle(['red', 'green', 'blue', 'yellow'])

plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)

plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x'], loc='upper left')

plt.show()

Plot showing control over default color cycling

If you're unfamiliar with matplotlib, the tutorial is a good place to start.

Edit:

First off, if you have a lot (>5) of things you want to plot on one figure, either:

  1. Put them on different plots (consider using a few subplots on one figure), or
  2. Use something other than color (i.e. marker styles or line thickness) to distinguish between them.

Otherwise, you're going to wind up with a very messy plot! Be nice to who ever is going to read whatever you're doing and don't try to cram 15 different things onto one figure!!

Beyond that, many people are colorblind to varying degrees, and distinguishing between numerous subtly different colors is difficult for more people than you may realize.

That having been said, if you really want to put 20 lines on one axis with 20 relatively distinct colors, here's one way to do it:

import matplotlib.pyplot as plt
import numpy as np

num_plots = 20

# Have a look at the colormaps here and decide which one you'd like:
# http://matplotlib.org/1.2.1/examples/pylab_examples/show_colormaps.html
colormap = plt.cm.gist_ncar
plt.gca().set_prop_cycle(plt.cycler('color', plt.cm.jet(np.linspace(0, 1, num_plots))))

# Plot several different functions...
x = np.arange(10)
labels = []
for i in range(1, num_plots + 1):
    plt.plot(x, i * x + 5 * i)
    labels.append(r'$y = %ix + %i$' % (i, 5*i))

# I'm basically just demonstrating several different legend options here...
plt.legend(labels, ncol=4, loc='upper center', 
           bbox_to_anchor=[0.5, 1.1], 
           columnspacing=1.0, labelspacing=0.0,
           handletextpad=0.0, handlelength=1.5,
           fancybox=True, shadow=True)

plt.show()

Unique colors for 20 lines based on a given colormap

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

If you want the structure of a particular data table(dataTable1) with column headers (without data) into another data table(dataTable2), you can follow the below code:

        DataTable dataTable2 = dataTable1.Clone();
        dataTable2.Clear();

Now you can fill dataTable2 according to your condition. :)

Javascript Audio Play on click

Try the below code snippet

<!doctype html>
<html>
  <head>
    <title>Audio</title>
  </head>
  <body>

    <script>
      function play() {
        var audio = document.getElementById("audio");
        audio.play();
      }
    </script>

    <input type="button" value="PLAY" onclick="play()">
    <audio id="audio" src="http://dev.interactive-creation-works.net/1/1.ogg"></audio>

  </body>
</html>

Python "SyntaxError: Non-ASCII character '\xe2' in file"

I had this exact issue running the simple .py code below:

import sys
print 'version is:', sys.version

DSM's code above provided the following:

1 'print \xe2\x80\x98version is\xe2\x80\x99, sys.version'

So the issue was that my text editor used SMART QUOTES, as John Y suggested. After changing the text editor settings and re-opening/saving the file, it works just fine.

Read a Csv file with powershell and capture corresponding data

Old topic, but never clearly answered. I've been working on similar as well, and found the solution:

The pipe (|) in this code sample from Austin isn't the delimiter, but to pipe the ForEach-Object, so if you want to use it as delimiter, you need to do this:

Import-Csv H:\Programs\scripts\SomeText.csv -delimiter "|" |`
ForEach-Object {
    $Name += $_.Name
    $Phone += $_."Phone Number"
}

Spent a good 15 minutes on this myself before I understood what was going on. Hope the answer helps the next person reading this avoid the wasted minutes! (Sorry for expanding on your comment Austin)

Android check null or empty string in Android

if you check null or empty String so you can try this

if (createReminderRequest.getDate() == null && createReminderRequest.getDate().trim().equals("")){
    DialogUtility.showToast(this, ProjectUtils.getString(R.string.please_select_date_n_time));
}

Where is Maven Installed on Ubuntu

I would like to add that .m2 folder a lot of people say it is in your home folder. It is right. But if use maven from ready to go IDE like Spring STS then your .m2 folder is placed in root folder

To access root folder you need to switch to super user account

sudo su

Go to root folder

cd root/

You will find it by

cd -all

Cannot kill Python script with Ctrl-C

An improved version of @Thomas K's answer:

  • Defining an assistant function is_any_thread_alive() according to this gist, which can terminates the main() automatically.

Example codes:

import threading

def job1():
    ...

def job2():
    ...

def is_any_thread_alive(threads):
    return True in [t.is_alive() for t in threads]

if __name__ == "__main__":
    ...
    t1 = threading.Thread(target=job1,daemon=True)
    t2 = threading.Thread(target=job2,daemon=True)
    t1.start()
    t2.start()

    while is_any_thread_alive([t1,t2]):
        time.sleep(0)

Java array assignment (multiple values)

This should work, but is slower and feels wrong: System.arraycopy(new float[]{...}, 0, values, 0, 3);

Border length smaller than div width?

I just accomplished the opposite of this using :after and ::after because I needed to make my bottom border exactly 1.3rem wider:

My element got super deformed when I used :before and :after at the same time because the elements are horizontally aligned with display: flex, flex-direction: row and align-items: center.

You could use this for making something wider or narrower, or probably any mathematical dimension mods:

a.nav_link-active {
  color: $e1-red;
  margin-top: 3.7rem;
}
a.nav_link-active:visited {
  color: $e1-red;
}
a.nav_link-active:after {
  content: '';
  margin-top: 3.3rem;      // margin and height should
  height: 0.4rem;          // add up to active link margin
  background: $e1-red;
  margin-left: -$nav-spacer-margin;
  display: block;
}
a.nav_link-active::after {
  content: '';
  margin-top: 3.3rem;      // margin and height should
  height: 0.4rem;          // add up to active link margin
  background: $e1-red;
  margin-right: -$nav-spacer-margin;
  display: block;
}

Sorry, this is SCSS, just multiply the numbers by 10 and change the variables with some normal values.

How to use Selenium with Python?

There are a lot of sources for selenium - here is good one for simple use Selenium, and here is a example snippet too Selenium Examples

You can find a lot of good sources to use selenium, it's not too hard to get it set up and start using it.

MySql difference between two timestamps in days?

I know is quite old, but I'll say just for the sake of it - I was looking for the same problem and got here, but I needed the difference in days.

I used SELECT (UNIX_TIMESTAMP(DATE1) - UNIX_TIMESTAMP(DATE2))/60/60/24 Unix_timestamp returns the difference in seconds, and then I just divide into minutes(seconds/60), hours(minutes/60), days(hours/24).

What are the integrity and crossorigin attributes?

Both attributes have been added to Bootstrap CDN to implement Subresource Integrity.

Subresource Integrity defines a mechanism by which user agents may verify that a fetched resource has been delivered without unexpected manipulation Reference

Integrity attribute is to allow the browser to check the file source to ensure that the code is never loaded if the source has been manipulated.

Crossorigin attribute is present when a request is loaded using 'CORS' which is now a requirement of SRI checking when not loaded from the 'same-origin'. More info on crossorigin

More detail on Bootstrap CDNs implementation

Faster way to zero memory than with memset?

memset is generally designed to be very very fast general-purpose setting/zeroing code. It handles all cases with different sizes and alignments, which affect the kinds of instructions you can use to do your work. Depending on what system you're on (and what vendor your stdlib comes from), the underlying implementation might be in assembler specific to that architecture to take advantage of whatever its native properties are. It might also have internal special cases to handle the case of zeroing (versus setting some other value).

That said, if you have very specific, very performance critical memory zeroing to do, it's certainly possible that you could beat a specific memset implementation by doing it yourself. memset and its friends in the standard library are always fun targets for one-upmanship programming. :)

Apache redirect to another port

You need 2 things:

  1. Add a ServerAlias www.mydomain.com to your config
  2. change your proxypass to ProxyPassMatch ^(.*)$ http://localhost:8080/example$1, to possibly keep mod_dir and trailing slashes from interferring.

Specifying Style and Weight for Google Fonts

Here's the issue: You can't specify font weights that don't exist in the font set from Google. Click on the SEE SPECIMEN link below the font, then scroll down to the STYLES section. There you'll see each of the "styles" available for that particular font. Sadly Google doesn't list the CSS font weights for each style. Here's how the names map to CSS font weight numbers:

Thin            100     
Extra Light     200
Light           300
Regular         400
Medium          500
Semi-Bold       600
Bold            700
Extra-Bold      800
Black           900

Note that very few fonts come in all 9 weights.

How to update ruby on linux (ubuntu)?

If you are like me using ubuntu 10.10 & cant find the lastest version which is now

  • ruby1.9.3

this is where you can get it http://www.ubuntuupdates.org/package/brightbox_ruby_ng_experimental/maverick/main/base/ruby1.9.3

or download the *.deb file :)

& remember that it wont alter you old version of ruby

CSS3 gradient background set on body doesn't stretch but instead repeats?

Regarding a previous answer, setting html and body to height: 100% doesn't seem to work if the content needs to scroll. Adding fixed to the background seems to fix that - no need for height: 100%;

E.g.:

_x000D_
_x000D_
body {_x000D_
  background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#cbccc8)) fixed;_x000D_
}
_x000D_
_x000D_
_x000D_

phonegap open link in browser

If you happen to have jQuery around, you can intercept the click on the link like this:

$(document).on('click', 'a', function (event) {
    event.preventDefault();
    window.open($(this).attr('href'), '_system');
    return false;
});

This way you don't have to modify the links in the html, which can save a lot of time. I have set this up using a delegate, that's why you see it being tied to the document object, with the 'a' tag as the second argument. This way all 'a' tags will be handled, regardless of when they are added.

Ofcourse you still have to install the InAppBrowser plug-in:

cordova plugin add org.apache.cordova.inappbrowser

How to compare different branches in Visual Studio Code

If you just want to view the changes to a particular file between the working copy and a particular commit using GitLens, the currently accepted answer can make it difficult to find the file you're interested in if many files have changed between the versions.

Instead, go to the file explorer in the side bar and right click on the file, go to Open Changes > Open Changes with Revision... (or Open Changes with Branch or Tag...).

How to display gpg key details without importing it?

I seem to be able to get along with simply:

$gpg <path_to_file>

Which outputs like this:

$ gpg /tmp/keys/something.asc 
  pub  1024D/560C6C26 2014-11-26 Something <[email protected]>
  sub  2048g/0C1ACCA6 2014-11-26

The op didn't specify in particular what key info is relevant. This output is all I care about.

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

Just Go to

iOS Simulator -> Hardware -> Keyboard -> Uncheck the Connect Hardware Keyboard Option.

This will fix the issue.

Your MAC keyboard will not work after performing the above step, You have to use simulator keyboard.

Loading and parsing a JSON file with multiple JSON objects

You have a JSON Lines format text file. You need to parse your file line by line:

import json

data = []
with open('file') as f:
    for line in f:
        data.append(json.loads(line))

Each line contains valid JSON, but as a whole, it is not a valid JSON value as there is no top-level list or object definition.

Note that because the file contains JSON per line, you are saved the headaches of trying to parse it all in one go or to figure out a streaming JSON parser. You can now opt to process each line separately before moving on to the next, saving memory in the process. You probably don't want to append each result to one list and then process everything if your file is really big.

If you have a file containing individual JSON objects with delimiters in-between, use How do I use the 'json' module to read in one JSON object at a time? to parse out individual objects using a buffered method.

What is the equivalent of Select Case in Access SQL?

You could do below:

select
iif ( OpeningBalance>=0 And OpeningBalance<=500 , 20, 

                  iif ( OpeningBalance>=5001 And OpeningBalance<=10000 , 30, 

                       iif ( OpeningBalance>=10001 And OpeningBalance<=20000 , 40, 

50 ) ) ) as commission
from table

How to parse JSON response from Alamofire API in Swift?

swift 3

pod 'Alamofire', '~> 4.4'
pod 'SwiftyJSON'

File json format:
{
    "codeAd": {
        "dateExpire": "2017/12/11",
        "codeRemoveAd":"1231243134"
        }
}

import Alamofire
import SwiftyJSON
    private func downloadJson() {
        Alamofire.request("https://yourlinkdownloadjson/abc").responseJSON { response in
            debugPrint(response)

            if let json = response.data {
                let data = JSON(data: json)
                print("data\(data["codeAd"]["dateExpire"])")
                print("data\(data["codeAd"]["codeRemoveAd"])")
            }
        }
    }

Is it .yaml or .yml?

After reading a bunch of people's comments online about this, my first reaction was that this is basically one of those really unimportant debates. However, my initial interest was to find out the right format so I could be consistent with my file naming practice.

Long story short, the creator of YAML are saying .yaml, but personally I keep doing .yml. That just makes more sense to me. So I went on the journey to find affirmation and soon enough, I realise that docker uses .yml everywhere. I've been writing docker-compose.yml files all this time, while you keep seeing in kubernetes' docs kubectl apply -f *.yaml...

So, in conclusion, both formats are obviously accepted and if you are on the other end, (ie: writing systems that receive a YAML file as input) you should allow for both. That seems like another snake case versus camel case thingy...

Swift days between two NSDates

Nice handy one liner :

extension Date {
  var daysFromNow: Int {
    return Calendar.current.dateComponents([.day], from: Date(), to: self).day!
  }
}

MySQL: Insert record if not exists in table

I'm not actually suggesting that you do this, as the UNIQUE index as suggested by Piskvor and others is a far better way to do it, but you can actually do what you were attempting:

CREATE TABLE `table_listnames` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  `address` varchar(255) NOT NULL,
  `tele` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB;

Insert a record:

INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Rupert', 'Somewhere', '022') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM table_listnames WHERE name = 'Rupert'
) LIMIT 1;

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM `table_listnames`;

+----+--------+-----------+------+
| id | name   | address   | tele |
+----+--------+-----------+------+
|  1 | Rupert | Somewhere | 022  |
+----+--------+-----------+------+

Try to insert the same record again:

INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Rupert', 'Somewhere', '022') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM table_listnames WHERE name = 'Rupert'
) LIMIT 1;

Query OK, 0 rows affected (0.00 sec)
Records: 0  Duplicates: 0  Warnings: 0

+----+--------+-----------+------+
| id | name   | address   | tele |
+----+--------+-----------+------+
|  1 | Rupert | Somewhere | 022  |
+----+--------+-----------+------+

Insert a different record:

INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'John', 'Doe', '022') AS tmp
WHERE NOT EXISTS (
    SELECT name FROM table_listnames WHERE name = 'John'
) LIMIT 1;

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM `table_listnames`;

+----+--------+-----------+------+
| id | name   | address   | tele |
+----+--------+-----------+------+
|  1 | Rupert | Somewhere | 022  |
|  2 | John   | Doe       | 022  |
+----+--------+-----------+------+

And so on...


Update:

To prevent #1060 - Duplicate column name error in case two values may equal, you must name the columns of the inner SELECT:

INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Unknown' AS name, 'Unknown' AS address, '022' AS tele) AS tmp
WHERE NOT EXISTS (
    SELECT name FROM table_listnames WHERE name = 'Rupert'
) LIMIT 1;

Query OK, 1 row affected (0.00 sec)
Records: 1  Duplicates: 0  Warnings: 0

SELECT * FROM `table_listnames`;

+----+---------+-----------+------+
| id | name    | address   | tele |
+----+---------+-----------+------+
|  1 | Rupert  | Somewhere | 022  |
|  2 | John    | Doe       | 022  |
|  3 | Unknown | Unknown   | 022  |
+----+---------+-----------+------+

Select parent element of known element in Selenium

Take a look at the possible XPath axes, you are probably looking for parent. Depending on how you are finding the first element, you could just adjust the xpath for that.

Alternatively you can try the double-dot syntax, .. which selects the parent of the current node.

Apply Calibri (Body) font to text

There is no such font as “Calibri (Body)”. You probably saw this string in Microsoft Word font selection menu, but it’s not a font name (see e.g. the explanation Font: +body (in W07)).

So use just font-family: Calibri or, better, font-family: Calibri, sans-serif. (There is no adequate backup font for Calibri, but the odds are that when Calibri is not available, the browser’s default sans-serif font suits your design better than the browser’s default font, which is most often a serif font.)

HttpURLConnection timeout settings

HttpURLConnection has a setConnectTimeout method.

Just set the timeout to 5000 milliseconds, and then catch java.net.SocketTimeoutException

Your code should look something like this:


try {
   HttpURLConnection.setFollowRedirects(false);
   HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
   con.setRequestMethod("HEAD");

   con.setConnectTimeout(5000); //set timeout to 5 seconds

   return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
   return false;
} catch (java.io.IOException e) {
   return false;
}


How to create a backup of a single table in a postgres database?

If you are on Ubuntu,

  1. Login to your postgres user sudo su postgres
  2. pg_dump -d <database_name> -t <table_name> > file.sql

Make sure that you are executing the command where the postgres user have write permissions (Example: /tmp)

Edit

If you want to dump the .sql in another computer, you may need to consider skipping the owner information getting saved into the .sql file.

You can use pg_dump --no-owner -d <database_name> -t <table_name> > file.sql

How to grep a text file which contains some binary data?

As James Selvakumar already said, grep -a does the trick. -a or --text forces Grep to handle the inputstream as text. See Manpage http://unixhelp.ed.ac.uk/CGI/man-cgi?grep

try

cat test.log | grep -a somestring

iOS Launching Settings -> Restrictions URL Scheme

Solution for iOS10. Works fine.

NSURL *URL = [NSURL URLWithString:@"App-prefs:root=TWITTER"];
[[UIApplication sharedApplication] openURL:URL options:@{} completionHandler:nil];

Simulator or Emulator? What is the difference?

It's a difference in focus. Emulators1 focus on recreating the behavior of a system, with no regard for how the system functions internally. Simulators2 focus on modeling the components of a system. You use an emulator when you care mostly about what a system does, and a simulator when you care about how it does it.

As for their general English meanings, emulation is "the endeavor to equal or to excel another in qualities or actions", while simulation is "to model, replicate, duplicate the behavior, appearance or properties of". Not much difference. Emulation comes from æmulus, "striving, rivaling," and is related to "imitate" and "image," which suggests a surface-lever resemblance. "Simulation" comes from similis "like", as does the word "similar," which perhaps suggests a deeper congruence.

References:

  1. Wikipedia: Emulator
  2. Wikipedia: Computer Simulation
  3. Wiktionary: emulation
  4. Wiktionary: simulation
  5. Etymology Online: emulation
  6. Etymology Online: simulation