Programs & Examples On #Temporaries

How to make a input field readonly with JavaScript?

document.getElementById("").readOnly = true

Sorting A ListView By Column

My solution is a class to sort listView items when you click on column header.

You can specify the type of each column.

listView.ListViewItemSorter = new ListViewColumnSorter();
listView.ListViewItemSorter.ColumnsTypeComparer.Add(0, DateTime);
listView.ListViewItemSorter.ColumnsTypeComparer.Add(1, int);

That's it !

The C# class :

using System.Collections;
using System.Collections.Generic;
using EDV;

namespace System.Windows.Forms
{
    /// <summary>
    /// Cette classe est une implémentation de l'interface 'IComparer' pour le tri des items de ListView. Adapté de http://support.microsoft.com/kb/319401.
    /// </summary>
    /// <remarks>Intégré par EDVariables.</remarks>
    public class ListViewColumnSorter : IComparer
    {
        /// <summary>
        /// Spécifie la colonne à trier
        /// </summary>
        private int ColumnToSort;
        /// <summary>
        /// Spécifie l'ordre de tri (en d'autres termes 'Croissant').
        /// </summary>
        private SortOrder OrderOfSort;
        /// <summary>
        /// Objet de comparaison ne respectant pas les majuscules et minuscules
        /// </summary>
        private CaseInsensitiveComparer ObjectCompare;

        /// <summary>
        /// Constructeur de classe.  Initialise la colonne sur '0' et aucun tri
        /// </summary>
        public ListViewColumnSorter()
            : this(0, SortOrder.None) { }

        /// <summary>
        /// Constructeur de classe.  Initializes various elements
        /// <param name="columnToSort">Spécifie la colonne à trier</param>
        /// <param name="orderOfSort">Spécifie l'ordre de tri</param>
        /// </summary>
        public ListViewColumnSorter(int columnToSort, SortOrder orderOfSort)
        {
            // Initialise la colonne
            ColumnToSort = columnToSort;

            // Initialise l'ordre de tri
            OrderOfSort = orderOfSort;

            // Initialise l'objet CaseInsensitiveComparer
            ObjectCompare = new CaseInsensitiveComparer();

            // Dictionnaire de comparateurs
            ColumnsComparer = new Dictionary<int, IComparer>();
            ColumnsTypeComparer = new Dictionary<int, Type>();

        }

        /// <summary>
        /// Cette méthode est héritée de l'interface IComparer.  Il compare les deux objets passés en effectuant une comparaison 
        ///qui ne tient pas compte des majuscules et des minuscules.
        /// <br/>Si le comparateur n'existe pas dans ColumnsComparer, CaseInsensitiveComparer est utilisé.
        /// </summary>
        /// <param name="x">Premier objet à comparer</param>
        /// <param name="x">Deuxième objet à comparer</param>
        /// <returns>Le résultat de la comparaison. "0" si équivalent, négatif si 'x' est inférieur à 'y' 
        ///et positif si 'x' est supérieur à 'y'</returns>
        public int Compare(object x, object y)
        {
            int compareResult;
            ListViewItem listviewX, listviewY;

            // Envoit les objets à comparer aux objets ListViewItem
            listviewX = (ListViewItem)x;
            listviewY = (ListViewItem)y;

            if (listviewX.SubItems.Count < ColumnToSort + 1 || listviewY.SubItems.Count < ColumnToSort + 1)
                return 0;

            IComparer objectComparer = null;
            Type comparableType = null;
            if (ColumnsComparer == null || !ColumnsComparer.TryGetValue(ColumnToSort, out objectComparer))
                if (ColumnsTypeComparer == null || !ColumnsTypeComparer.TryGetValue(ColumnToSort, out comparableType))
                    objectComparer = ObjectCompare;

            // Compare les deux éléments
            if (comparableType != null) {
                //Conversion du type
                object valueX = listviewX.SubItems[ColumnToSort].Text;
                object valueY = listviewY.SubItems[ColumnToSort].Text;
                if (!edvTools.TryParse(ref valueX, comparableType) || !edvTools.TryParse(ref valueY, comparableType))
                    return 0;
                compareResult = (valueX as IComparable).CompareTo(valueY);
            }
            else
                compareResult = objectComparer.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);

            // Calcule la valeur correcte d'après la comparaison d'objets
            if (OrderOfSort == SortOrder.Ascending) {
                // Le tri croissant est sélectionné, renvoie des résultats normaux de comparaison
                return compareResult;
            }
            else if (OrderOfSort == SortOrder.Descending) {
                // Le tri décroissant est sélectionné, renvoie des résultats négatifs de comparaison
                return (-compareResult);
            }
            else {
                // Renvoie '0' pour indiquer qu'ils sont égaux
                return 0;
            }
        }

        /// <summary>
        /// Obtient ou définit le numéro de la colonne à laquelle appliquer l'opération de tri (par défaut sur '0').
        /// </summary>
        public int SortColumn
        {
            set
            {
                ColumnToSort = value;
            }
            get
            {
                return ColumnToSort;
            }
        }

        /// <summary>
        /// Obtient ou définit l'ordre de tri à appliquer (par exemple, 'croissant' ou 'décroissant').
        /// </summary>
        public SortOrder Order
        {
            set
            {
                OrderOfSort = value;
            }
            get
            {
                return OrderOfSort;
            }
        }

        /// <summary>
        /// Dictionnaire de comparateurs par colonne.
        /// <br/>Pendant le tri, si le comparateur n'existe pas dans ColumnsComparer, CaseInsensitiveComparer est utilisé.
        /// </summary>
        public Dictionary<int, IComparer> ColumnsComparer { get; set; }

        /// <summary>
        /// Dictionnaire de comparateurs par colonne.
        /// <br/>Pendant le tri, si le comparateur n'existe pas dans ColumnsTypeComparer, CaseInsensitiveComparer est utilisé.
        /// </summary>
        public Dictionary<int, Type> ColumnsTypeComparer { get; set; }
    }
}

Initializing a ListView :

    <var>Visual.WIN.ctrlListView.OnShown</var>  : 
    eventSender.Columns.Clear();
    eventSender.SmallImageList = edvWinForm.ImageList16;
    eventSender.ListViewItemSorter = new ListViewColumnSorter();
    var col = eventSender.Columns.Add("Répertoire");
    col.Width = 160;
    col.ImageKey = "Domain";
    col = eventSender.Columns.Add("Fichier");
    col.Width = 180;
    col.ImageKey = "File";
    col = eventSender.Columns.Add("Date");
    col.Width = 120;
    col.ImageKey = "DateTime";
    eventSender.ListViewItemSorter.ColumnsTypeComparer.Add(col.Index, DateTime);
    col = eventSender.Columns.Add("Position");
    col.TextAlign = HorizontalAlignment.Right;
    col.Width = 80;
    col.ImageKey = "Num";
    eventSender.ListViewItemSorter.ColumnsTypeComparer.Add(col.Index, Int32);

Fill a ListView :

<var>Visual.WIN.cmdSearch.OnClick</var>  : 
//non récursif et sans fonction
    ..ctrlListView:Items.Clear();
    ..ctrlListView:Sorting = SortOrder.None;
    var group = ..ctrlListView:Groups.Add(DateTime.Now.ToString()
                , Path.Combine(..cboDir:Text, ..ctrlPattern1:Text) + " contenant " + ..ctrlSearch1:Text);
    var perf =  Environment.TickCount;

    var files = new DirectoryInfo(..cboDir:Text).GetFiles(..ctrlPattern1:Text)
    var search = ..ctrlSearch1:Text;
    var ignoreCase = ..Search.IgnoreCase;
    //var result = new StringBuilder();
    var dirLength : int = ..cboDir:Text.Length;
    var position : int;
    var added : int = 0;
    for(var i : int = 0; i &lt; files.Length; i++){
        var file = files[i];
        if(search == ""
        || (position = File.ReadAllText(file.FullName).IndexOf(String(search)
                            , StringComparison(ignoreCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture))) &gt; =0) {

        //  result.AppendLine(file.FullName.Substring(dirLength) + "\tPos : " + pkvFile.Value);
            var item = ..ctrlListView:Items.Add(file.FullName.Substring(dirLength));
            item.SubItems.Add(file.Name);
            item.SubItems.Add(File.GetLastWriteTime(file.FullName).ToString());
            item.SubItems.Add(position.ToString("# ### ##0"));
            item.Group = group;
            ++added;
        }
    }
    group.Header += " : " + added + "/" + files.Length + " fichier(s)"
                + "  en " + (Environment.TickCount - perf).ToString("# ##0 msec");

On ListView column click :

<var>Visual.WIN.ctrlListView.OnColumnClick</var>  : 
// Déterminer si la colonne sélectionnée est déjà la colonne triée.
var sorter = eventSender.ListViewItemSorter;
if ( eventArgs.Column == sorter .SortColumn )
{
    // Inverser le sens de tri en cours pour cette colonne.
    if (sorter.Order == SortOrder.Ascending)
    {
        sorter.Order = SortOrder.Descending;
    }
    else
    {
        sorter.Order = SortOrder.Ascending;
    }
}
else
{
    // Définir le numéro de colonne à trier ; par défaut sur croissant.
    sorter.SortColumn = eventArgs.Column;
    sorter.Order = SortOrder.Ascending;
}

// Procéder au tri avec les nouvelles options.
eventSender.Sort();

Function edvTools.TryParse used above

class edvTools {
    /// <summary>
    /// Tente la conversion d'une valeur suivant un type EDVType
    /// </summary>
    /// <param name="pValue">Référence de la valeur à convertir</param>
    /// <param name="pType">Type EDV en sortie</param>
    /// <returns></returns>
    public static bool TryParse(ref object pValue, System.Type pType)
    {
        int lIParsed;
        double lDParsed;
        string lsValue;
        if (pValue == null) return false;
        if (pType.Equals(typeof(bool))) {
            bool lBParsed;
            if (pValue is bool) return true;
            if (double.TryParse(pValue.ToString(), out lDParsed)) {
                pValue = lDParsed != 0D;
                return true;
            }
            if (bool.TryParse(pValue.ToString(), out lBParsed)) {
                pValue = lBParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(Double))) {
            if (pValue is Double) return true;
            if (double.TryParse(pValue.ToString(), out lDParsed)
                || double.TryParse(pValue.ToString().Replace(NumberDecimalSeparatorNOT, NumberDecimalSeparator), out lDParsed)) {
                pValue = lDParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(int))) {
            if (pValue is int) return true;
            if (Int32.TryParse(pValue.ToString(), out lIParsed)) {
                pValue = lIParsed;
                return true;
            }
            else if (double.TryParse(pValue.ToString(), out lDParsed)) {
                pValue = (int)lDParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(Byte))) {
            if (pValue is byte) return true;
            byte lByte;
            if (Byte.TryParse(pValue.ToString(), out lByte)) {
                pValue = lByte;
                return true;
            }
            else if (double.TryParse(pValue.ToString(), out lDParsed)) {
                pValue = (byte)lDParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(long))) {
            long lLParsed;
            if (pValue is long) return true;
            if (long.TryParse(pValue.ToString(), out lLParsed)) {
                pValue = lLParsed;
                return true;
            }
            else if (double.TryParse(pValue.ToString(), out lDParsed)) {
                pValue = (long)lDParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(Single))) {
            if (pValue is float) return true;
            Single lSParsed;
            if (Single.TryParse(pValue.ToString(), out lSParsed)
                || Single.TryParse(pValue.ToString().Replace(NumberDecimalSeparatorNOT, NumberDecimalSeparator), out lSParsed)) {
                pValue = lSParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(DateTime))) {
            if (pValue is DateTime) return true;
            DateTime lDTParsed;
            if (DateTime.TryParse(pValue.ToString(), out lDTParsed)) {
                pValue = lDTParsed;
                return true;
            }
            else if (pValue.ToString().Contains("UTC")) //Date venant de JScript
            {
                if (_MonthsUTC == null) InitMonthsUTC();
                string[] lDateParts = pValue.ToString().Split(' ');
                lDTParsed = new DateTime(int.Parse(lDateParts[5]), _MonthsUTC[lDateParts[1]], int.Parse(lDateParts[2]));
                lDateParts = lDateParts[3].ToString().Split(':');
                pValue = lDTParsed.AddSeconds(int.Parse(lDateParts[0]) * 3600 + int.Parse(lDateParts[1]) * 60 + int.Parse(lDateParts[2]));
                return true;
            }
            else
                return false;

        }
        if (pType.Equals(typeof(Array))) {
            if (pValue is System.Collections.ICollection || pValue is System.Collections.ArrayList)
                return true;
            return pValue is System.Data.DataTable
                || pValue is string && (pValue as string).StartsWith("<");
        }
        if (pType.Equals(typeof(DataTable))) {
            return pValue is System.Data.DataTable
                || pValue is string && (pValue as string).StartsWith("<");

        }
        if (pType.Equals(typeof(System.Drawing.Bitmap))) {
            return pValue is System.Drawing.Image || pValue is byte[];

        }
        if (pType.Equals(typeof(System.Drawing.Image))) {
            return pValue is System.Drawing.Image || pValue is byte[];

        }
        if (pType.Equals(typeof(System.Drawing.Color))) {
            if (pValue is System.Drawing.Color) return true;
            if (pValue is System.Drawing.KnownColor) {
                pValue = System.Drawing.Color.FromKnownColor((System.Drawing.KnownColor)pValue);
                return true;
            }

            int lARGB;
            if (!int.TryParse(lsValue = pValue.ToString(), out lARGB)) {
                if (lsValue.StartsWith("Color [A=", StringComparison.InvariantCulture)) {
                    foreach (string lsARGB in lsValue.Substring("Color [".Length, lsValue.Length - "Color []".Length).Split(','))
                        switch (lsARGB.TrimStart().Substring(0, 1)) {
                            case "A":
                                lARGB = int.Parse(lsARGB.Substring(2)) * 0x1000000;
                                break;
                            case "R":
                                lARGB += int.Parse(lsARGB.TrimStart().Substring(2)) * 0x10000;
                                break;
                            case "G":
                                lARGB += int.Parse(lsARGB.TrimStart().Substring(2)) * 0x100;
                                break;
                            case "B":
                                lARGB += int.Parse(lsARGB.TrimStart().Substring(2));
                                break;
                            default:
                                break;
                        }
                    pValue = System.Drawing.Color.FromArgb(lARGB);
                    return true;
                }
                if (lsValue.StartsWith("Color [", StringComparison.InvariantCulture)) {
                    pValue = System.Drawing.Color.FromName(lsValue.Substring("Color [".Length, lsValue.Length - "Color []".Length));
                    return true;
                }
                return false;
            }
            pValue = System.Drawing.Color.FromArgb(lARGB);
            return true;
        }
        if (pType.IsEnum) {
            try {
                if (pValue == null) return false;
                if (pValue is int || pValue is byte || pValue is ulong || pValue is long || pValue is double)
                    pValue = Enum.ToObject(pType, pValue);
                else
                    pValue = Enum.Parse(pType, pValue.ToString());
            }
            catch {
                return false;
            }
        }
        return true;
    }
}

Getting all file names from a folder using C#

DirectoryInfo d = new DirectoryInfo(@"D:\Test");//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files
string str = "";
foreach(FileInfo file in Files )
{
  str = str + ", " + file.Name;
}

Hope this will help...

Export to csv in jQuery

Here are two WORKAROUNDS to the problem of triggering downloads from the client only. In later browsers you should look at "blob"


1. Drag and drop the table

Did you know you can simply DRAG your table into excel?

Here is how to select the table to either cut and past or drag

Select a complete table with Javascript (to be copied to clipboard)


2. create a popup page from your div

Although it will not produce a save dialog, if the resulting popup is saved with extension .csv, it will be treated correctly by Excel.

The string could be
w.document.write("row1.1\trow1.2\trow1.3\nrow2.1\trow2.2\trow2.3");
e.g. tab-delimited with a linefeed for the lines.

There are plugins that will create the string for you - such as http://plugins.jquery.com/project/table2csv

var w = window.open('','csvWindow'); // popup, may be blocked though
// the following line does not actually do anything interesting with the 
// parameter given in current browsers, but really should have. 
// Maybe in some browser it will. It does not hurt anyway to give the mime type
w.document.open("text/csv");
w.document.write(csvstring); // the csv string from for example a jquery plugin
w.document.close();

DISCLAIMER: These are workarounds, and does not fully answer the question which currently has the answer for most browser: not possible on the client only

rails 3 validation on uniqueness on multiple attributes

Multiple Scope Parameters:

class TeacherSchedule < ActiveRecord::Base
  validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
end

http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of

This should answer Greg's question.

PHP, pass array through POST

Edit If you are asking about security, see my addendum at the bottom Edit

PHP has a serialize function provided for this specific purpose. Pass it an array, and it will give you a string representation of it. When you want to convert it back to an array, you just use the unserialize function.

$data = array('one'=>1, 'two'=>2, 'three'=>33);
$dataString = serialize($data);
//send elsewhere
$data = unserialize($dataString);

This is often used by lazy coders to save data to a database. Not recommended, but works as a quick/dirty solution.

Addendum

I was under the impression that you were looking for a way to send the data reliably, not "securely". No matter how you pass the data, if it is going through the users system, you cannot trust it at all. Generally, you should store it somewhere on the server & use a credential (cookie, session, password, etc) to look it up.

gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now

This probably because of your gzip version incompatibility.

Check these points first:

which gzip

/usr/bin/gzip or /bin/gzip

It should be either /bin/gzip or /usr/bin/gzip. If your gzip points to some other gzip application please try by removing that path from your PATH env variable.

Next is

gzip -V

gzip 1.3.5 (2002-09-30)

Your problem can be resolve with these check points.

How to use ADB in Android Studio to view an SQLite DB

What it mentions as you type adb?

step1. >adb shell
step2. >cd data/data
step3. >ls -l|grep "your app package here"
step4. >cd "your app package here"
step5. >sqlite3 xx.db

outline on only one border

Try with Shadow( Like border ) + Border

border-bottom: 5px solid #fff;
box-shadow: 0 5px 0 #ffbf0e;

Jquery href click - how can I fire up an event?

It doesn't because the href value is not sign_up.It is #sign_up. Try like below, You need to add "#" to indicate the id of the href value.

$('a[href="#sign_up"]').click(function(){
  alert('Sign new href executed.'); 
}); 

DEMO: http://jsfiddle.net/pnGbP/

How to use Collections.sort() in Java?

Use the method that accepts a Comparator when you want to sort in something other than natural order.

Collections.sort(List, Comparator)

How can I use an http proxy with node.js http.Client?

The 'request' http package seems to have this feature:

https://github.com/mikeal/request

For example, the 'r' request object below uses localproxy to access its requests:

var r = request.defaults({'proxy':'http://localproxy.com'})

http.createServer(function (req, resp) {
  if (req.url === '/doodle.png') {
    r.get('http://google.com/doodle.png').pipe(resp)
  }
})

Unfortunately there are no "global" defaults so that users of libs that use this cannot amend the proxy unless the lib pass through http options...

HTH, Chris

Tkinter scrollbar for frame

Please see my class that is a scrollable frame. It's vertical scrollbar is binded to <Mousewheel> event as well. So, all you have to do is to create a frame, fill it with widgets the way you like, and then make this frame a child of my ScrolledWindow.scrollwindow. Feel free to ask if something is unclear.

Used a lot from @ Brayan Oakley answers to close to this questions

class ScrolledWindow(tk.Frame):
    """
    1. Master widget gets scrollbars and a canvas. Scrollbars are connected 
    to canvas scrollregion.

    2. self.scrollwindow is created and inserted into canvas

    Usage Guideline:
    Assign any widgets as children of <ScrolledWindow instance>.scrollwindow
    to get them inserted into canvas

    __init__(self, parent, canv_w = 400, canv_h = 400, *args, **kwargs)
    docstring:
    Parent = master of scrolled window
    canv_w - width of canvas
    canv_h - height of canvas

    """


    def __init__(self, parent, canv_w = 400, canv_h = 400, *args, **kwargs):
        """Parent = master of scrolled window
        canv_w - width of canvas
        canv_h - height of canvas

       """
        super().__init__(parent, *args, **kwargs)

        self.parent = parent

        # creating a scrollbars
        self.xscrlbr = ttk.Scrollbar(self.parent, orient = 'horizontal')
        self.xscrlbr.grid(column = 0, row = 1, sticky = 'ew', columnspan = 2)         
        self.yscrlbr = ttk.Scrollbar(self.parent)
        self.yscrlbr.grid(column = 1, row = 0, sticky = 'ns')         
        # creating a canvas
        self.canv = tk.Canvas(self.parent)
        self.canv.config(relief = 'flat',
                         width = 10,
                         heigh = 10, bd = 2)
        # placing a canvas into frame
        self.canv.grid(column = 0, row = 0, sticky = 'nsew')
        # accociating scrollbar comands to canvas scroling
        self.xscrlbr.config(command = self.canv.xview)
        self.yscrlbr.config(command = self.canv.yview)

        # creating a frame to inserto to canvas
        self.scrollwindow = ttk.Frame(self.parent)

        self.canv.create_window(0, 0, window = self.scrollwindow, anchor = 'nw')

        self.canv.config(xscrollcommand = self.xscrlbr.set,
                         yscrollcommand = self.yscrlbr.set,
                         scrollregion = (0, 0, 100, 100))

        self.yscrlbr.lift(self.scrollwindow)        
        self.xscrlbr.lift(self.scrollwindow)
        self.scrollwindow.bind('<Configure>', self._configure_window)  
        self.scrollwindow.bind('<Enter>', self._bound_to_mousewheel)
        self.scrollwindow.bind('<Leave>', self._unbound_to_mousewheel)

        return

    def _bound_to_mousewheel(self, event):
        self.canv.bind_all("<MouseWheel>", self._on_mousewheel)   

    def _unbound_to_mousewheel(self, event):
        self.canv.unbind_all("<MouseWheel>") 

    def _on_mousewheel(self, event):
        self.canv.yview_scroll(int(-1*(event.delta/120)), "units")  

    def _configure_window(self, event):
        # update the scrollbars to match the size of the inner frame
        size = (self.scrollwindow.winfo_reqwidth(), self.scrollwindow.winfo_reqheight())
        self.canv.config(scrollregion='0 0 %s %s' % size)
        if self.scrollwindow.winfo_reqwidth() != self.canv.winfo_width():
            # update the canvas's width to fit the inner frame
            self.canv.config(width = self.scrollwindow.winfo_reqwidth())
        if self.scrollwindow.winfo_reqheight() != self.canv.winfo_height():
            # update the canvas's width to fit the inner frame
            self.canv.config(height = self.scrollwindow.winfo_reqheight())

net::ERR_INSECURE_RESPONSE in Chrome

I was having this issue when testing my Cordova app on android. It just so happens that this android device does not persist its date, and will reset back to its factory date somehow. The API that it calls has a cert that is valid starting this year, while the device date after bootup is in 2017. For now, I have to adb shell and change the date manually.

How to Create a circular progressbar in Android which rotates on it?

Here is a simple customview for display circle progress. You can modify and optimize more to suitable for your project.

class CircleProgressBar @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    private val backgroundWidth = 10f
    private val progressWidth = 20f

    private val backgroundPaint = Paint().apply {
        color = Color.LTGRAY
        style = Paint.Style.STROKE
        strokeWidth = backgroundWidth
        isAntiAlias = true
    }

    private val progressPaint = Paint().apply {
        color = Color.RED
        style = Paint.Style.STROKE
        strokeWidth = progressWidth
        isAntiAlias = true
    }

    var progress: Float = 0f
        set(value) {
            field = value
            invalidate()
        }

    private val oval = RectF()
    private var centerX: Float = 0f
    private var centerY: Float = 0f
    private var radius: Float = 0f

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        centerX = w.toFloat() / 2
        centerY = h.toFloat() / 2
        radius = w.toFloat() / 2 - progressWidth
        oval.set(centerX - radius,
                centerY - radius,
                centerX + radius,
                centerY + radius)
        super.onSizeChanged(w, h, oldw, oldh)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.drawCircle(centerX, centerY, radius, backgroundPaint)
        canvas?.drawArc(oval, 270f, 360f * progress, false, progressPaint)
    }
}

Example using

xml

<com.example.androidcircleprogressbar.CircleProgressBar
    android:id="@+id/circle_progress"
    android:layout_width="200dp"
    android:layout_height="200dp" />

kotlin

class MainActivity : AppCompatActivity() {
    val TOTAL_TIME = 10 * 1000L

    override fun onCreate(savedInstanceState: Bundle?) {
        ...

        timeOutRemoveTimer.start()
    }

    private var timeOutRemoveTimer = object : CountDownTimer(TOTAL_TIME, 10) {
        override fun onFinish() {
            circle_progress.progress = 1f
        }

        override fun onTick(millisUntilFinished: Long) {
            circle_progress.progress = (TOTAL_TIME - millisUntilFinished).toFloat() / TOTAL_TIME
        }
    }
}

Result

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

What is JSON and why would I use it?

Sometimes technicality is given where none is required, and while many of the top voted answers are accurately technical and specific, I personally don't think they are any more easy to understand, or succinct, as what can be found on Wikipedia, or in official documentation.

The way I like to think of JSON is exactly what it is - a language within a world of different languages. However, the difference between JSON and other languages is that "everyone" "speaks" JSON, along with their "native language."

Using a real world example, let's pretend we have three people. One person speaks Igbo as their native tongue. The second person would like to interact with the first person, however, the first person speaks Yoruba as their first language.

What can we do?

Thankfully, the third person in our example grew up speaking English, but also happens to speak both Igbo and Yoruba as second languages, and so can act as an intermediary between the first two individuals.

In the programming world, the first "person" is Python, the second "person" is Ruby, and the third "person" is JSON, who just so happens to be able to "translate" Ruby into Python and vice versa! Now obviously this analogy isn't a perfect one, but, as someone who is bilingual, I believe it's an easy way to look at how JSON interacts with other programming languages.

Angular2 get clicked element id

do like this simply: (as said in comment here is with example with two methods)

import {Component} from 'angular2/core';

@Component({
    selector: 'my-app', 
    template: `
      <button (click)="checkEvent($event,'a')" id="abc" class="def">Display Toastr</button>
      <button (click)="checkEvent($event,'b')" id="abc1" class="def1">Display Toastr1</button>
    `
})
export class AppComponent {
  checkEvent(event, id){
    console.log(event, id, event.srcElement.attributes.id);
  }
}

demo: http://plnkr.co/edit/5kJaj9D13srJxmod213r?p=preview

How to delete a line from a text file in C#?

string fileIN = @"C:\myTextFile.txt";
string fileOUT = @"C:\myTextFile_Out.txt";
if (File.Exists(fileIN))
{
    string[] data = File.ReadAllLines(fileIN);
    foreach (string line in data)
        if (!line.Equals("my line to remove"))
            File.AppendAllText(fileOUT, line);
    File.Delete(fileIN);
    File.Move(fileOUT, fileIN);
}

How to read string from keyboard using C?

#include<stdio.h>

int main()
{
    char str[100];
    scanf("%[^\n]s",str);
    printf("%s",str);
    return 0;
}

input: read the string
ouput: print the string

This code prints the string with gaps as shown above.

How do I put text on ProgressBar?

Just want to point out something on @codingbadger answer. When using "ProgressBarRenderer" you should always check for "ProgressBarRenderer.IsSupported" before using the class. For me, this has been a nightmare with Visual Styles errors in Win7 that I couldn't fix. So, a better approach and workaround for the solution would be:

Rectangle clip = new Rectangle(rect.X, rect.Y, (int)Math.Round(((float)Value / Maximum) * rect.Width), rect.Height);
if (ProgressBarRenderer.IsSupported)
  ProgressBarRenderer.DrawHorizontalChunks(g, clip);
else
  g.FillRectangle(new SolidBrush(this.ForeColor), clip);

Notice that the fill will be a simple rectangle and not chunks. Chunks will be used only if ProgressBarRenderer is supported

Convert a String In C++ To Upper Case

The answer of @dirkgently is very inspiring, but I want to emphasize that due to the concern as is shown below,

Like all other functions from , the behavior of std::toupper is undefined if the argument's value is neither representable as unsigned char nor equal to EOF. To use these functions safely with plain chars (or signed chars), the argument should first be converted to unsigned char
Reference: std::toupper

As the standard does not specify if plain char is signed or unsigned[1], the correct usage of std::toupper should be:

#include <algorithm>
#include <cctype>
#include <iostream>
#include <iterator>
#include <string>

void ToUpper(std::string& input)
{
    std::for_each(std::begin(input), std::end(input), [](char& c) {
        c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
    });
}

int main()
{
    std::string s{ "Hello world!" };
    std::cout << s << std::endl;
    ::ToUpper(s);
    std::cout << s << std::endl;

    return 0;
}

Output:

Hello world!
HELLO WORLD!

How can I verify if an AD account is locked?

Here's another one:

PS> Search-ADAccount -Locked | Select Name, LockedOut, LastLogonDate

Name                                       LockedOut LastLogonDate
----                                       --------- -------------
Yxxxxxxx                                        True 14/11/2014 10:19:20
Bxxxxxxx                                        True 18/11/2014 08:38:34
Administrator                                   True 03/11/2014 20:32:05

Other parameters worth mentioning:

Search-ADAccount -AccountExpired
Search-ADAccount -AccountDisabled
Search-ADAccount -AccountInactive

Get-Help Search-ADAccount -ShowWindow

addEventListener vs onclick

`let element = document.queryselector('id or classname');

element.addeventlistiner('click',()=>{

do work })`

<button onclick="click()">click</click>

function click(){ do work };

How do I show my global Git configuration?

How do I edit my global Git configuration?

Short answer: git config --edit --global


To understand Git configuration, you should know that:

Git configuration variables can be stored at three different levels. Each level overrides values at the previous level.

1. System level (applied to every user on the system and all their repositories)

  • to view, git config --list --system (may need sudo)
  • to set, git config --system color.ui true
  • to edit system config file, git config --edit --system

2. Global level (values specific personally to you, the user).

  • to view, git config --list --global
  • to set, git config --global user.name xyz
  • to edit global config file, git config --edit --global

3. Repository level (specific to that single repository)

  • to view, git config --list --local
  • to set, git config --local core.ignorecase true (--local optional)
  • to edit repository config file, git config --edit --local (--local optional)

How do I view all settings?

  • Run git config --list, showing system, global, and (if inside a repository) local configs
  • Run git config --list --show-origin, also shows the origin file of each config item

How do I read one particular configuration?

  • Run git config user.name to get user.name, for example.
  • You may also specify options --system, --global, --local to read that value at a particular level.

Reference: 1.6 Getting Started - First-Time Git Setup

What is the meaning of single and double underscore before an object name?

Excellent answers so far but some tidbits are missing. A single leading underscore isn't exactly just a convention: if you use from foobar import *, and module foobar does not define an __all__ list, the names imported from the module do not include those with a leading underscore. Let's say it's mostly a convention, since this case is a pretty obscure corner;-).

The leading-underscore convention is widely used not just for private names, but also for what C++ would call protected ones -- for example, names of methods that are fully intended to be overridden by subclasses (even ones that have to be overridden since in the base class they raise NotImplementedError!-) are often single-leading-underscore names to indicate to code using instances of that class (or subclasses) that said methods are not meant to be called directly.

For example, to make a thread-safe queue with a different queueing discipline than FIFO, one imports Queue, subclasses Queue.Queue, and overrides such methods as _get and _put; "client code" never calls those ("hook") methods, but rather the ("organizing") public methods such as put and get (this is known as the Template Method design pattern -- see e.g. here for an interesting presentation based on a video of a talk of mine on the subject, with the addition of synopses of the transcript).

Edit: The video links in the description of the talks are now broken. You can find the first two videos here and here.

How do I use shell variables in an awk script?

Getting shell variables into awk

may be done in several ways. Some are better than others. This should cover most of them. If you have a comment, please leave below.                                                                                    v1.5


Using -v (The best way, most portable)

Use the -v option: (P.S. use a space after -v or it will be less portable. E.g., awk -v var= not awk -vvar=)

variable="line one\nline two"
awk -v var="$variable" 'BEGIN {print var}'
line one
line two

This should be compatible with most awk, and the variable is available in the BEGIN block as well:

If you have multiple variables:

awk -v a="$var1" -v b="$var2" 'BEGIN {print a,b}'

Warning. As Ed Morton writes, escape sequences will be interpreted so \t becomes a real tab and not \t if that is what you search for. Can be solved by using ENVIRON[] or access it via ARGV[]

PS If you like three vertical bar as separator |||, it can't be escaped, so use -F"[|][|][|]"

Example on getting data from a program/function inn to awk (here date is used)

awk -v time="$(date +"%F %H:%M" -d '-1 minute')" 'BEGIN {print time}'

Variable after code block

Here we get the variable after the awk code. This will work fine as long as you do not need the variable in the BEGIN block:

variable="line one\nline two"
echo "input data" | awk '{print var}' var="${variable}"
or
awk '{print var}' var="${variable}" file
  • Adding multiple variables:

awk '{print a,b,$0}' a="$var1" b="$var2" file

  • In this way we can also set different Field Separator FS for each file.

awk 'some code' FS=',' file1.txt FS=';' file2.ext

  • Variable after the code block will not work for the BEGIN block:

echo "input data" | awk 'BEGIN {print var}' var="${variable}"


Here-string

Variable can also be added to awk using a here-string from shells that support them (including Bash):

awk '{print $0}' <<< "$variable"
test

This is the same as:

printf '%s' "$variable" | awk '{print $0}'

P.S. this treats the variable as a file input.


ENVIRON input

As TrueY writes, you can use the ENVIRON to print Environment Variables. Setting a variable before running AWK, you can print it out like this:

X=MyVar
awk 'BEGIN{print ENVIRON["X"],ENVIRON["SHELL"]}'
MyVar /bin/bash

ARGV input

As Steven Penny writes, you can use ARGV to get the data into awk:

v="my data"
awk 'BEGIN {print ARGV[1]}' "$v"
my data

To get the data into the code itself, not just the BEGIN:

v="my data"
echo "test" | awk 'BEGIN{var=ARGV[1];ARGV[1]=""} {print var, $0}' "$v"
my data test

Variable within the code: USE WITH CAUTION

You can use a variable within the awk code, but it's messy and hard to read, and as Charles Duffy points out, this version may also be a victim of code injection. If someone adds bad stuff to the variable, it will be executed as part of the awk code.

This works by extracting the variable within the code, so it becomes a part of it.

If you want to make an awk that changes dynamically with use of variables, you can do it this way, but DO NOT use it for normal variables.

variable="line one\nline two"
awk 'BEGIN {print "'"$variable"'"}'
line one
line two

Here is an example of code injection:

variable='line one\nline two" ; for (i=1;i<=1000;++i) print i"'
awk 'BEGIN {print "'"$variable"'"}'
line one
line two
1
2
3
.
.
1000

You can add lots of commands to awk this way. Even make it crash with non valid commands.


Extra info:

Use of double quote

It's always good to double quote variable "$variable"
If not, multiple lines will be added as a long single line.

Example:

var="Line one
This is line two"

echo $var
Line one This is line two

echo "$var"
Line one
This is line two

Other errors you can get without double quote:

variable="line one\nline two"
awk -v var=$variable 'BEGIN {print var}'
awk: cmd. line:1: one\nline
awk: cmd. line:1:    ^ backslash not last character on line
awk: cmd. line:1: one\nline
awk: cmd. line:1:    ^ syntax error

And with single quote, it does not expand the value of the variable:

awk -v var='$variable' 'BEGIN {print var}'
$variable

More info about AWK and variables

Read this faq.

Get a list of all the files in a directory (recursive)

The following works for me in Gradle / Groovy for build.gradle for an Android project, without having to import groovy.io.FileType (NOTE: Does not recurse subdirectories, but when I found this solution I no longer cared about recursion, so you may not either):

FileCollection proGuardFileCollection = files { file('./proguard').listFiles() }
proGuardFileCollection.each {
    println "Proguard file located and processed: " + it
}

Remove 'b' character do in front of a string literal in Python 3

This should do the trick:

pw_bytes.decode("utf-8")

How to make cross domain request

You can make cross domain requests using the XMLHttpRequest object. This is done using something called "Cross Origin Resource Sharing". See: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Very simply put, when the request is made to the server the server can respond with a Access-Control-Allow-Origin header which will either allow or deny the request. The browser needs to check this header and if it is allowed then it will continue with the request process. If not the browser will cancel the request.

You can find some more information and a working example here: http://www.leggetter.co.uk/2010/03/12/making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html

JSONP is an alternative solution, but you could argue it's a bit of a hack.

Javascript sleep/delay/wait function

The behavior exact to the one specified by you is impossible in JS as implemented in current browsers. Sorry.

Well, you could in theory make a function with a loop where loop's end condition would be based on time, but this would hog your CPU, make browser unresponsive and would be extremely poor design. I refuse to even write an example for this ;)


Update: My answer got -1'd (unfairly), but I guess I could mention that in ES6 (which is not implemented in browsers yet, nor is it enabled in Node.js by default), it will be possible to write a asynchronous code in a synchronous fashion. You would need promises and generators for that.

You can use it today, for instance in Node.js with harmony flags, using Q.spawn(), see this blog post for example (last example there).

Hive load CSV with commas in quoted fields

ORG.APACHE.HADOOP.HIVE.SERDE2.OPENCSVSERDE Serde worked for me. My delimiter was '|' and one of the columns is enclosed in double quotes.

Query:

CREATE EXTERNAL TABLE EMAIL(MESSAGE_ID STRING, TEXT STRING, TO_ADDRS STRING, FROM_ADDRS STRING, SUBJECT STRING, DATE STRING)
ROW FORMAT SERDE 'ORG.APACHE.HADOOP.HIVE.SERDE2.OPENCSVSERDE'
WITH SERDEPROPERTIES (
     "SEPARATORCHAR" = "|",
     "QUOTECHAR"     = "\"",
     "ESCAPECHAR"    = "\""
)    
STORED AS TEXTFILE location '/user/abc/csv_folder';

How to return a file (FileContentResult) in ASP.NET WebAPI

Here is an implementation that streams the file's content out without buffering it (buffering in byte[] / MemoryStream, etc. can be a server problem if it's a big file).

public class FileResult : IHttpActionResult
{
    public FileResult(string filePath)
    {
        if (filePath == null)
            throw new ArgumentNullException(nameof(filePath));

        FilePath = filePath;
    }

    public string FilePath { get; }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StreamContent(File.OpenRead(FilePath));
        var contentType = MimeMapping.GetMimeMapping(Path.GetExtension(FilePath));
        response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
        return Task.FromResult(response);
    }
}

It can be simply used like this:

public class MyController : ApiController
{
    public IHttpActionResult Get()
    {
        string filePath = GetSomeValidFilePath();
        return new FileResult(filePath);
    }
}

Two onClick actions one button

Try it:

<input type="button" value="Dont show this again! " onClick="fbLikeDump();WriteCookie();" />

Or also

<script>
function clickEvent(){
    fbLikeDump();
    WriteCookie();
}
</script>
<input type="button" value="Dont show this again! " onClick="clickEvent();" />

Java - escape string to prevent SQL injection

If you are using PL/SQL you can also use DBMS_ASSERT it can sanitize your input so you can use it without worrying about SQL injections.

see this answer for instance: https://stackoverflow.com/a/21406499/1726419

Total size of the contents of all the files in a directory

Just an alternative:

ls -lAR | grep -v '^d' | awk '{total += $5} END {print "Total:", total}'

grep -v '^d' will exclude the directories.

How to loop an object in React?

I highly suggest you to use an array instead of an object if you're doing react itteration, this is a syntax I use it ofen.

const rooms = this.state.array.map((e, i) =>(<div key={i}>{e}</div>))

To use the element, just place {rooms} in your jsx.

Where e=elements of the arrays and i=index of the element. Read more here. If your looking for itteration, this is the way to do it.

Javascript close alert box

I want to be able to close an alert box automatically using javascript after a certain amount of time or on a specific event (i.e. onkeypress)

A sidenote: if you have an Alert("data"), you won't be able to keep code running in background (AFAIK)... . the dialog box is a modal window, so you can't lose focus too. So you won't have any keypress or timer running...

How to use Google Translate API in my Java application?

You can use google script which has FREE translate API. All you need is a common google account and do these THREE EASY STEPS.
1) Create new script with such code on google script:

var mock = {
  parameter:{
    q:'hello',
    source:'en',
    target:'fr'
  }
};


function doGet(e) {
  e = e || mock;

  var sourceText = ''
  if (e.parameter.q){
    sourceText = e.parameter.q;
  }

  var sourceLang = '';
  if (e.parameter.source){
    sourceLang = e.parameter.source;
  }

  var targetLang = 'en';
  if (e.parameter.target){
    targetLang = e.parameter.target;
  }

  var translatedText = LanguageApp.translate(sourceText, sourceLang, targetLang, {contentType: 'html'});

  return ContentService.createTextOutput(translatedText).setMimeType(ContentService.MimeType.JSON);
}

2) Click Publish -> Deploy as webapp -> Who has access to the app: Anyone even anonymous -> Deploy. And then copy your web app url, you will need it for calling translate API.
google script deploy

3) Use this java code for testing your API:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class Translator {

    public static void main(String[] args) throws IOException {
        String text = "Hello world!";
        //Translated text: Hallo Welt!
        System.out.println("Translated text: " + translate("en", "de", text));
    }

    private static String translate(String langFrom, String langTo, String text) throws IOException {
        // INSERT YOU URL HERE
        String urlStr = "https://your.google.script.url" +
                "?q=" + URLEncoder.encode(text, "UTF-8") +
                "&target=" + langTo +
                "&source=" + langFrom;
        URL url = new URL(urlStr);
        StringBuilder response = new StringBuilder();
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        return response.toString();
    }

}

As it is free, there are QUATA LIMITS: https://docs.google.com/macros/dashboard

Detect if PHP session exists

I use a combined version:

if(session_id() == '' || !isset($_SESSION)) {
    // session isn't started
    session_start();
}

.includes() not working in Internet Explorer

For react:

import 'react-app-polyfill/ie11';
import 'core-js/es5';
import 'core-js/es6';
import 'core-js/es7';

Issue resolve for - includes(), find(), and so on..

How to remove line breaks (no characters!) from the string?

It's because nl2br() doesn't remove new lines at all.

Returns string with <br /> or <br> inserted before all newlines (\r\n, \n\r, \n and \r).

Use str_replace instead:

$string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string);

How do I use HTML as the view engine in Express?

To make the render engine accept html instead of jade you can follow the following steps;

Install consolidate and swig to your directory.

 npm install consolidate
 npm install swig

add following lines to your app.js file

var cons = require('consolidate');

// view engine setup
app.engine('html', cons.swig)
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');

add your view templates as .html inside “views” folder. Restart you node server and start the app in the browser.

This should work

Node.js version on the command line? (not the REPL)

open node.js command prompt
run this command

node -v

How to connect access database in c#

Try this code,

public void ConnectToAccess()
{
    System.Data.OleDb.OleDbConnection conn = new 
        System.Data.OleDb.OleDbConnection();
    // TODO: Modify the connection string and include any
    // additional required properties for your database.
    conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
        @"Data source= C:\Documents and Settings\username\" +
        @"My Documents\AccessFile.mdb";
    try
    {
        conn.Open();
        // Insert code to process data.
    }
        catch (Exception ex)
    {
        MessageBox.Show("Failed to connect to data source");
    }
    finally
    {
        conn.Close();
    }
}

http://msdn.microsoft.com/en-us/library/5ybdbtte(v=vs.71).aspx

How can I solve "Either the parameter @objname is ambiguous or the claimed @objtype (COLUMN) is wrong."?

Are you running the query in the correct database? i.e.,

Use MyDatabase;
GO
EXEC sp_rename 'ENG_TEst.[ENG_Test_A/C_TYPE]', 'ENG_Test_AC_TYPE', 'COLUMN';
GO

How can I initialize a String array with length 0 in Java?

String[] str = {};

But

return {};

won't work as the type information is missing.

Counting in a FOR loop using Windows Batch script

for a = 1 to 100 step 1

Command line in Windows . Please use %%a if running in Batch file.

    for /L %a in (1,1,100) Do echo %a 

Port 80 is being used by SYSTEM (PID 4), what is that?

I had the same problem and it was because of IIS running on the server, you can stop it using IIS Manager if it is the case for you.

Dynamically changing font size of UILabel

Its a little bit not sophisticated but this should work, for example lets say you want to cap your uilabel to 120x120, with max font size of 28:

magicLabel.numberOfLines = 0;
magicLabel.lineBreakMode = NSLineBreakByWordWrapping;
...
magicLabel.text = text;
    for (int i = 28; i>3; i--) {
        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:(CGFloat)i] constrainedToSize:CGSizeMake(120.0f, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
        if (size.height < 120) {
            magicLabel.font = [UIFont systemFontOfSize:(CGFloat)i];
            break;
        }
    }

How to use andWhere and orWhere in Doctrine?

One thing missing here: if you have a varying number of elements that you want to put together to something like

WHERE [...] AND (field LIKE '%abc%' OR field LIKE '%def%')

and dont want to assemble a DQL-String yourself, you can use the orX mentioned above like this:

$patterns = ['abc', 'def'];
$orStatements = $qb->expr()->orX();
foreach ($patterns as $pattern) {
    $orStatements->add(
        $qb->expr()->like('field', $qb->expr()->literal('%' . $pattern . '%'))
    );
}
$qb->andWhere($orStatements);

Load text file as strings using numpy.loadtxt()

There is also read_csv in Pandas, which is fast and supports non-comma column separators and automatic typing by column:

import pandas as pd
df = pd.read_csv('your_file',sep='\t')

It can be converted to a NumPy array if you prefer that type with:

import numpy as np
arr = np.array(df)

This is by far the easiest and most mature text import approach I've come across.

PHP: maximum execution time when importing .SQL data file

Best solution for this error when i tried some points. Follow this steps to solve this issue:

  1. locate the file [XAMPP Installation Directory]\php\php.ini (e.g. C:\xampp\php\php.ini)
  2. open php.ini in Notepad or any Text editor
  3. locate the line containing max_execution_time and
  4. increase the value from 30 to some larger number (e.g. set: max_execution_time = 90)
  5. then restart Apache web server from the XAMPP control panel

How can I use the MS JDBC driver with MS SQL Server 2008 Express?

You can try the following. Works fine in my case:

  1. Download the current jTDS JDBC Driver
  2. Put jtds-x.x.x.jar in your classpath.
  3. Copy ntlmauth.dll to windows/system32. Choose the dll based on your hardware x86,x64...
  4. The connection url is: 'jdbc:jtds:sqlserver://localhost:1433/YourDB' , you don't have to provide username and password.

Hope that helps.

jquery click event not firing?

I was wasting my time on this for hours. Fortunately, I found the solution. If you are using bootstrap admin templates (AdminLTE), this problem may show up. Thing is we have to use adminLTE framework plugins.

example: ifChecked event:

$('input').on('ifChecked', function(event){
   alert(event.type + ' callback');
});

For more information click here.

Hope it helps you too.

Python conditional assignment operator

(can't comment or I would just do that) I believe the suggestion to check locals above is not quite right. It should be:

foo = foo if 'foo' in locals() or 'foo' in globals() else 'default'

to be correct in all contexts.

However, despite its upvotes, I don't think even that is a good analog to the Ruby operator. Since the Ruby operator allows more than just a simple name on the left:

foo[12] ||= something
foo.bar ||= something

The exception method is probably closest analog.

C#: New line and tab characters in strings

sb.AppendLine();

or

sb.Append( "\n" );

And

sb.Append( "\t" );

How to view file history in Git?

you could also use tig for a nice, ncurses-based git repository browser. To view history of a file:

tig path/to/file

Can regular expressions be used to match nested patterns?

No, you are getting into the realm of Context Free Grammars at that point.

How to go up a level in the src path of a URL in HTML?

In Chrome when you load a website from some HTTP server both absolute paths (e.g. /images/sth.png) and relative paths to some upper level directory (e.g. ../images/sth.png) work.

But!

When you load (in Chrome!) a HTML document from local filesystem you cannot access directories above current directory. I.e. you cannot access ../something/something.sth and changing relative path to absolute or anything else won't help.

Javascript counting number of objects in object

In recent browsers you can use:

Object.keys(obj.Data).length

See MDN

For older browsers, use the for-in loop in Michael Geary's answer.

Python Binomial Coefficient

Your program will continue with the second if statement in the case of y == x, causing a ZeroDivisionError. You need to make the statements mutually exclusive; the way to do that is to use elif ("else if") instead of if:

import math
x = int(input("Enter a value for x: "))
y = int(input("Enter a value for y: "))
if y == x:
    print(1)
elif y == 1:         # see georg's comment
    print(x)
elif y > x:          # will be executed only if y != 1 and y != x
    print(0)
else:                # will be executed only if y != 1 and y != x and x <= y
    a = math.factorial(x)
    b = math.factorial(y)
    c = math.factorial(x-y)  # that appears to be useful to get the correct result
    div = a // (b * c)
    print(div)  

Copying files from one directory to another in Java

following code to copy files from one directory to another

File destFile = new File(targetDir.getAbsolutePath() + File.separator
    + file.getName());
try {
  showMessage("Copying " + file.getName());
  in = new BufferedInputStream(new FileInputStream(file));
  out = new BufferedOutputStream(new FileOutputStream(destFile));
  int n;
  while ((n = in.read()) != -1) {
    out.write(n);
  }
  showMessage("Copied " + file.getName());
} catch (Exception e) {
  showMessage("Cannot copy file " + file.getAbsolutePath());
} finally {
  if (in != null)
    try {
      in.close();
    } catch (Exception e) {
    }
  if (out != null)
    try {
      out.close();
    } catch (Exception e) {
    }
}

Add a summary row with totals

If you are on SQL Server 2008 or later version, you can use the ROLLUP() GROUP BY function:

SELECT
  Type = ISNULL(Type, 'Total'),
  TotalSales = SUM(TotalSales)
FROM atable
GROUP BY ROLLUP(Type)
;

This assumes that the Type column cannot have NULLs and so the NULL in this query would indicate the rollup row, the one with the grand total. However, if the Type column can have NULLs of its own, the more proper type of accounting for the total row would be like in @Declan_K's answer, i.e. using the GROUPING() function:

SELECT
  Type = CASE GROUPING(Type) WHEN 1 THEN 'Total' ELSE Type END,
  TotalSales = SUM(TotalSales)
FROM atable
GROUP BY ROLLUP(Type)
;

Display Last Saved Date on worksheet

May be this time stamp fit you better Code

Function LastInputTimeStamp() As Date
  LastInputTimeStamp = Now()
End Function

and each time you input data in defined cell (in my example below it is cell C36) you'll get a new constant time stamp. As an example in Excel file may use this

=IF(C36>0,LastInputTimeStamp(),"")

Removing duplicate rows from table in Oracle

solution :

delete from emp where rowid in
(
    select rid from
    (
        select rowid rid,
        row_number() over(partition by empno order by empno) rn
        from emp
    )
    where rn > 1
);

What does "The following object is masked from 'package:xxx'" mean?

I have the same problem. I avoid it with remove.packages("Package making this confusion") and it works. In my case, I don't need the second package, so that is not a very good idea.

How do I alter the precision of a decimal column in Sql Server?

There may be a better way, but you can always copy the column into a new column, drop it and rename the new column back to the name of the first column.

to wit:

ALTER TABLE MyTable ADD NewColumnName DECIMAL(16, 2);
GO

UPDATE  MyTable
SET     NewColumnName = OldColumnName;
GO

ALTER TABLE CONTRACTS DROP COLUMN OldColumnName;
GO


EXEC sp_rename
    @objname = 'MyTable.NewColumnName',
    @newname = 'OldColumnName',
    @objtype = 'COLUMN'
GO

This was tested on SQL Server 2008 R2, but should work on SQL Server 2000+.

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

Only for .NET Core Web API project, add following changes:

  1. Add the following code after the services.AddMvc() line in the ConfigureServices() method of the Startup.cs file:
services.AddCors(allowsites=>{allowsites.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
            });
  1. Add the following code after app.UseMvc() line in the Configure() method of the Startup.cs file:
app.UseCors(options => options.AllowAnyOrigin());
  1. Open the controller which you want to access outside the domain and add this following attribute at the controller level:
[EnableCors("AllowOrigin")]

Fastest way to convert Image to Byte array

public static byte[] ReadImageFile(string imageLocation)
    {
        byte[] imageData = null;
        FileInfo fileInfo = new FileInfo(imageLocation);
        long imageFileLength = fileInfo.Length;
        FileStream fs = new FileStream(imageLocation, FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);
        imageData = br.ReadBytes((int)imageFileLength);
        return imageData;
    }

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

This was resolved. It turns out our IT Staff was correct. Both TLS 1.1 and TLS 1.2 were installed on the server. However, the issue was that our sites are running as ASP.NET 4.0 and you have to have ASP.NET 4.5 to run TLS 1.1 or TLS 1.2. So, to resolve the issue, our IT Staff had to re-enable TLS 1.0 to allow a connection with PayTrace.

So in short, the error message, "the client and server cannot communicate, because they do not possess a common algorithm", was caused because there was no SSL Protocol available on the server to communicate with PayTrace's servers.

UPDATE: Please do not enable TLS 1.0 on your servers, this was a temporary fix and is not longer applicable since there are now better work-arounds that ensure strong security practices. Please see accepted answer for a solution. FYI, I'm going to keep this answer on the site as it provides information on what the problem was, please do not down-vote.

Succeeded installing but could not start apache 2.4 on my windows 7 system

So, that is why i do a two (or more) post.

I was having the same problem when starting the service (logs can not be opened).

I thought it was because i was trying to have htdocs inside a VeraCrypt encripted container, absurd since i hace such contained mounted and i use a juntion to not affect paths.

The i read the cause could be low ram: after some tests i get to the next conclusion.

Windows is not sending pages to virtual ram to free enough ram if it is a service, for applications it is doing it, i have more than 200GiB of pagefile ready to be used as virtual ram in a 4GiB 64 Bit windows 10.

My solution:

  1. Run a free utility that free ram (512MiB in my test)
  2. Inmediatly after start the service, it starts with no errors

Real Cause:

  • I was using a virtual machine that uses 1/2 physical free ram (1.5GiB)

Hope this help others.

LOAD DATA INFILE Error Code : 13

This is normally a file access permissions issue but I see your already addressing that in point b, but it's worth going over just in case. Another option is to use LOAD DATA LOCAL INFILE which gets past a lot of these issues of file access permissions. To use this method though you need to copy the file locally (in the mysql folder is best) first. •If LOCAL is specified, the file is read by the client program on the client host and sent to the server.

Insufficient Directory Permissions

The error in this example has resulted because the file you are trying to import is not in a directory which is readable by the user the MySql server is running as. Note that all the parent directories of the directory the is in need to be readable by the MySql user for this to work. Saving the file to /tmp will usually work as this is usually readable (and writable) by all users. The error code number is 13. Source

EDIT:

Remember you will need permissions on not just the folder the holds the file but also the upper directories.

Example from this post on the MySql Forums.

If your file was contained within the following strucutre: /tmp/imports/site1/data.file

you would need (I think, 755 worked) r+x for 'other' on these directories:

/tmp

/tmp/imports

As well as the main two:

/tmp/imports/site1

/tmp/imports/site1/data.file

You need the file and directory to be world-readable. Apologies if you've already tried this method but it may be worth retracing your steps, never hurts to double check.

Code signing is required for product type 'Application' in SDK 'iOS5.1'

I had this problem even though I had a valid provisioning profile for the device. It turned out that I had changed my developer account password and needed to update the password in xcode. This is done by going to preferences-Accounts-Apple ID and entering the new password.

RuntimeError on windows trying python multiprocessing

Though the earlier answers are correct, there's a small complication it would help to remark on.

In case your main module imports another module in which global variables or class member variables are defined and initialized to (or using) some new objects, you may have to condition that import in the same way:

if __name__ ==  '__main__':
  import my_module

How can I overwrite file contents with new content in PHP?

MY PREFERRED METHOD is using fopen,fwrite and fclose [it will cost less CPU]

$f=fopen('myfile.txt','w');
fwrite($f,'new content');
fclose($f);

Warning for those using file_put_contents

It'll affect a lot in performance, for example [on the same class/situation] file_get_contents too: if you have a BIG FILE, it'll read the whole content in one shot and that operation could take a long waiting time

How to write inline if statement for print?

Inline if-else EXPRESSION must always contain else clause, e.g:

a = 1 if b else 0

If you want to leave your 'a' variable value unchanged - assing old 'a' value (else is still required by syntax demands):

a = 1 if b else a

This piece of code leaves a unchanged when b turns to be False.

How to delete directory content in Java?

for(File f : files) {
    f.delete();
}    
files.delete(); // will work

Replacing blank values (white space) with NaN in pandas

I think df.replace() does the job, since pandas 0.13:

df = pd.DataFrame([
    [-0.532681, 'foo', 0],
    [1.490752, 'bar', 1],
    [-1.387326, 'foo', 2],
    [0.814772, 'baz', ' '],     
    [-0.222552, '   ', 4],
    [-1.176781,  'qux', '  '],         
], columns='A B C'.split(), index=pd.date_range('2000-01-01','2000-01-06'))

# replace field that's entirely space (or empty) with NaN
print(df.replace(r'^\s*$', np.nan, regex=True))

Produces:

                   A    B   C
2000-01-01 -0.532681  foo   0
2000-01-02  1.490752  bar   1
2000-01-03 -1.387326  foo   2
2000-01-04  0.814772  baz NaN
2000-01-05 -0.222552  NaN   4
2000-01-06 -1.176781  qux NaN

As Temak pointed it out, use df.replace(r'^\s+$', np.nan, regex=True) in case your valid data contains white spaces.

How to check if a date is in a given range?

Use the DateTime class if you have PHP 5.3+. Easier to use, better functionality.

DateTime internally supports timezones, with the other solutions is up to you to handle that.

<?php    
/**
 * @param DateTime $date Date that is to be checked if it falls between $startDate and $endDate
 * @param DateTime $startDate Date should be after this date to return true
 * @param DateTime $endDate Date should be before this date to return true
 * return bool
 */
function isDateBetweenDates(DateTime $date, DateTime $startDate, DateTime $endDate) {
    return $date > $startDate && $date < $endDate;
}

$fromUser = new DateTime("2012-03-01");
$startDate = new DateTime("2012-02-01 00:00:00");
$endDate = new DateTime("2012-04-30 23:59:59");

echo isDateBetweenDates($fromUser, $startDate, $endDate);

Ajax success function

It is because Ajax is asynchronous, the success or the error function will be called later, when the server answer the client. So, just move parts depending on the result into your success function like that :

jQuery.ajax({

            type:"post",
            dataType:"json",
            url: myAjax.ajaxurl,
            data: {action: 'submit_data', info: info},
            success: function(data) {
                successmessage = 'Data was succesfully captured';
                $("label#successmessage").text(successmessage);
            },
            error: function(data) {
                successmessage = 'Error';
                $("label#successmessage").text(successmessage);
            },
        });

        $(":input").val('');
        return false;

Best way to reset an Oracle sequence to the next value in an existing column?

These two procedures let me reset the sequence and reset the sequence based on data in a table (apologies for the coding conventions used by this client):

CREATE OR REPLACE PROCEDURE SET_SEQ_TO(p_name IN VARCHAR2, p_val IN NUMBER)
AS
   l_num   NUMBER;
BEGIN
   EXECUTE IMMEDIATE 'select ' || p_name || '.nextval from dual' INTO l_num;

   -- Added check for 0 to avoid "ORA-04002: INCREMENT must be a non-zero integer"
   IF (p_val - l_num - 1) != 0
   THEN
      EXECUTE IMMEDIATE 'alter sequence ' || p_name || ' increment by ' || (p_val - l_num - 1) || ' minvalue 0';
   END IF;

   EXECUTE IMMEDIATE 'select ' || p_name || '.nextval from dual' INTO l_num;

   EXECUTE IMMEDIATE 'alter sequence ' || p_name || ' increment by 1 ';

   DBMS_OUTPUT.put_line('Sequence ' || p_name || ' is now at ' || p_val);
END;

CREATE OR REPLACE PROCEDURE SET_SEQ_TO_DATA(seq_name IN VARCHAR2, table_name IN VARCHAR2, col_name IN VARCHAR2)
AS
   nextnum   NUMBER;
BEGIN
   EXECUTE IMMEDIATE 'SELECT MAX(' || col_name || ') + 1 AS n FROM ' || table_name INTO nextnum;

   SET_SEQ_TO(seq_name, nextnum);
END;

PHP Error: Function name must be a string

<?php
    require_once '../config/config.php';
    require_once '../classes/class.College.php';
    $Response = array();
    $Parms = $_POST;
    $Parms['Id'] = Id;  

        $Parms['function'] = 'DeleteCollege';
        switch ($Parms['function']) {
        case 'InsertCollege': {
            $Response = College::InsertCollege($Parms);
            break;
        }
        case 'GetCollegeById': {
            $Response = College::GetCollegeById($Parms['Id']);
            break;
        }
        case 'GetAllCollege': {
            $Response = College::GetAllCollege();
            break;
        }
        case 'UpdateCollege': {
            $Response = College::UpdateCollege($Parms);
            break;
        }
        case 'DeleteCollege': {
            College::DeleteCollege($Parms['Id']);
            $Response = array('status' => 'R');
            break;
        }
    }
    echo json_encode($Response);
?>

How does the Spring @ResponseBody annotation work?

First of all, the annotation doesn't annotate List. It annotates the method, just as RequestMapping does. Your code is equivalent to

@RequestMapping(value="/orders", method=RequestMethod.GET)
@ResponseBody
public List<Account> accountSummary() {
    return accountManager.getAllAccounts();
}

Now what the annotation means is that the returned value of the method will constitute the body of the HTTP response. Of course, an HTTP response can't contain Java objects. So this list of accounts is transformed to a format suitable for REST applications, typically JSON or XML.

The choice of the format depends on the installed message converters, on the values of the produces attribute of the @RequestMapping annotation, and on the content type that the client accepts (that is available in the HTTP request headers). For example, if the request says it accepts XML, but not JSON, and there is a message converter installed that can transform the list to XML, then XML will be returned.

How do you add an ActionListener onto a JButton in Java

Your best bet is to review the Java Swing tutorials, specifically the tutorial on Buttons.

The short code snippet is:

jBtnDrawCircle.addActionListener( /*class that implements ActionListener*/ );

How to get the containing form of an input?

would this work? (leaving action blank submits form back to itself too, right?)

<form action="">
<select name="memberid" onchange="this.form.submit();">
<option value="1">member 1</option>
<option value="2">member 2</option>
</select>

"this" would be the select element, .form would be its parent form. Right?

Iterator over HashMap in Java

Iterator through keySet will give you keys. You should use entrySet if you want to iterate entries.

HashMap hm = new HashMap();

hm.put(0, "zero");
hm.put(1, "one");

Iterator iter = (Iterator) hm.entrySet().iterator();

while(iter.hasNext()) {

    Map.Entry entry = (Map.Entry) iter.next();
    System.out.println(entry.getKey() + " - " + entry.getValue());

}

How to concatenate items in a list to a single string?

This will help for sure -

arr=['a','b','h','i']     # let this be the list
s=""                      # creating a empty string
for i in arr:
   s+=i                   # to form string without using any function
print(s) 


       

Why are only a few video games written in Java?

A large reason is that video games require direct knowledge of the hardware underneath, often times, and there really is no great implementation for many architectures. It's the knowledge of the underlying hardware architecture that allows developers to squeeze every ounce of performance out of a gaming system. Why would you take the time to port Java to a gaming platform, and then write a game on top of that port when you could just write the game?

edit: this is to say that it's more than a "speed" or "don't have the right libraries" issue. Those two things go hand-in-hand with this, but it's more a matter of "how do I make a system like the cell b.e. run my java code? there aren't really any good java compilers that can manage the pipelines and vectors like i need.."

How to run test cases in a specified file?

@zzzz's answer is mostly complete, but just to save others from having to dig through the referenced documentation you can run a single test in a package as follows:

go test packageName -run TestName

Note that you want to pass in the name of the test, not the file name where the test exists.

The -run flag actually accepts a regex so you could limit the test run to a class of tests. From the docs:

-run regexp
    Run only those tests and examples matching the regular
    expression.

How can I check whether an array is null / empty?

There's a key difference between a null array and an empty array. This is a test for null.

int arr[] = null;
if (arr == null) {
  System.out.println("array is null");
}

"Empty" here has no official meaning. I'm choosing to define empty as having 0 elements:

arr = new int[0];
if (arr.length == 0) {
  System.out.println("array is empty");
}

An alternative definition of "empty" is if all the elements are null:

Object arr[] = new Object[10];
boolean empty = true;
for (int i=0; i<arr.length; i++) {
  if (arr[i] != null) {
    empty = false;
    break;
  }
}

or

Object arr[] = new Object[10];
boolean empty = true;
for (Object ob : arr) {
  if (ob != null) {
    empty = false;
    break;
  }
}

Undefined variable: $_SESSION

Turned out there was some extra code in the AppModel that was messing things up:

in beforeFind and afterFind:

App::Import("Session");
$session = new CakeSession();
$sim_id = $session->read("Simulation.id");

I don't know why, but that was what the problem was. Removing those lines fixed the issue I was having.

Ant if else condition?

Since ant 1.9.1 you can use a if:set condition : https://ant.apache.org/manual/ifunless.html

bitwise XOR of hex numbers in python

If the strings are the same length, then I would go for '%x' % () of the built-in xor (^).

Examples -

>>>a = '290b6e3a'
>>>b = 'd6f491c5'
>>>'%x' % (int(a,16)^int(b,16))
'ffffffff'
>>>c = 'abcd'
>>>d = '12ef'
>>>'%x' % (int(a,16)^int(b,16))
'b922'

If the strings are not the same length, truncate the longer string to the length of the shorter using a slice longer = longer[:len(shorter)]

How to generate XML from an Excel VBA macro?

This one more version - this will help in generic

Public strSubTag As String
Public iStartCol As Integer
Public iEndCol As Integer
Public strSubTag2 As String
Public iStartCol2 As Integer
Public iEndCol2 As Integer

Sub Create()
Dim strFilePath As String
Dim strFileName As String

'ThisWorkbook.Sheets("Sheet1").Range("C3").Activate
'strTag = ActiveCell.Offset(0, 1).Value
strFilePath = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
strFileName = ThisWorkbook.Sheets("Sheet1").Range("B5").Value
strSubTag = ThisWorkbook.Sheets("Sheet1").Range("F3").Value
iStartCol = ThisWorkbook.Sheets("Sheet1").Range("F4").Value
iEndCol = ThisWorkbook.Sheets("Sheet1").Range("F5").Value

strSubTag2 = ThisWorkbook.Sheets("Sheet1").Range("G3").Value
iStartCol2 = ThisWorkbook.Sheets("Sheet1").Range("G4").Value
iEndCol2 = ThisWorkbook.Sheets("Sheet1").Range("G5").Value

Dim iCaptionRow As Integer
iCaptionRow = ThisWorkbook.Sheets("Sheet1").Range("B3").Value
'strFileName = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
MakeXML iCaptionRow, iCaptionRow + 1, strFilePath, strFileName

End Sub


Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFilePath As String, sOutputFileName As String)
    Dim Q As String
    Dim sOutputFileNamewithPath As String
    Q = Chr$(34)

    Dim sXML As String


    'sXML = sXML & "<rows>"

'    ''--determine count of columns
    Dim iColCount As Integer
    iColCount = 1

    While Trim$(Cells(iCaptionRow, iColCount)) > ""
        iColCount = iColCount + 1
    Wend


    Dim iRow As Integer
    Dim iCount  As Integer
    iRow = iDataStartRow
    iCount = 1
    While Cells(iRow, 1) > ""
        'sXML = sXML & "<row id=" & Q & iRow & Q & ">"
        sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
        For iCOl = 1 To iColCount - 1
          If (iStartCol = iCOl) Then
               sXML = sXML & "<" & strSubTag & ">"
          End If
          If (iEndCol = iCOl) Then
               sXML = sXML & "</" & strSubTag & ">"
          End If
         If (iStartCol2 = iCOl) Then
               sXML = sXML & "<" & strSubTag2 & ">"
          End If
          If (iEndCol2 = iCOl) Then
               sXML = sXML & "</" & strSubTag2 & ">"
          End If
           sXML = sXML & "<" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
           sXML = sXML & Trim$(Cells(iRow, iCOl))
           sXML = sXML & "</" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
        Next

        'sXML = sXML & "</row>"
        Dim nDestFile As Integer, sText As String

    ''Close any open text files
        Close

    ''Get the number of the next free text file
        nDestFile = FreeFile
        sOutputFileNamewithPath = sOutputFilePath & sOutputFileName & iCount & ".XML"
    ''Write the entire file to sText
        Open sOutputFileNamewithPath For Output As #nDestFile
        Print #nDestFile, sXML

        iRow = iRow + 1
        sXML = ""
        iCount = iCount + 1
    Wend
    'sXML = sXML & "</rows>"

    Close
End Sub

MySQL SELECT WHERE datetime matches day (and not necessarily time)

NEVER EVER use a selector like DATE(datecolumns) = '2012-12-24' - it is a performance killer:

  • it will calculate DATE() for all rows, including those, that don't match
  • it will make it impossible to use an index for the query

It is much faster to use

SELECT * FROM tablename 
WHERE columname BETWEEN '2012-12-25 00:00:00' AND '2012-12-25 23:59:59'

as this will allow index use without calculation.

EDIT

As pointed out by Used_By_Already, in the time since the inital answer in 2012, there have emerged versions of MySQL, where using '23:59:59' as a day end is no longer safe. An updated version should read

SELECT * FROM tablename 
WHERE columname >='2012-12-25 00:00:00'
AND columname <'2012-12-26 00:00:00'

The gist of the answer, i.e. the avoidance of a selector on a calculated expression, of course still stands.

How to count down in for loop?

First I recommand you can try use print and observe the action:

for i in range(0, 5, 1):
    print i

the result:

0
1
2
3
4

You can understand the function principle. In fact, range scan range is from 0 to 5-1. It equals 0 <= i < 5

When you really understand for-loop in python, I think its time we get back to business. Let's focus your problem.

You want to use a DECREMENT for-loop in python. I suggest a for-loop tutorial for example.

for i in range(5, 0, -1):
    print i

the result:

5
4
3
2
1

Thus it can be seen, it equals 5 >= i > 0

You want to implement your java code in python:

for (int index = last-1; index >= posn; index--)

It should code this:

for i in range(last-1, posn-1, -1)

Javascript checkbox onChange

The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.

const checkbox = $("#checkboxId");

checkbox.change(function(event) {
    var checkbox = event.target;
    if (checkbox.checked) {
        //Checkbox has been checked
    } else {
        //Checkbox has been unchecked
    }
});

How to make for loops in Java increase by increments other than 1

That’s because j+3 doesn’t change the value of j. You need to replace that with j = j + 3 or j += 3 so that the value of j is increased by 3:

for (j = 0; j <= 90; j += 3) { }

Run two async tasks in parallel and collect results in .NET 4.5

This article helped explain a lot of things. It's in FAQ style.

Async/Await FAQ

This part explains why Thread.Sleep runs on the same original thread - leading to my initial confusion.

Does the “async” keyword cause the invocation of a method to queue to the ThreadPool? To create a new thread? To launch a rocket ship to Mars?

No. No. And no. See the previous questions. The “async” keyword indicates to the compiler that “await” may be used inside of the method, such that the method may suspend at an await point and have its execution resumed asynchronously when the awaited instance completes. This is why the compiler issues a warning if there are no “awaits” inside of a method marked as “async”.

How to use SearchView in Toolbar Android

If you want to add it directly in the toolbar.

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <SearchView
            android:id="@+id/searchView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:iconifiedByDefault="false"
            android:queryHint="Search"
            android:layout_centerHorizontal="true" />

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

How to generate a random string in Ruby

(0...8).map { (65 + rand(26)).chr }.join

I spend too much time golfing.

(0...50).map { ('a'..'z').to_a[rand(26)] }.join

And a last one that's even more confusing, but more flexible and wastes fewer cycles:

o = [('a'..'z'), ('A'..'Z')].map(&:to_a).flatten
string = (0...50).map { o[rand(o.length)] }.join

How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

You can use ExtendedXmlSerializer. If you have a class:

public class TestClass
{
    public Dictionary<int, string> Dictionary { get; set; }
}

and create instance of this class:

var obj = new TestClass
{
    Dictionary = new Dictionary<int, string>
    {
        {1, "First"},
        {2, "Second"},
        {3, "Other"},
    }
};

You can serialize this object using ExtendedXmlSerializer:

var serializer = new ConfigurationContainer()
    .UseOptimizedNamespaces() //If you want to have all namespaces in root element
    .Create();

var xml = serializer.Serialize(
    new XmlWriterSettings { Indent = true }, //If you want to formated xml
    obj);

Output xml will look like:

<?xml version="1.0" encoding="utf-8"?>
<TestClass xmlns:sys="https://extendedxmlserializer.github.io/system" xmlns:exs="https://extendedxmlserializer.github.io/v2" xmlns="clr-namespace:ExtendedXmlSerializer.Samples;assembly=ExtendedXmlSerializer.Samples">
  <Dictionary>
    <sys:Item>
      <Key>1</Key>
      <Value>First</Value>
    </sys:Item>
    <sys:Item>
      <Key>2</Key>
      <Value>Second</Value>
    </sys:Item>
    <sys:Item>
      <Key>3</Key>
      <Value>Other</Value>
    </sys:Item>
  </Dictionary>
</TestClass>

You can install ExtendedXmlSerializer from nuget or run the following command:

Install-Package ExtendedXmlSerializer

jquery function setInterval

This is because you are executing the function not referencing it. You should do:

  setInterval(swapImages,1000);

Convert pyQt UI to python

You don't have to install PyQt4 with all its side features, you just need the PyQt4 package itself. Inside the package you could use the module pyuic.py ("C:\Python27\Lib\site-packages\PyQt4\uic") to convert your Ui file.

C:\test>python C:\Python27x64\Lib\site-packages\PyQt4\uic\pyuic.py -help

update python3: use pyuic5 -help # add filepath if needed. pyuic version = 4 or 5.

You will get all options listed:

Usage: pyuic4 [options] <ui-file>

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -p, --preview         show a preview of the UI instead of generating code
  -o FILE, --output=FILE
                        write generated code to FILE instead of stdout
  -x, --execute         generate extra code to test and display the class
  -d, --debug           show debug output
  -i N, --indent=N      set indent width to N spaces, tab if N is 0 [default:
                        4]
  -w, --pyqt3-wrapper   generate a PyQt v3 style wrapper

  Code generation options:
    --from-imports      generate imports relative to '.'
    --resource-suffix=SUFFIX
                        append SUFFIX to the basename of resource files
                        [default: _rc]

So your command will look like this:

C:\test>python C:\Python27x64\Lib\site-packages\PyQt4\uic\pyuic.py test_dialog.ui -o test.py -x

You could also use full file paths to your file to convert it.

Why do you want to convert it anyway? I prefer creating widgets in the designer and implement them with via the *.ui file. That makes it much more comfortable to edit it later. You could also write your own widget plugins and load them into the Qt Designer with full access. Having your ui hard coded doesn't makes it very flexible.

I reuse a lot of my ui's not only in Maya, also for Max, Nuke, etc.. If you have to change something software specific, you should try to inherit the class (with the parented ui file) from a more global point of view and patch or override the methods you have to adjust. That saves a lot of work time. Let me know if you have more questions about it.

How do you get an iPhone's device name

For xamarin user, use this

UIKit.UIDevice.CurrentDevice.Name

Center Plot title in ggplot2

If you are working a lot with graphs and ggplot, you might be tired to add the theme() each time. If you don't want to change the default theme as suggested earlier, you may find easier to create your own personal theme.

personal_theme = theme(plot.title = 
element_text(hjust = 0.5))

Say you have multiple graphs, p1, p2 and p3, just add personal_theme to them.

p1 + personal_theme
p2 + personal_theme
p3 + personal_theme

dat <- data.frame(
  time = factor(c("Lunch","Dinner"), 
levels=c("Lunch","Dinner")),
  total_bill = c(14.89, 17.23)
)
p1 = ggplot(data=dat, aes(x=time, y=total_bill, 
fill=time)) + 
  geom_bar(colour="black", fill="#DD8888", 
width=.8, stat="identity") + 
  guides(fill=FALSE) +
  xlab("Time of day") + ylab("Total bill") +
  ggtitle("Average bill for 2 people")

p1 + personal_theme

React setState not updating state

The setstate is asynchronous in react, so to see the updated state in console use the callback as shown below (Callback function will execute after the setstate update)

enter image description here

The below method is "not recommended" but for understanding, if you mutate state directly you can see the updated state in the next line. I repeat this is "not recommended"

enter image description here

Assigning a function to a variable

when you perform y=x() you are actually assigning y to the result of calling the function object x and the function has a return value of None. Function calls in python are performed using (). To assign x to y so you can call y just like you would x you assign the function object x to y like y=x and call the function using y()

Appending the same string to a list of strings in Python

my_list = ['foo', 'fob', 'faz', 'funk']
string = 'bar'
my_new_list = [x + string for x in my_list]
print my_new_list

This will print:

['foobar', 'fobbar', 'fazbar', 'funkbar']

Notepad++ cached files location

I noticed it myself, and found the files inside the backup folder. You can check where it is using Menu:Settings -> Preferences -> Backup. Note : My NPP installation is portable, and on Windows, so YMMV.

How to remove specific value from array using jQuery

With jQuery, you can do a single-line operation like this:

Example: http://jsfiddle.net/HWKQY/

y.splice( $.inArray(removeItem, y), 1 );

Uses the native .splice() and jQuery's $.inArray().

replace \n and \r\n with <br /> in java

It works for me. The Java code works exactly as you wrote it. In the tester, the input string should be:

This is a string.
This is a long string.

...with a real linefeed. You can't use:

This is a string.\nThis is a long string.

...because it treats \n as the literal sequence backslash 'n'.

How to force a html5 form validation without submitting it via jQuery

Here is a more general way that is a bit cleaner:

Create your form like this (can be a dummy form that does nothing):

<form class="validateDontSubmit">
...

Bind all forms that you dont really want to submit:

$(document).on('submit','.validateDontSubmit',function (e) {
    //prevent the form from doing a submit
    e.preventDefault();
    return false;
})

Now lets say you have an <a> (within the <form>) that on click you want to validate the form:

$('#myLink').click(function(e){
  //Leverage the HTML5 validation w/ ajax. Have to submit to get em. Wont actually submit cuz form
  //has .validateDontSubmit class
  var $theForm = $(this).closest('form');
  //Some browsers don't implement checkValidity
  if (( typeof($theForm[0].checkValidity) == "function" ) && !$theForm[0].checkValidity()) {
     return;
  }

  //if you've gotten here - play on playa'
});

Few notes here:

  • I have noticed that you don't have to actually submit the form for validation to occur - the call to checkValidity() is enough (at least in chrome). If others could add comments with testing this theory on other browsers I'll update this answer.
  • The thing that triggers the validation does not have to be within the <form>. This was just a clean and flexible way to have a general purpose solution..

Shell script "for" loop syntax

Brace expansion, {x..y} is performed before other expansions, so you cannot use that for variable length sequences.

Instead, use the seq 2 $max method as user mob stated.

So, for your example it would be:

max=10
for i in `seq 2 $max`
do
    echo "$i"
done

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

For me the code:

_x000D_
_x000D_
<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
_x000D_
_x000D_

throws error, but I added name attribute to input:

_x000D_
_x000D_
<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text" name="text">_x000D_
</form>
_x000D_
_x000D_
_x000D_

and it started to work.

REST / SOAP endpoints for a WCF service

This is what i did to make it work. Make sure you put
webHttp automaticFormatSelectionEnabled="true" inside endpoint behaviour.

[ServiceContract]
public interface ITestService
{

    [WebGet(BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/product", ResponseFormat = WebMessageFormat.Json)]
    string GetData();
}

public class TestService : ITestService
{
    public string GetJsonData()
    {
        return "I am good...";
    }
}

Inside service model

   <service name="TechCity.Business.TestService">

    <endpoint address="soap" binding="basicHttpBinding" name="SoapTest"
      bindingName="BasicSoap" contract="TechCity.Interfaces.ITestService" />
    <endpoint address="mex"
              contract="IMetadataExchange" binding="mexHttpBinding"/>
    <endpoint behaviorConfiguration="jsonBehavior" binding="webHttpBinding"
              name="Http" contract="TechCity.Interfaces.ITestService" />
    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8739/test" />
      </baseAddresses>
    </host>
  </service>

EndPoint Behaviour

  <endpointBehaviors>
    <behavior name="jsonBehavior">
      <webHttp automaticFormatSelectionEnabled="true"  />
      <!-- use JSON serialization -->
    </behavior>
  </endpointBehaviors>

What does the @ symbol before a variable name mean in C#?

The @ symbol allows you to use reserved word. For example:

int @class = 15;

The above works, when the below wouldn't:

int class = 15;

A completely free agile software process tool

EDIT: Kanbanize is a commercial product and offers a 30 day free trial.

Disclosing: I am a co-founder of http://kanbanize.com/

Mark, I understand your desire to find the perfect application with all these features inside, but I really doubt that you will get it for free. There's a bunch of super cool apps (including Kanbanize) out there, but none of them is completely free.

Be careful what you call a Kanban board and what not, though. Trello is definitely NOT a kanban system (no WIP limits, no analytics, etc.). It is a great visual management system, but not a Kanban one.

Finally, to answer your question, tools that deserve attention in my opinion are: Kanbanize (of course), LeanKit, KanbanTool, Kanbanery and probably a few others. My personal bias is that LeanKit is the most advanced to date followed by Kanbanize and KanbanTool.

I hope that helps.

On Windows, running "import tensorflow" generates No module named "_pywrap_tensorflow" error

Dll not found. Install Visual C++ 2015 redistributable to fix.

How to instantiate a javascript class in another js file?

Possible Suggestions to make it work:

Some modifications (U forgot to include a semicolon in the statement this.getName=function(){...} it should be this.getName=function(){...};)

function Customer(){
this.name="Jhon";
this.getName=function(){
return this.name;
};
}

(This might be one of the problem.)

and

Make sure U Link the JS files in the correct order

<script src="file1.js" type="text/javascript"></script>
<script src="file2.js" type="text/javascript"></script>

How to find out if an installed Eclipse is 32 or 64 bit version?

In Linux, run file on the Eclipse executable, like this:

$ file /usr/bin/eclipse
eclipse: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.4.0, not stripped

Why should I use a container div in HTML?

The most common reasons for me are so that:

  1. The layout can have a fixed width (yes, I know, I do a lot of work for designers who love fixed widths), and
  2. So the layout can be centered by applying text-align: center to the body and then margin: auto to the left and right of the container div.

Reading in double values with scanf in c

Use the %lf format specifier to read a double:

double a;
scanf("%lf",&a);

Wikipedia has a decent reference for available format specifiers.

You'll need to use the %lf format specifier to print out the results as well:

printf("%lf %lf",a,b);

How do I copy a range of formula values and paste them to a specific range in another sheet?

You can change

Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)

to

Range("B3:B65536").Copy 
Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues

BTW, if you have xls file (excel 2003), you would get an error if your lastrow would be greater 3.

Try to use this code instead:

Sub Get_Data()
    Dim lastrowDB As Long, lastrow As Long
    Dim arr1, arr2, i As Integer

    With Sheets("DB")
        lastrowDB = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
    End With

    arr1 = Array("B", "C", "D", "E", "F", "AH", "AI", "AJ", "J", "P", "AF")
    arr2 = Array("B", "A", "C", "P", "D", "E", "G", "F", "H", "I", "J")

    For i = LBound(arr1) To UBound(arr1)
        With Sheets("Sheet1")
             lastrow = Application.Max(3, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
             .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
             Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
        End With
    Next
    Application.CutCopyMode = False
End Sub

Note, above code determines last non empty row on DB sheet in column A (variable lastrowDB). If you need to find lastrow for each destination column in DB sheet, use next modification:

For i = LBound(arr1) To UBound(arr1)
   With Sheets("DB")
       lastrowDB = .Cells(.Rows.Count, arr2(i)).End(xlUp).Row + 1
   End With

   ' NEXT CODE

Next

You could also use next approach instead Copy/PasteSpecial. Replace

.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues

with

Sheets("DB").Range(arr2(i) & lastrowDB).Resize(lastrow - 2).Value = _
      .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Value

How to populate HTML dropdown list with values from database

<?php
 $query = "select username from users";
 $res = mysqli_query($connection, $query);   
?>


<form>
  <select>
     <?php
       while ($row = $res->fetch_assoc()) 
       {
         echo '<option value=" '.$row['id'].' "> '.$row['name'].' </option>';
       }
    ?>
  </select>
</form>

How to delete columns in pyspark dataframe

Maybe a little bit off topic, but here is the solution using Scala. Make an Array of column names from your oldDataFrame and delete the columns that you want to drop ("colExclude"). Then pass the Array[Column] to select and unpack it.

val columnsToKeep: Array[Column] = oldDataFrame.columns.diff(Array("colExclude"))
                                               .map(x => oldDataFrame.col(x))
val newDataFrame: DataFrame = oldDataFrame.select(columnsToKeep: _*)

Breaking out of a for loop in Java

public class Test {

public static void main(String args[]) {

  for(int x = 10; x < 20; x = x+1) {
     if(x==15)
         break;
     System.out.print("value of x : " + x );
     System.out.print("\n");
  }
}
}

Why specify @charset "UTF-8"; in your CSS file?

If you're putting a <meta> tag in your css files, you're doing something wrong. The <meta> tag belongs in your html files, and tells the browser how the html is encoded, it doesn't say anything about the css, which is a separate file. You could conceivably have completely different encodings for your html and css, although I can't imagine this would be a good idea.

Specify a Root Path of your HTML directory for script links?

Use two periods before /, example:

../style.css

load iframe in bootstrap modal

$('.modal').on('shown.bs.modal',function(){      //correct here use 'shown.bs.modal' event which comes in bootstrap3
  $(this).find('iframe').attr('src','http://www.google.com')
})

As shown above use 'shown.bs.modal' event which comes in bootstrap 3.

EDIT :-

and just try to open some other url from iframe other than google.com ,it will not allow you to open google.com due to some security threats.

The reason for this is, that Google is sending an "X-Frame-Options: SAMEORIGIN" response header. This option prevents the browser from displaying iFrames that are not hosted on the same domain as the parent page.

Get underlined text with Markdown

You can wrote **_bold and italic_** and re-style it to underlined text, like this:

strong>em,
em>strong,
b>i,
i>b {
    font-style:normal;
    font-weight:normal;
    text-decoration:underline;
}

How to disable auto-play for local video in iframe

Replace the iframe for this:

<video class="video-fluid z-depth-1" loop controls muted>
  <source src="videos/example.mp4" type="video/mp4" />
</video>

How can I make the contents of a fixed element scrollable only when it exceeds the height of the viewport?

Try this on your position:fixed element.

overflow-y: scroll;
max-height: 100%;

How can you export the Visual Studio Code extension list?

Dump extensions:

code --list-extensions > extensions.txt

Install extensions with Bash (Linux, OS X and WSL):

cat extensions.txt | xargs code --list-extensions {}

Install extensions on Windows with PowerShell:

cat extensions.txt |% { code --install-extension $_}

Format an Integer using Java String Format

String.format("%03d", 1)  // => "001"
//              ¦¦¦   +-- print the number one
//              ¦¦+------ ... as a decimal integer
//              ¦+------- ... minimum of 3 characters wide
//              +-------- ... pad with zeroes instead of spaces

See java.util.Formatter for more information.

What’s the difference between Response.Write() andResponse.Output.Write()?

Response.write() is used to display the normal text and Response.output.write() is used to display the formated text.

How to find a Java Memory Leak

NetBeans has a built-in profiler.

How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?

It seems like you can also use the patch command. Put the diff in the root of the repository and run patch from the command line.

patch -i yourcoworkers.diff

or

patch -p0 -i yourcoworkers.diff

You may need to remove the leading folder structure if they created the diff without using --no-prefix.

If so, then you can remove the parts of the folder that don't apply using:

patch -p1 -i yourcoworkers.diff

The -p(n) signifies how many parts of the folder structure to remove.

More information on creating and applying patches here.

You can also use

git apply yourcoworkers.diff --stat 

to see if the diff by default will apply any changes. It may say 0 files affected if the patch is not applied correctly (different folder structure).

What is the best way to merge mp3 files?

As Thomas Owens pointed out, simply concatenating the files will leave multiple ID3 headers scattered throughout the resulting concatenated file - so the time/bitrate info will be wildly wrong.

You're going to need to use a tool which can combine the audio data for you.

mp3wrap would be ideal for this - it's designed to join together MP3 files, without needing to decode + re-encode the data (which would result in a loss of audio quality) and will also deal with the ID3 tags intelligently.

The resulting file can also be split back into its component parts using the mp3splt tool - mp3wrap adds information to the IDv3 comment to allow this.

Regex AND operator

Maybe just an OR operator | could be enough for your problem:

String: foo,bar,baz

Regex: (foo)|(baz)

Result: ["foo", "baz"]

What does the function then() mean in JavaScript?

doSome("task")must be returning a promise object , and that promise always have a then function .So your code is just like this

promise.then(function(env) {
    // logic
}); 

and you know this is just an ordinary call to member function .

How to convert jsonString to JSONObject in Java

No need to use any external library.

You can use this class instead :) (handles even lists , nested lists and json)

public class Utility {

    public static Map<String, Object> jsonToMap(Object json) throws JSONException {

        if(json instanceof JSONObject)
            return _jsonToMap_((JSONObject)json) ;

        else if (json instanceof String)
        {
            JSONObject jsonObject = new JSONObject((String)json) ;
            return _jsonToMap_(jsonObject) ;
        }
        return null ;
    }


   private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
        Map<String, Object> retMap = new HashMap<String, Object>();

        if(json != JSONObject.NULL) {
            retMap = toMap(json);
        }
        return retMap;
    }


    private static Map<String, Object> toMap(JSONObject object) throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();

        Iterator<String> keysItr = object.keys();
        while(keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = object.get(key);

            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            map.put(key, value);
        }
        return map;
    }


    public static List<Object> toList(JSONArray array) throws JSONException {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            list.add(value);
        }
        return list;
    }
}

To convert your JSON string to hashmap use this :

HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(

Check if PHP-page is accessed from an iOS device

<?php
$iPhone = false;
$AndroidPhone = false;
$deviceType = 0;

$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
print "<br>".$ua;

if(strpos($ua,"iphone") !== false ){
    $iPhone = true;
}
if(strpos($ua,"android") !== false){

    if(strpos($_SERVER['HTTP_USER_AGENT'],"mobile")){
        $AndroidPhone = true;        
    }
}
if(stripos($_SERVER['HTTP_USER_AGENT'],"iPad")){
    $iPad = true;
    $Tablet = true;
    $iOS = true;
}   

if($AndroidPhone==true || $iPhone==true)
{
    $deviceType = 1;
}
?>

converting numbers in to words C#

When I had to solve this problem, I created a hard-coded data dictionary to map between numbers and their associated words. For example, the following might represent a few entries in the dictionary:

{1, "one"}
{2, "two"}
{30, "thirty"}

You really only need to worry about mapping numbers in the 10^0 (1,2,3, etc.) and 10^1 (10,20,30) positions because once you get to 100, you simply have to know when to use words like hundred, thousand, million, etc. in combination with your map. For example, when you have a number like 3,240,123, you get: three million two hundred forty thousand one hundred twenty three.

After you build your map, you need to work through each digit in your number and figure out the appropriate nomenclature to go with it.

UIAlertView first deprecated IOS 9

From iOS8 Apple provide new UIAlertController class which you can use instead of UIAlertView which is now deprecated, it is also stated in deprecation message:

UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead

So you should use something like this

UIAlertController * alert = [UIAlertController
                alertControllerWithTitle:@"Title"
                                 message:@"Message"
                          preferredStyle:UIAlertControllerStyleAlert];



UIAlertAction* yesButton = [UIAlertAction
                    actionWithTitle:@"Yes, please"
                              style:UIAlertActionStyleDefault
                            handler:^(UIAlertAction * action) {
                                //Handle your yes please button action here
                            }];

UIAlertAction* noButton = [UIAlertAction
                        actionWithTitle:@"No, thanks"
                                  style:UIAlertActionStyleDefault
                                handler:^(UIAlertAction * action) {
                                   //Handle no, thanks button                
                                }];

[alert addAction:yesButton];
[alert addAction:noButton];

[self presentViewController:alert animated:YES completion:nil];

Failed to load resource: the server responded with a status of 404 (Not Found)

Add this to your Configuration file. Then put all your resources(eg. img,css,js etc) into the src > main > webapp > resources directory.

public class Config extends WebMvcConfigurerAdapter{
   @Override
   public void addResourceHandlers(ResourceHandlerRegistry registry) {  
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
   }
}

After this, you can access your resources like this.

<link href="${pageContext.request.contextPath}/resources/assets/css/demo.css" rel="stylesheet" />

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

The whole point of a class is that you create an instance, and that instance encapsulates a set of data. So it's wrong to say that your variables are global within the scope of the class: say rather that an instance holds attributes, and that instance can refer to its own attributes in any of its code (via self.whatever). Similarly, any other code given an instance can use that instance to access the instance's attributes - ie instance.whatever.

How to set xlim and ylim for a subplot in matplotlib

You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.* function are thin wrappers that basically do gca().*.

plt.subplot returns an axes object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.

import matplotlib.pyplot as plt

ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])


ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])

and so on for as many axes as you want.

or better, wrap it all up in a loop:

import matplotlib.pyplot as plt

DATA_x = ([1, 2],
          [2, 3],
          [3, 4])

DATA_y = DATA_x[::-1]

XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3

for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
    ax = plt.subplot(1, 3, j + 1)
    ax.scatter(x, y)
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

Bootstrap Alert Auto Close

C# Controller:

var result = await _roleManager.CreateAsync(identityRole);
   if (result.Succeeded == true)
       TempData["roleCreateAlert"] = "Added record successfully";

Razor Page:

@if (TempData["roleCreateAlert"] != null)
{
    <div class="alert alert-success">
        <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
        <p>@TempData["roleCreateAlert"]</p>
    </div>
}

Any Alert Auto Close:

<script type="text/javascript">
    $(".alert").delay(5000).slideUp(200, function () {
        $(this).alert('close');
    });
</script>

Cannot use special principal dbo: Error 15405

Fix: Cannot use the special principal ‘sa’. Microsoft SQL Server, Error: 15405

When importing a database in your SQL instance you would find yourself with Cannot use the special principal 'sa'. Microsoft SQL Server, Error: 15405 popping out when setting the sa user as the DBO of the database. To fix this, Open SQL Management Studio and Click New Query. Type:

USE mydatabase
exec sp_changedbowner 'sa', 'true'

Close the new query and after viewing the security of the sa, you will find that that sa is the DBO of the database. (14444)

Source: http://www.noelpulis.com/fix-cannot-use-the-special-principal-sa-microsoft-sql-server-error-15405/

ASP.NET MVC DropDownListFor with model of type List<string>

I realize this question was asked a long time ago, but I came here looking for answers and wasn't satisfied with anything I could find. I finally found the answer here:

https://www.tutorialsteacher.com/mvc/htmlhelper-dropdownlist-dropdownlistfor

To get the results from the form, use the FormCollection and then pull each individual value out by it's model name thus:

yourRecord.FieldName = Request.Form["FieldNameInModel"];

As far as I could tell it makes absolutely no difference what argument name you give to the FormCollection - use Request.Form["NameFromModel"] to retrieve it.

No, I did not dig down to see how th4e magic works under the covers. I just know it works...

I hope this helps somebody avoid the hours I spent trying different approaches before I got it working.

Find duplicates and delete all in notepad++

If it is possible to change the sequence of the lines you could do:

  1. sort line with Edit -> Line Operations -> Sort Lines Lexicographically ascending
  2. do a Find / Replace:
    • Find What: ^(.*\r?\n)\1+
    • Replace with: (Nothing, leave empty)
    • Check Regular Expression in the lower left
    • Click Replace All

How it works: The sorting puts the duplicates behind each other. The find matches a line ^(.*\r?\n) and captures the line in \1 then it continues and tries to find \1 one or more times (+) behind the first match. Such a block of duplicates (if it exists) is replaced with nothing.

The \r?\n should deal nicely with Windows and Unix lineendings.

Styling HTML5 input type number

Also you can replace size attribute by a style attribute:
<input type="number" name="numericInput" style="width: 50px;" min="0" max="18" value="0" />

AngularJS ng-click to go to another page (with Ionic framework)

Based on comments, and due to the fact that @Thinkerer (the OP - original poster) created a plunker for this case, I decided to append another answer with more details.

The first and important change:

// instead of this
$urlRouterProvider.otherwise('/tab/post');

// we have to use this
$urlRouterProvider.otherwise('/tab/posts');

because the states definition is:

.state('tab', {
  url: "/tab",
  abstract: true,
  templateUrl: 'tabs.html'
})

.state('tab.posts', {
  url: '/posts',
  views: {
    'tab-posts': {
      templateUrl: 'tab-posts.html',
      controller: 'PostsCtrl'
    }
  }
})

and we need their concatenated url '/tab' + '/posts'. That's the url we want to use as a otherwise

The rest of the application is really close to the result we need...
E.g. we stil have to place the content into same view targetgood, just these were changed:

.state('tab.newpost', {
  url: '/newpost',
  views: {
    // 'tab-newpost': {
    'tab-posts': {
      templateUrl: 'tab-newpost.html',
      controller: 'NavCtrl'
    }
  }

because .state('tab.newpost' would be replacing the .state('tab.posts' we have to place it into the same anchor:

<ion-nav-view name="tab-posts"></ion-nav-view>  

Finally some adjustments in controllers:

$scope.create = function() {
    $state.go('tab.newpost');
};
$scope.close = function() { 
     $state.go('tab.posts'); 
};

As I already said in my previous answer and comments ... the $state.go() is the only right way how to use ionic or ui-router

Check that all here Final note - I made running just navigation between tab.posts... tab.newpost... the rest would be similar

SQL multiple column ordering

SELECT  *
FROM    mytable
ORDER BY
        column1 DESC, column2 ASC

Assigning more than one class for one event

Have you tried this:

 function doSomething() {
     if ($(this).hasClass('clickedTag')){
         // code here
     } else {
         // and here
     }
 }

 $('.tag1, .tag2').click(doSomething);

How to add leading zeros?

Here's a generalizable base R function:

pad_left <- function(x, len = 1 + max(nchar(x)), char = '0'){

    unlist(lapply(x, function(x) {
        paste0(
            paste(rep(char, len - nchar(x)), collapse = ''),
            x
        )
    }))
}

pad_left(1:100)

I like sprintf but it comes with caveats like:

however the actual implementation will follow the C99 standard and fine details (especially the behaviour under user error) may depend on the platform

Kubernetes how to make Deployment to update image

I am using Azure DevOps to deploy the containerize applications, I am easily manage to overcome this problem by using the build ID

Everytime its builds and generate the new Build ID, I use this build ID as tag for docker image here is example

imagename:buildID

once your image is build (CI) successfully, in CD pipeline in deployment yml file I have give image name as

imagename:env:buildID

here evn:buildid is the azure devops variable which having value of build ID.

so now every time I have new changes to build(CI) and deploy(CD).

please comment if you need build definition for CI/CD.

What is the Ruby <=> (spaceship) operator?

I will explain with simple example

  1. [1,3,2] <=> [2,2,2]

    Ruby will start comparing each element of both array from left hand side. 1 for left array is smaller than 2 of right array. Hence left array is smaller than right array. Output will be -1.

  2. [2,3,2] <=> [2,2,2]

    As above it will first compare first element which are equal then it will compare second element, in this case second element of left array is greater hence output is 1.

How to check if a character is upper-case in Python?

Maybe you want str.istitle

>>> help(str.istitle)
Help on method_descriptor:

istitle(...)
    S.istitle() -> bool

    Return True if S is a titlecased string and there is at least one
    character in S, i.e. uppercase characters may only follow uncased
    characters and lowercase characters only cased ones. Return False
    otherwise.

>>> "Alpha_beta_Gamma".istitle()
False
>>> "Alpha_Beta_Gamma".istitle()
True
>>> "Alpha_Beta_GAmma".istitle()
False

An efficient way to Base64 encode a byte array?

Based on your edit and comments.. would this be what you're after?

byte[] newByteArray = UTF8Encoding.UTF8.GetBytes(Convert.ToBase64String(currentByteArray));

How to pre-populate the sms body text via an html link

It turns out this is 100% possible, though a little hacky.

If you want it to work on Android you need to use this format:

<a href="sms:/* phone number here */?body=/* body text here */">Link</a>

If you want it to work on iOS, you need this:

<a href="sms:/* phone number here */;body=/* body text here */">Link</a>

Live demo here: http://bradorego.com/test/sms.html (note the "Phone and ?body" and "Phone and ;body" should autofill both the to: field and the body text. View the source for more info)

UPDATE:

Apparently iOS8 had to go and change things on us, so thanks to some of the other commenters/responders, there's a new style for iOS:

<a href="sms:/* phone number here */&body=/* body text here */">Link</a>

(phone number is optional)

Package structure for a Java project?

I usually like to have the following:

  • bin (Binaries)
  • doc (Documents)
  • inf (Information)
  • lib (Libraries)
  • res (Resources)
  • src (Source)
  • tst (Test)

These may be considered unconventional, but I find it to be a very nice way to organize things.

Constructors in JavaScript objects

They do if you use Typescript - open source from MicroSoft :-)

class BankAccount {
 balance: number;
 constructor(initially: number) {
 this.balance = initially;
 }
 deposit(credit: number) {
 this.balance += credit;
 return this.balance;
 }
}

Typescript lets you 'fake' OO constructs that are compiled into javascript constructs. If you're starting a large project it may save you a lot of time and it just reached milestone 1.0 version.

http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf

The above code gets 'compiled' to :

var BankAccount = (function () {
    function BankAccount(initially) {
        this.balance = initially;
    }
    BankAccount.prototype.deposit = function (credit) {
        this.balance += credit;
        return this.balance;
    };
    return BankAccount;
})();

Is it possible to declare two variables of different types in a for loop?

No - but technically there is a work-around (not that i'd actually use it unless forced to):

for(struct { int a; char b; } s = { 0, 'a' } ; s.a < 5 ; ++s.a) 
{
    std::cout << s.a << " " << s.b << std::endl;
}

What is a singleton in C#?

I know it's very late to answer the question but with Auto-Property you can do something like that:

public static Singleton Instance { get; } = new Singleton();

Where Singleton is you class and can be via, in this case the readonly property Instance.

How to get the caller class in Java

Find below a simple example illustrating how to get class and method names.

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

   void callMe()
   {
      try
      {
         throw new Exception("Who called me?");
      }
      catch( Exception e )
      {
         System.out.println( "I was called by " + 
                             e.getStackTrace()[1].getClassName() + 
                             "." +
                             e.getStackTrace()[1].getMethodName() + 
                             "()!" );
      }
   }

e has getClassName(), getFileName(), getLineNumber() and getMethodName()...

Move branch pointer to different commit without checkout

You can do it for arbitrary refs. This is how to move a branch pointer:

git update-ref -m "reset: Reset <branch> to <new commit>" refs/heads/<branch> <commit>

where -m adds a message to the reflog for the branch.

The general form is

git update-ref -m "reset: Reset <branch> to <new commit>" <ref> <commit>

You can pick nits about the reflog message if you like - I believe the branch -f one is different from the reset --hard one, and this isn't exactly either of them.

Android: long click on a button -> perform actions

To get both functions working for a clickable image that will respond to both short and long clicks, I tried the following that seems to work perfectly:

    image = (ImageView) findViewById(R.id.imageViewCompass);
    image.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            shortclick();
        }
     });

    image.setOnLongClickListener(new View.OnLongClickListener() {
    public boolean onLongClick(View v) {
        longclick();
        return true;
    }
});

//Then the functions that are called:

 public void shortclick()
{
 Toast.makeText(this, "Why did you do that? That hurts!!!", Toast.LENGTH_LONG).show();

}

 public void longclick()
{
 Toast.makeText(this, "Why did you do that? That REALLY hurts!!!", Toast.LENGTH_LONG).show();

}

It seems that the easy way of declaring the item in XML as clickable and then defining a function to call on the click only applies to short clicks - you must have a listener to differentiate between short and long clicks.

Python 'list indices must be integers, not tuple"

The problem is that [...] in python has two distinct meanings

  1. expr [ index ] means accessing an element of a list
  2. [ expr1, expr2, expr3 ] means building a list of three elements from three expressions

In your code you forgot the comma between the expressions for the items in the outer list:

[ [a, b, c] [d, e, f] [g, h, i] ]

therefore Python interpreted the start of second element as an index to be applied to the first and this is what the error message is saying.

The correct syntax for what you're looking for is

[ [a, b, c], [d, e, f], [g, h, i] ]

How to use a switch case 'or' in PHP

Try

switch($value) {
    case 1:
    case 2:
        echo "the value is either 1 or 2";
        break;
}

endforeach in loops?

It's just a different syntax. Instead of

foreach ($a as $v) {
    # ...
}

You could write this:

foreach ($a as $v):
    # ...
endforeach;

They will function exactly the same; it's just a matter of style. (Personally I have never seen anyone use the second form.)

Put byte array to JSON and vice versa

Amazingly now org.json now lets you put a byte[] object directly into a json and it remains readable. you can even send the resulting object over a websocket and it will be readable on the other side. but i am not sure yet if the size of the resulting object is bigger or smaller than if you were converting your byte array to base64, it would certainly be neat if it was smaller.

It seems to be incredibly hard to measure how much space such a json object takes up in java. if your json consists merely of strings it is easily achievable by simply stringifying it but with a bytearray inside it i fear it is not as straightforward.

stringifying our json in java replaces my bytearray for a 10 character string that looks like an id. doing the same in node.js replaces our byte[] for an unquoted value reading <Buffered Array: f0 ff ff ...> the length of the latter indicates a size increase of ~300% as would be expected

What's the best way to add a full screen background image in React Native

import React, { Component } from 'react';
import { Image, StyleSheet } from 'react-native';

export default class App extends Component {
  render() {
    return (
      <Image source={{uri: 'http://i.imgur.com/IGlBYaC.jpg'}} style={s.backgroundImage} />
    );
  }
}

const s = StyleSheet.create({
  backgroundImage: {
      flex: 1,
      width: null,
      height: null,
  }
});

You can try it at: https://sketch.expo.io/B1EAShDie (from: github.com/Dorian/sketch-reactive-native-apps)

Docs: https://facebook.github.io/react-native/docs/images.html#background-image-via-nesting

Reading NFC Tags with iPhone 6 / iOS 8

The iPhone6/6s/6+ are NOT designed to read passive NFC tags (aka Discovery Mode). There's a lot of misinformation on this topic, so I thought to provide some tangible info for developers to consider. The lack of NFC tag read support is not because of software but because of hardware. To understand why, you need to understand how NFC works. NFC works by way of Load Modulation. That means that the interrogator (PCD) emits a carrier magnetic field that energizes the passive target (PICC). With the potential generated by this carrier field, the target then is able to demodulate data coming from the interrogator and respond by modulating data over top of this very same field. The key here is that the target never creates a field of its own.

If you look at the iPhone6 teardown and parts list you will see the presence of a very small NFC loop antenna as well as the use of the AS3923 booster IC. This design was intended for custom microSD or SIM cards to enable mobile phones of old to do payments. This is the type of application where the mobile phone presents a Card Emulated credential to a high power contactless POS terminal. The POS terminal acts as the reader, energizing the iPhone6 with help from the AS3923 chip. The AS3923 block diagram clearly shows how the RX and TX modulation is boosted from a signal presented by a reader device. In other words the iPhone6 is not meant to provide a field, only to react to one. That's why it's design is only meant for NFC Card Emulation and perhaps Peer-2-Peer, but definitely not tag Discovery.

AS3923 booster IC

There are some alternatives to achieving tag Discovery with an iPhone6 using HW accessories. I talk about these integrations and how developers can architect solutions in this blog post. Our low power reader designs open interesting opportunities for mobile engagement that few developers are thinking about.

Disclosure: I'm the founder of Flomio, Inc., a TechStars company that delivers proximity ID hardware, software, and services for applications ranging from access control to payments.

Update: This rumor, if true, would open up the possibility for the iPhone to practically support NFC tag Discovery mode. An all glass design would not interfere with the NFC antenna as does the metal back of the current iPhone. We've attempted this design approach --albeit with cheaper materials-- on some of our custom reader designs with success so looking forward to this improvement.

Update: iOS11 has announced support for "NFC reader mode" for iPhone7/7+. Details here. API only supports reading NDEF messages (no ISO7816 APDUs) while an app is in the foreground (no background detection). Due out in the Fall, 2017... check the screenshot from WWDC keynote:

enter image description here

node.js hash string?

function md5(a) {
    var r = 0,
        c = "";
    return h(a);

    function h(t) {
        return u(l(m(t)))
    }

    function l(t) {
        return p(g(f(t), 8 * t.length))
    }

    function u(t) {
        for (var e, i = r ? "0123456789ABCDEF" : "0123456789abcdef", n = "", o = 0; o < t.length; o++)
            e = t.charCodeAt(o),
            n += i.charAt(e >>> 4 & 15) + i.charAt(15 & e);
        return n
    }

    function m(t) {
        for (var e, i, n = "", o = -1; ++o < t.length;)
            e = t.charCodeAt(o),
            i = o + 1 < t.length ? t.charCodeAt(o + 1) : 0,
            55296 <= e && e <= 56319 && 56320 <= i && i <= 57343 && (e = 65536 + ((1023 & e) << 10) + (1023 & i),
                o++),
            e <= 127 ? n += String.fromCharCode(e) : e <= 2047 ? n += String.fromCharCode(192 | e >>> 6 & 31, 128 | 63 & e) : e <= 65535 ? n += String.fromCharCode(224 | e >>> 12 & 15, 128 | e >>> 6 & 63, 128 | 63 & e) : e <= 2097151 && (n += String.fromCharCode(240 | e >>> 18 & 7, 128 | e >>> 12 & 63, 128 | e >>> 6 & 63, 128 | 63 & e));
        return n
    }

    function f(t) {
        for (var e = Array(t.length >> 2), i = 0; i < e.length; i++)
            e[i] = 0;
        for (i = 0; i < 8 * t.length; i += 8)
            e[i >> 5] |= (255 & t.charCodeAt(i / 8)) << i % 32;
        return e
    }

    function p(t) {
        for (var e = "", i = 0; i < 32 * t.length; i += 8)
            e += String.fromCharCode(t[i >> 5] >>> i % 32 & 255);
        return e
    }

    function g(t, e) {
        t[e >> 5] |= 128 << e % 32,
            t[14 + (e + 64 >>> 9 << 4)] = e;
        for (var i = 1732584193, n = -271733879, o = -1732584194, s = 271733878, a = 0; a < t.length; a += 16) {
            var r = i,
                c = n,
                h = o,
                l = s;
            n = E(n = E(n = E(n = E(n = N(n = N(n = N(n = N(n = C(n = C(n = C(n = C(n = S(n = S(n = S(n = S(n, o = S(o, s = S(s, i = S(i, n, o, s, t[a + 0], 7, -680876936), n, o, t[a + 1], 12, -389564586), i, n, t[a + 2], 17, 606105819), s, i, t[a + 3], 22, -1044525330), o = S(o, s = S(s, i = S(i, n, o, s, t[a + 4], 7, -176418897), n, o, t[a + 5], 12, 1200080426), i, n, t[a + 6], 17, -1473231341), s, i, t[a + 7], 22, -45705983), o = S(o, s = S(s, i = S(i, n, o, s, t[a + 8], 7, 1770035416), n, o, t[a + 9], 12, -1958414417), i, n, t[a + 10], 17, -42063), s, i, t[a + 11], 22, -1990404162), o = S(o, s = S(s, i = S(i, n, o, s, t[a + 12], 7, 1804603682), n, o, t[a + 13], 12, -40341101), i, n, t[a + 14], 17, -1502002290), s, i, t[a + 15], 22, 1236535329), o = C(o, s = C(s, i = C(i, n, o, s, t[a + 1], 5, -165796510), n, o, t[a + 6], 9, -1069501632), i, n, t[a + 11], 14, 643717713), s, i, t[a + 0], 20, -373897302), o = C(o, s = C(s, i = C(i, n, o, s, t[a + 5], 5, -701558691), n, o, t[a + 10], 9, 38016083), i, n, t[a + 15], 14, -660478335), s, i, t[a + 4], 20, -405537848), o = C(o, s = C(s, i = C(i, n, o, s, t[a + 9], 5, 568446438), n, o, t[a + 14], 9, -1019803690), i, n, t[a + 3], 14, -187363961), s, i, t[a + 8], 20, 1163531501), o = C(o, s = C(s, i = C(i, n, o, s, t[a + 13], 5, -1444681467), n, o, t[a + 2], 9, -51403784), i, n, t[a + 7], 14, 1735328473), s, i, t[a + 12], 20, -1926607734), o = N(o, s = N(s, i = N(i, n, o, s, t[a + 5], 4, -378558), n, o, t[a + 8], 11, -2022574463), i, n, t[a + 11], 16, 1839030562), s, i, t[a + 14], 23, -35309556), o = N(o, s = N(s, i = N(i, n, o, s, t[a + 1], 4, -1530992060), n, o, t[a + 4], 11, 1272893353), i, n, t[a + 7], 16, -155497632), s, i, t[a + 10], 23, -1094730640), o = N(o, s = N(s, i = N(i, n, o, s, t[a + 13], 4, 681279174), n, o, t[a + 0], 11, -358537222), i, n, t[a + 3], 16, -722521979), s, i, t[a + 6], 23, 76029189), o = N(o, s = N(s, i = N(i, n, o, s, t[a + 9], 4, -640364487), n, o, t[a + 12], 11, -421815835), i, n, t[a + 15], 16, 530742520), s, i, t[a + 2], 23, -995338651), o = E(o, s = E(s, i = E(i, n, o, s, t[a + 0], 6, -198630844), n, o, t[a + 7], 10, 1126891415), i, n, t[a + 14], 15, -1416354905), s, i, t[a + 5], 21, -57434055), o = E(o, s = E(s, i = E(i, n, o, s, t[a + 12], 6, 1700485571), n, o, t[a + 3], 10, -1894986606), i, n, t[a + 10], 15, -1051523), s, i, t[a + 1], 21, -2054922799), o = E(o, s = E(s, i = E(i, n, o, s, t[a + 8], 6, 1873313359), n, o, t[a + 15], 10, -30611744), i, n, t[a + 6], 15, -1560198380), s, i, t[a + 13], 21, 1309151649), o = E(o, s = E(s, i = E(i, n, o, s, t[a + 4], 6, -145523070), n, o, t[a + 11], 10, -1120210379), i, n, t[a + 2], 15, 718787259), s, i, t[a + 9], 21, -343485551),
                i = v(i, r),
                n = v(n, c),
                o = v(o, h),
                s = v(s, l)
        }
        return [i, n, o, s]
    }

    function _(t, e, i, n, o, s) {
        return v((a = v(v(e, t), v(n, s))) << (r = o) | a >>> 32 - r, i);
        var a, r
    }

    function S(t, e, i, n, o, s, a) {
        return _(e & i | ~e & n, t, e, o, s, a)
    }

    function C(t, e, i, n, o, s, a) {
        return _(e & n | i & ~n, t, e, o, s, a)
    }

    function N(t, e, i, n, o, s, a) {
        return _(e ^ i ^ n, t, e, o, s, a)
    }

    function E(t, e, i, n, o, s, a) {
        return _(i ^ (e | ~n), t, e, o, s, a)
    }

    function v(t, e) {
        var i = (65535 & t) + (65535 & e);
        return (t >> 16) + (e >> 16) + (i >> 16) << 16 | 65535 & i
    }
}
string = 'hello';
console.log(md5(string));

Best way to copy a database (SQL Server 2008)

The detach/copy/attach method will take down the database. That's not something you'd want in production.

The backup/restore will only work if you have write permissions to the production server. I work with Amazon RDS and I don't.

The import/export method doesn't really work because of foreign keys - unless you do tables one by one in the order they reference one another. You can do an import/export to a new database. That will copy all the tables and data, but not the foreign keys.

This sounds like a common operation one needs to do with database. Why isn't SQL Server handling this properly? Every time I had to do this it was frustrating.

That being said, the only painless solution I've encountered was Sql Azure Migration Tool which is maintained by the community. It works with SQL Server too.

How to set layout_weight attribute dynamically from code?

Any of LinearLayout.LayoutParams and TableLayout.LayoutParams worked for me, for buttons the right one is TableRow.LayoutParams. That is:

            TableRow.LayoutParams buttonParams = new TableRow.LayoutParams(
                    TableRow.LayoutParams.MATCH_PARENT,
                    TableRow.LayoutParams.WRAP_CONTENT, 1f);

About using MATCH_PARENT or WRAP_CONTENT be the same.

How to get first and last day of the current week in JavaScript

This works across year and month changes.

Date.prototype.GetFirstDayOfWeek = function() {
    return (new Date(this.setDate(this.getDate() - this.getDay())));
}

Date.prototype.GetLastDayOfWeek = function() {
    return (new Date(this.setDate(this.getDate() - this.getDay() +6)));
}

var today = new Date();

alert(today.GetFirstDayOfWeek());

alert(today.GetLastDayOfWeek());

Can the Unix list command 'ls' output numerical chmod permissions?

Use this to display the Unix numerical permission values (octal values) and file name.

stat -c '%a %n' *

Use this to display the Unix numerical permission values (octal values) and the folder's sgid and sticky bit, user name of the owner, group name, total size in bytes and file name.

stat -c '%a %A %U %G %s %n' *

enter image description here

Add %y if you need time of last modification in human-readable format. For more options see stat.

Better version using an Alias

Using an alias is a more efficient way to accomplish what you need and it also includes color. The following displays your results organized by group directories first, display in color, print sizes in human readable format (e.g., 1K 234M 2G) edit your ~/.bashrc and add an alias for your account or globally by editing /etc/profile.d/custom.sh

Typing cls displays your new LS command results.

alias cls="ls -lha --color=always -F --group-directories-first |awk '{k=0;s=0;for(i=0;i<=8;i++){;k+=((substr(\$1,i+2,1)~/[rwxst]/)*2^(8-i));};j=4;for(i=4;i<=10;i+=3){;s+=((substr(\$1,i,1)~/[stST]/)*j);j/=2;};if(k){;printf(\"%0o%0o \",s,k);};print;}'"

Alias is the most efficient solution

Folder Tree

While you are editing your bashrc or custom.sh include the following alias to see a graphical representation where typing lstree will display your current folder tree structure

alias lstree="ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/   /' -e 's/-/|/'"

It would display:

   |-scripts
   |--mod_cache_disk
   |--mod_cache_d
   |---logs
   |-run_win
   |-scripts.tar.gz

What are file descriptors, explained in simple terms?

Hear it from the Horse's Mouth : APUE (Richard Stevens).
To the kernel, all open files are referred to by File Descriptors. A file descriptor is a non-negative number.

When we open an existing file or create a new file, the kernel returns a file descriptor to the process. The kernel maintains a table of all open file descriptors, which are in use. The allotment of file descriptors is generally sequential and they are allotted to the file as the next free file descriptor from the pool of free file descriptors. When we closes the file, the file descriptor gets freed and is available for further allotment.
See this image for more details :

Two Process

When we want to read or write a file, we identify the file with the file descriptor that was returned by open() or create() function call, and use it as an argument to either read() or write().
It is by convention that, UNIX System shells associates the file descriptor 0 with Standard Input of a process, file descriptor 1 with Standard Output, and file descriptor 2 with Standard Error.
File descriptor ranges from 0 to OPEN_MAX. File descriptor max value can be obtained with ulimit -n. For more information, go through 3rd chapter of APUE Book.

React-Router External link

You can now link to an external site using React Link by providing an object to to with the pathname key:

<Link to={ { pathname: '//example.zendesk.com/hc/en-us/articles/123456789-Privacy-Policies' } } >

If you find that you need to use JS to generate the link in a callback, you can use window.location.replace() or window.location.assign().

Over using window.location.replace(), as other good answers suggest, try using window.location.assign().

window.location.replace() will replace the location history without preserving the current page.

window.location.assign() will transition to the url specified, but will save the previous page in the browser history, allowing proper back-button functionality.

https://developer.mozilla.org/en-US/docs/Web/API/Location/replace https://developer.mozilla.org/en-US/docs/Web/API/Location/assign

Also, if you are using a window.location = url method as mentioned in other answers, I highly suggest switching to window.location.href = url. There is a heavy argument about it, where many users seem to adamantly want to revert the newer object type window.location to its original implementation as string merely because they can (and they egregiously attack anyone who says otherwise), but you could theoretically interrupt other library functionality accessing the window.location object.

Check out this convo. It's terrible. Javascript: Setting location.href versus location

Adding a Method to an Existing Object Instance

Module new is deprecated since python 2.6 and removed in 3.0, use types

see http://docs.python.org/library/new.html

In the example below I've deliberately removed return value from patch_me() function. I think that giving return value may make one believe that patch returns a new object, which is not true - it modifies the incoming one. Probably this can facilitate a more disciplined use of monkeypatching.

import types

class A(object):#but seems to work for old style objects too
    pass

def patch_me(target):
    def method(target,x):
        print "x=",x
        print "called from", target
    target.method = types.MethodType(method,target)
    #add more if needed

a = A()
print a
#out: <__main__.A object at 0x2b73ac88bfd0>  
patch_me(a)    #patch instance
a.method(5)
#out: x= 5
#out: called from <__main__.A object at 0x2b73ac88bfd0>
patch_me(A)
A.method(6)        #can patch class too
#out: x= 6
#out: called from <class '__main__.A'>

Limit on the WHERE col IN (...) condition

Depending on your version, use a table valued parameter in 2008, or some approach described here:

Arrays and Lists in SQL Server 2005

Android XML Percent Symbol

Try using a backslash in front of it, like below:

\%

How to specify the private SSH-key to use when executing shell command on Git?

If none of the other solutions here work for you, and you have created multiple ssh-keys, but still cannot do simple things like

git pull

then assuming you have two ssh key files like

id_rsa
id_rsa_other_key

then inside of the git repo, try:

# Run these commands INSIDE your git directory
eval `ssh-agent -s`
ssh-add ~/.ssh/id_rsa
ssh-add ~/.ssh/id_rsa_other_key

and also make sure your github default username and userid are correct by:

# Run these commands INSIDE your git directory
git config user.name "Mona Lisa"
git config user.email "[email protected]"

See https://gist.github.com/jexchan/2351996 for more more information.

How to get character array from a string?

simple answer:

_x000D_
_x000D_
let str = 'this is string, length is >26';_x000D_
_x000D_
console.log([...str]);
_x000D_
_x000D_
_x000D_

How can I select all children of an element except the last child?

to find elements from last, use

<style>
ul li:nth-last-of-type(3n){ color:#a94442}  /**/
</style>

How to replace sql field value

You could just use REPLACE:

UPDATE myTable SET emailCol = REPLACE(emailCol, '.com', '.org')`.

But take into account an email address such as [email protected] will be updated to [email protected].

If you want to be on a safer side, you should check for the last 4 characters using RIGHT, and append .org to the SUBSTRING manually instead. Notice the usage of UPPER to make the search for the .com ending case insensitive.

UPDATE myTable 
SET emailCol = SUBSTRING(emailCol, 1, LEN(emailCol)-4) + '.org'
WHERE UPPER(RIGHT(emailCol,4)) = '.COM';

See it working in this SQLFiddle.

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

Try this:

 >>> f = open('goodlines.txt')
 >>> mylist = f.readlines()

open() function returns a file object. And for file object, there is no method like splitlines() or split(). You could use dir(f) to see all the methods of file object.

Change text color with Javascript?

innerHTML is a string representing the contents of the element.

You want to modify the element itself. Drop the .innerHTML part.

How to open my files in data_folder with pandas using relative path?

Keeping things tidy with f-strings:

import os
import pandas as pd

data_files = '../data_folder/'
csv_name = 'data.csv'

pd.read_csv(f"{data_files}{csv_name}")

Why does z-index not work?

The z-index property only works on elements with a position value other than static (e.g. position: absolute;, position: relative;, or position: fixed).

There is also position: sticky; that is supported in Firefox, is prefixed in Safari, worked for a time in older versions of Chrome under a custom flag, and is under consideration by Microsoft to add to their Edge browser.

Important
For regular positioning, be sure to include position: relative on the elements where you also set the z-index. Otherwise, it won't take effect.

What is an .axd file?

from Google

An .axd file is a HTTP Handler file. There are two types of .axd files.

  1. ScriptResource.axd
  2. WebResource.axd

These are files which are generated at runtime whenever you use ScriptManager in your Web app. This is being generated only once when you deploy it on the server.

Simply put the ScriptResource.AXD contains all of the clientside javascript routines for Ajax. Just because you include a scriptmanager that loads a script file it will never appear as a ScriptResource.AXD - instead it will be merely passed as the .js file you send if you reference a external script file. If you embed it in code then it may merely appear as part of the html as a tag and code but depending if you code according to how the ToolKit handles it - may or may not appear as as a ScriptResource.axd. ScriptResource.axd is only introduced with AJAX and you will never see it elsewhere

And ofcourse it is necessary

SQL not a single-group group function

Well the problem simply-put is that the SUM(TIME) for a specific SSN on your query is a single value, so it's objecting to MAX as it makes no sense (The maximum of a single value is meaningless).

Not sure what SQL database server you're using but I suspect you want a query more like this (Written with a MSSQL background - may need some translating to the sql server you're using):

SELECT TOP 1 SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
ORDER BY 2 DESC

This will give you the SSN with the highest total time and the total time for it.

Edit - If you have multiple with an equal time and want them all you would use:

SELECT
SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
HAVING SUM(TIME)=(SELECT MAX(SUM(TIME)) FROM downloads GROUP BY SSN))

Overloading operators in typedef structs (c++)

The breakdown of your declaration and its members is somewhat littered:

Remove the typedef

The typedef is neither required, not desired for class/struct declarations in C++. Your members have no knowledge of the declaration of pos as-written, which is core to your current compilation failure.

Change this:

typedef struct {....} pos;

To this:

struct pos { ... };

Remove extraneous inlines

You're both declaring and defining your member operators within the class definition itself. The inline keyword is not needed so long as your implementations remain in their current location (the class definition)


Return references to *this where appropriate

This is related to an abundance of copy-constructions within your implementation that should not be done without a strong reason for doing so. It is related to the expression ideology of the following:

a = b = c;

This assigns c to b, and the resulting value b is then assigned to a. This is not equivalent to the following code, contrary to what you may think:

a = c;
b = c;

Therefore, your assignment operator should be implemented as such:

pos& operator =(const pos& a)
{
    x = a.x;
    y = a.y;
    return *this;
}

Even here, this is not needed. The default copy-assignment operator will do the above for you free of charge (and code! woot!)

Note: there are times where the above should be avoided in favor of the copy/swap idiom. Though not needed for this specific case, it may look like this:

pos& operator=(pos a) // by-value param invokes class copy-ctor
{
    this->swap(a);
    return *this;
}

Then a swap method is implemented:

void pos::swap(pos& obj)
{
    // TODO: swap object guts with obj
}

You do this to utilize the class copy-ctor to make a copy, then utilize exception-safe swapping to perform the exchange. The result is the incoming copy departs (and destroys) your object's old guts, while your object assumes ownership of there's. Read more the copy/swap idiom here, along with the pros and cons therein.


Pass objects by const reference when appropriate

All of your input parameters to all of your members are currently making copies of whatever is being passed at invoke. While it may be trivial for code like this, it can be very expensive for larger object types. An exampleis given here:

Change this:

bool operator==(pos a) const{
    if(a.x==x && a.y== y)return true;
    else return false;
}

To this: (also simplified)

bool operator==(const pos& a) const
{
    return (x == a.x && y == a.y);
}

No copies of anything are made, resulting in more efficient code.


Finally, in answering your question, what is the difference between a member function or operator declared as const and one that is not?

A const member declares that invoking that member will not modifying the underlying object (mutable declarations not withstanding). Only const member functions can be invoked against const objects, or const references and pointers. For example, your operator +() does not modify your local object and thus should be declared as const. Your operator =() clearly modifies the local object, and therefore the operator should not be const.


Summary

struct pos
{
    int x;
    int y;

    // default + parameterized constructor
    pos(int x=0, int y=0) 
        : x(x), y(y)
    {
    }

    // assignment operator modifies object, therefore non-const
    pos& operator=(const pos& a)
    {
        x=a.x;
        y=a.y;
        return *this;
    }

    // addop. doesn't modify object. therefore const.
    pos operator+(const pos& a) const
    {
        return pos(a.x+x, a.y+y);
    }

    // equality comparison. doesn't modify object. therefore const.
    bool operator==(const pos& a) const
    {
        return (x == a.x && y == a.y);
    }
};

EDIT OP wanted to see how an assignment operator chain works. The following demonstrates how this:

a = b = c;

Is equivalent to this:

b = c;
a = b;

And that this does not always equate to this:

a = c;
b = c;

Sample code:

#include <iostream>
#include <string>
using namespace std;

struct obj
{
    std::string name;
    int value;

    obj(const std::string& name, int value)
        : name(name), value(value)
    {
    }

    obj& operator =(const obj& o)
    {
        cout << name << " = " << o.name << endl;
        value = (o.value+1); // note: our value is one more than the rhs.
        return *this;
    }    
};

int main(int argc, char *argv[])
{

    obj a("a", 1), b("b", 2), c("c", 3);

    a = b = c;
    cout << "a.value = " << a.value << endl;
    cout << "b.value = " << b.value << endl;
    cout << "c.value = " << c.value << endl;

    a = c;
    b = c;
    cout << "a.value = " << a.value << endl;
    cout << "b.value = " << b.value << endl;
    cout << "c.value = " << c.value << endl;

    return 0;
}

Output

b = c
a = b
a.value = 5
b.value = 4
c.value = 3
a = c
b = c
a.value = 4
b.value = 4
c.value = 3