Programs & Examples On #Email spam

Spam is the use of electronic messaging systems to send unsolicited bulk messages indiscriminately.

sending email via php mail function goes to spam

Try changing your headers to this:

$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= "From: [email protected]" . "\r\n" .
"Reply-To: [email protected]" . "\r\n" .
"X-Mailer: PHP/" . phpversion();

For a few reasons.

  • One of which is the need of a Reply-To and,

  • The use of apostrophes instead of double-quotes. Those two things in my experience with forms, is usually what triggers a message ending up in the Spam box.

You could also try changing the $from to:

$from = "[email protected]";


EDIT:

See these links I found on the subject https://stackoverflow.com/a/9988544/1415724 and https://stackoverflow.com/a/16717647/1415724 and https://stackoverflow.com/a/9899837/1415724

https://stackoverflow.com/a/5944155/1415724 and https://stackoverflow.com/a/6532320/1415724

  • Try using the SMTP server of your ISP.

    Using this apparently worked for many: X-MSMail-Priority: High

http://www.webhostingtalk.com/showthread.php?t=931932

"My host helped me to enable DomainKeys and SPF Records on my domain and now when I send a test message to my Hotmail address it doesn't end up in Junk. It was actually really easy to enable these settings in cPanel under Email Authentication. I can't believe I never saw that before. It only works with sending through SMTP using phpmailer by the way. Any other way it still is marked as spam."

PHPmailer sending mail to spam in hotmail. how to fix http://pastebin.com/QdQUrfax

How do you make sure email you send programmatically is not automatically marked as spam?

I hate to tell you, but I and others may be using white-list defaults to control our filtering of spam.

This means that all e-mail from an unknown source is automatically spam and diverted into a spam folder. (I don't let my e-mail service delete spam, because I want to always review the arrivals for false positives, something that is pretty easy to do by a quick scan of the folder.)

I even have e-mail from myself go to the spam bucket because (1) I usually don't send e-mail to myself and (2) there are spammers that fake my return address in spam sent to me.

So to get out of the spam designation, I have to consider that your mail might be legitimate (from sender and subject information) and open it first in plaintext (my default for all incoming mail, spam or not) to see if it is legitimate. My spam folder will not use any links in e-mails so I am protected against tricky image links and other misbehavior.

If I want future arrivals from the same source to go to my in box and not be diverted for spam review, I will specify that to my e-mail client. For those organizations that use bulk-mail forwarders and unique sender addresses per mail piece, that's too bad. They never get my approval and always show up in my spam folder, and if I'm busy I will never look at them.

Finally, if an e-mail is not legible in plaintext, even when sent as HTML, I am likely to just delete it unless it is something that I know is of interest to me by virtue of the source and previous valuable experiences.

As you can see, it is ultimately under an users control and there is no automated act that will convince such a system that your mail is legitimate from its structure alone. In this case, you need to play nice, don't do anything that is similar to phishing, and make it easy for users willing to trust your mail to add you to their white list.

What is the worst programming language you ever worked with?

Not sure if its a true language, but I hate Makefiles.

Makefiles have meaningful differences between space and TAB, so even if two lines appear identical, they do not run the same.

Make also relies on a complex set of implicit rules for many languages, which are difficult to learn, but then are frequently overridden by the make file.

A Makefile system is typically spread over many, many files, across many directories. With virtually no scoping or abstraction, a change to a make file several directories away can prevent my source from building. Yet the error message is invariably a compliation error, not a meaningful error about make, or the makefiles.

Any environment I've worked in that uses makefiles successfully has a full-time Make expert. And all this to shave a few minutes off compilation??

TypeError: unsupported operand type(s) for -: 'str' and 'int'

  1. The reason this is failing is because (Python 3) input returns a string. To convert it to an integer, use int(some_string).

  2. You do not typically keep track of indices manually in Python. A better way to implement such a function would be

    def cat_n_times(s, n):
        for i in range(n):
            print(s) 
    
    text = input("What would you like the computer to repeat back to you: ")
    num = int(input("How many times: ")) # Convert to an int immediately.
    
    cat_n_times(text, num)
    
  3. I changed your API above a bit. It seems to me that n should be the number of times and s should be the string.

How to send email by using javascript or jquery

You can do it server-side with nodejs.

Check out the popular Nodemailer package. There are plenty of transports and plugins for integrating with services like AWS SES and SendGrid!

The following example uses SES transport (Amazon SES):

let nodemailer = require("nodemailer");
let aws = require("aws-sdk");
let transporter = nodemailer.createTransport({
  SES: new aws.SES({ apiVersion: "2010-12-01" })
});

FileProvider - IllegalArgumentException: Failed to find configured root

I am sure I am late to the party but below worked for me.

<paths>
    <root-path name="root" path="." />
</paths>

Is there a Boolean data type in Microsoft SQL Server like there is in MySQL?

I use TINYINT(1)datatype in order to store boolean values in SQL Server though BIT is very effective

MySQL IF ELSEIF in select query

You have what you have used in stored procedures like this for reference, but they are not intended to be used as you have now. You can use IF as shown by duskwuff. But a Case statement is better for eyes. Like this:

select id, 
    (
    CASE 
        WHEN qty_1 <= '23' THEN price
        WHEN '23' > qty_1 && qty_2 <= '23' THEN price_2
        WHEN '23' > qty_2 && qty_3 <= '23' THEN price_3
        WHEN '23' > qty_3 THEN price_4
        ELSE 1
    END) AS total
 from product;

This looks cleaner. I suppose you do not require the inner SELECT anyway..

How can I get a JavaScript stack trace when I throw an exception?

Edit 2 (2017):

In all modern browsers you can simply call: console.trace(); (MDN Reference)

Edit 1 (2013):

A better (and simpler) solution as pointed out in the comments on the original question is to use the stack property of an Error object like so:

function stackTrace() {
    var err = new Error();
    return err.stack;
}

This will generate output like this:

DBX.Utils.stackTrace@http://localhost:49573/assets/js/scripts.js:44
DBX.Console.Debug@http://localhost:49573/assets/js/scripts.js:9
.success@http://localhost:49573/:462
x.Callbacks/c@http://localhost:49573/assets/js/jquery-1.10.2.min.js:4
x.Callbacks/p.fireWith@http://localhost:49573/assets/js/jquery-1.10.2.min.js:4
k@http://localhost:49573/assets/js/jquery-1.10.2.min.js:6
.send/r@http://localhost:49573/assets/js/jquery-1.10.2.min.js:6

Giving the name of the calling function along with the URL, its calling function, and so on.

Original (2009):

A modified version of this snippet may somewhat help:

function stacktrace() { 
  function st2(f) {
    return !f ? [] : 
        st2(f.caller).concat([f.toString().split('(')[0].substring(9) + '(' + f.arguments.join(',') + ')']);
  }
  return st2(arguments.callee.caller);
}

Creating a ZIP archive in memory using System.IO.Compression

       private void button6_Click(object sender, EventArgs e)
    {

        //create With Input FileNames
        AddFileToArchive_InputByte(new ZipItem[]{ new ZipItem( @"E:\b\1.jpg",@"images\1.jpg"),
            new ZipItem(@"E:\b\2.txt",@"text\2.txt")}, @"C:\test.zip");

        //create with input stream
        AddFileToArchive_InputByte(new ZipItem[]{ new ZipItem(File.ReadAllBytes( @"E:\b\1.jpg"),@"images\1.jpg"),
            new ZipItem(File.ReadAllBytes(@"E:\b\2.txt"),@"text\2.txt")}, @"C:\test.zip");

        //Create Archive And Return StreamZipFile
        MemoryStream GetStreamZipFile = AddFileToArchive(new ZipItem[]{ new ZipItem( @"E:\b\1.jpg",@"images\1.jpg"),
            new ZipItem(@"E:\b\2.txt",@"text\2.txt")});


        //Extract in memory
        ZipItem[] ListitemsWithBytes = ExtractItems(@"C:\test.zip");

        //Choese Files For Extract To memory
        List<string> ListFileNameForExtract = new List<string>(new string[] { @"images\1.jpg", @"text\2.txt" });
        ListitemsWithBytes = ExtractItems(@"C:\test.zip", ListFileNameForExtract);


        // Choese Files For Extract To Directory
        ExtractItems(@"C:\test.zip", ListFileNameForExtract, "c:\\extractFiles");

    }

    public struct ZipItem
    {
        string _FileNameSource;
        string _PathinArchive;
        byte[] _Bytes;
        public ZipItem(string __FileNameSource, string __PathinArchive)
        {
            _Bytes=null ;
            _FileNameSource = __FileNameSource;
            _PathinArchive = __PathinArchive;
        }
        public ZipItem(byte[] __Bytes, string __PathinArchive)
        {
            _Bytes = __Bytes;
            _FileNameSource = "";
            _PathinArchive = __PathinArchive;

        }
        public string FileNameSource
        {
            set
            {
                FileNameSource = value;
            }
            get
            {
                return _FileNameSource;
            }
        }
        public string PathinArchive
        {
            set
            {
                _PathinArchive = value;
            }
            get
            {
                return _PathinArchive;
            }
        }
        public byte[] Bytes
        {
            set
            {
                _Bytes = value;
            }
            get
            {
                return _Bytes;
            }
        }
    }


     public void AddFileToArchive(ZipItem[] ZipItems, string SeveToFile)
    {

        MemoryStream memoryStream = new MemoryStream();

        //Create Empty Archive
        ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);

        foreach (ZipItem item in ZipItems)
        {

            //Create Path File in Archive
            ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);


            //Open File in Archive For Write
            var OpenFileInArchive = FileInArchive.Open();

            //Read Stream
            FileStream fsReader = new FileStream(item.FileNameSource, FileMode.Open, FileAccess.Read);

            byte[] ReadAllbytes = new byte[4096];//Capcity buffer
            int ReadByte = 0;
            while (fsReader.Position != fsReader.Length)
            {
                //Read Bytes
                ReadByte = fsReader.Read(ReadAllbytes, 0, ReadAllbytes.Length);

                //Write Bytes
                OpenFileInArchive.Write(ReadAllbytes, 0, ReadByte);
            }
            fsReader.Dispose();
            OpenFileInArchive.Close();


        }
        archive.Dispose();

        using (var fileStream = new FileStream(SeveToFile, FileMode.Create))
        {
            memoryStream.Seek(0, SeekOrigin.Begin);
            memoryStream.CopyTo(fileStream);
        }





    }
     public MemoryStream  AddFileToArchive(ZipItem[] ZipItems)
    {

        MemoryStream memoryStream = new MemoryStream();

        //Create Empty Archive
        ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);

        foreach (ZipItem item in ZipItems)
        {

            //Create Path File in Archive
            ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);


            //Open File in Archive For Write
            var OpenFileInArchive = FileInArchive.Open();

            //Read Stream
            FileStream fsReader = new FileStream(item.FileNameSource, FileMode.Open, FileAccess.Read);

            byte[] ReadAllbytes = new byte[4096];//Capcity buffer
            int ReadByte = 0;
            while (fsReader.Position != fsReader.Length)
            {
                //Read Bytes
                ReadByte = fsReader.Read(ReadAllbytes, 0, ReadAllbytes.Length);

                //Write Bytes
                OpenFileInArchive.Write(ReadAllbytes, 0, ReadByte);
            }
            fsReader.Dispose();
            OpenFileInArchive.Close();


        }
        archive.Dispose();




        return memoryStream;


    }

     public void AddFileToArchive_InputByte(ZipItem[] ZipItems, string SeveToFile)
    {

        MemoryStream memoryStream = new MemoryStream();

        //Create Empty Archive
        ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);

        foreach (ZipItem item in ZipItems)
        {

            //Create Path File in Archive
            ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);


            //Open File in Archive For Write
            var OpenFileInArchive = FileInArchive.Open();

            //Read Stream
          //  FileStream fsReader = new FileStream(item.FileNameSource, FileMode.Open, FileAccess.Read);

            byte[] ReadAllbytes = new byte[4096];//Capcity buffer
            int ReadByte = 4096 ;int  TotalWrite=0;
            while (TotalWrite != item.Bytes.Length)
            {

                if(TotalWrite+4096>item.Bytes.Length)
                 ReadByte=item.Bytes.Length-TotalWrite;



                Array.Copy(item.Bytes, TotalWrite, ReadAllbytes, 0, ReadByte);




                //Write Bytes
                OpenFileInArchive.Write(ReadAllbytes, 0, ReadByte);
                TotalWrite += ReadByte;
            }

            OpenFileInArchive.Close();


        }
        archive.Dispose();

        using (var fileStream = new FileStream(SeveToFile, FileMode.Create))
        {
            memoryStream.Seek(0, SeekOrigin.Begin);
            memoryStream.CopyTo(fileStream);
        }


    }
     public MemoryStream  AddFileToArchive_InputByte(ZipItem[] ZipItems)
    {

        MemoryStream memoryStream = new MemoryStream();

        //Create Empty Archive
        ZipArchive archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true);

        foreach (ZipItem item in ZipItems)
        {

            //Create Path File in Archive
            ZipArchiveEntry FileInArchive = archive.CreateEntry(item.PathinArchive);


            //Open File in Archive For Write
            var OpenFileInArchive = FileInArchive.Open();

            //Read Stream
          //  FileStream fsReader = new FileStream(item.FileNameSource, FileMode.Open, FileAccess.Read);

            byte[] ReadAllbytes = new byte[4096];//Capcity buffer
            int ReadByte = 4096 ;int  TotalWrite=0;
            while (TotalWrite != item.Bytes.Length)
            {

                if(TotalWrite+4096>item.Bytes.Length)
                 ReadByte=item.Bytes.Length-TotalWrite;



                Array.Copy(item.Bytes, TotalWrite, ReadAllbytes, 0, ReadByte);




                //Write Bytes
                OpenFileInArchive.Write(ReadAllbytes, 0, ReadByte);
                TotalWrite += ReadByte;
            }

            OpenFileInArchive.Close();


        }
        archive.Dispose();



        return memoryStream;
    }

     public void ExtractToDirectory(string sourceArchiveFileName, string destinationDirectoryName)
     {
         //Opens the zip file up to be read
         using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
         {
             if (Directory.Exists(destinationDirectoryName)==false )
                 Directory.CreateDirectory(destinationDirectoryName);

             //Loops through each file in the zip file
             archive.ExtractToDirectory(destinationDirectoryName);

         }
     }  
     public void   ExtractItems(string sourceArchiveFileName,List< string> _PathFilesinArchive, string destinationDirectoryName)
     {

         //Opens the zip file up to be read
         using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
         {


             //Loops through each file in the zip file
             foreach (ZipArchiveEntry file in archive.Entries)
             {
                 int PosResult = _PathFilesinArchive.IndexOf(file.FullName);
                 if (PosResult != -1)
                 {
                     //Create Folder
                     if (Directory.Exists( destinationDirectoryName + "\\" +Path.GetDirectoryName( _PathFilesinArchive[PosResult])) == false)
                         Directory.CreateDirectory(destinationDirectoryName + "\\" + Path.GetDirectoryName(_PathFilesinArchive[PosResult]));

                     Stream OpenFileGetBytes = file.Open();

                     FileStream   FileStreamOutput = new FileStream(destinationDirectoryName + "\\" + _PathFilesinArchive[PosResult], FileMode.Create);

                     byte[] ReadAllbytes = new byte[4096];//Capcity buffer
                     int ReadByte = 0; int TotalRead = 0; 
                     while (TotalRead != file.Length)
                     {
                         //Read Bytes
                         ReadByte = OpenFileGetBytes.Read(ReadAllbytes, 0, ReadAllbytes.Length);
                         TotalRead += ReadByte;

                         //Write Bytes
                         FileStreamOutput.Write(ReadAllbytes, 0, ReadByte);
                     }

                     FileStreamOutput.Close();
                     OpenFileGetBytes.Close();



                     _PathFilesinArchive.RemoveAt(PosResult);
                 }

                 if (_PathFilesinArchive.Count == 0)
                     break;
             }
         }


     }

     public ZipItem[] ExtractItems(string sourceArchiveFileName)
     {
       List<  ZipItem> ZipItemsReading = new List<ZipItem>();
         //Opens the zip file up to be read
         using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
         {


             //Loops through each file in the zip file
             foreach (ZipArchiveEntry file in archive.Entries)
             {
                 Stream OpenFileGetBytes = file.Open();

                 MemoryStream memstreams = new MemoryStream();
                 byte[] ReadAllbytes = new byte[4096];//Capcity buffer
                 int ReadByte = 0; int TotalRead = 0;
                 while (TotalRead != file.Length)
                 {
                     //Read Bytes
                     ReadByte = OpenFileGetBytes.Read(ReadAllbytes, 0, ReadAllbytes.Length);
                     TotalRead += ReadByte;

                     //Write Bytes
                     memstreams.Write(ReadAllbytes, 0, ReadByte);
                 }

                 memstreams.Position = 0;
                 OpenFileGetBytes.Close();
                 memstreams.Dispose();

                 ZipItemsReading.Add(new ZipItem(memstreams.ToArray(),file.FullName));


             }
         }

         return ZipItemsReading.ToArray();
     }
     public ZipItem[] ExtractItems(string sourceArchiveFileName,List< string> _PathFilesinArchive)
     {
       List<  ZipItem> ZipItemsReading = new List<ZipItem>();
         //Opens the zip file up to be read
         using (ZipArchive archive = ZipFile.OpenRead(sourceArchiveFileName))
         {

             //Loops through each file in the zip file
             foreach (ZipArchiveEntry file in archive.Entries)
             {
                 int PosResult = _PathFilesinArchive.IndexOf(file.FullName); 
                 if (PosResult!= -1)
                 {
                     Stream OpenFileGetBytes = file.Open();

                     MemoryStream memstreams = new MemoryStream();
                     byte[] ReadAllbytes = new byte[4096];//Capcity buffer
                     int ReadByte = 0; int TotalRead = 0;  
                     while (TotalRead != file.Length)
                     {
                         //Read Bytes
                         ReadByte = OpenFileGetBytes.Read(ReadAllbytes, 0, ReadAllbytes.Length);
                         TotalRead += ReadByte;

                         //Write Bytes
                         memstreams.Write(ReadAllbytes, 0, ReadByte);
                     }

                     //Create item
                     ZipItemsReading.Add(new ZipItem(memstreams.ToArray(),file.FullName));

                     OpenFileGetBytes.Close();
                     memstreams.Dispose();



                     _PathFilesinArchive.RemoveAt(PosResult);
                 }

                 if (_PathFilesinArchive.Count == 0)
                     break;


             }
         }

         return ZipItemsReading.ToArray();
     }

How to center images on a web page for all screen sizes

text-align:center

Applying the text-align:center style to an element containing elements will center those elements.

<div id="method-one" style="text-align:center">
  CSS `text-align:center`
</div>

Thomas Shields mentions this method



margin:0 auto

Applying the margin:0 auto style to a block element will center it within the element it is in.

<div id="method-two" style="background-color:green">
  <div style="margin:0 auto;width:50%;background-color:lightblue">
    CSS `margin:0 auto` to have left and right margin set to center a block element within another element.
  </div>
</div>

user1468562 mentions this method


Center tag

My original answer was that you can use the <center></center> tag. To do this, just place the content you want centered between the tags. As of HTML4, this tag has been deprecated, though. <center> is still technically supported today (9 years later at the time of updating this), but I'd recommend the CSS alternatives I've included above.

<h3>Method 3</h1>
<div id="method-three">
  <center>Center tag (not recommended and deprecated in HTML4)</center>
</div>

You can see these three code samples in action in this jsfiddle.

I decided I should revise this answer as the previous one I gave was outdated. It was already deprecated when I suggested it as a solution and that's all the more reason to avoid it now 9 years later.

bash: Bad Substitution

I have found that this issue is either caused by the marked answer or you have a line or space before the bash declaration

Encrypting & Decrypting a String in C#

Try this class:

public class DataEncryptor
{
    TripleDESCryptoServiceProvider symm;

    #region Factory
    public DataEncryptor()
    {
        this.symm = new TripleDESCryptoServiceProvider();
        this.symm.Padding = PaddingMode.PKCS7;
    }
    public DataEncryptor(TripleDESCryptoServiceProvider keys)
    {
        this.symm = keys;
    }

    public DataEncryptor(byte[] key, byte[] iv)
    {
        this.symm = new TripleDESCryptoServiceProvider();
        this.symm.Padding = PaddingMode.PKCS7;
        this.symm.Key = key;
        this.symm.IV = iv;
    }

    #endregion

    #region Properties
    public TripleDESCryptoServiceProvider Algorithm
    {
        get { return symm; }
        set { symm = value; }
    }
    public byte[] Key
    {
        get { return symm.Key; }
        set { symm.Key = value; }
    }
    public byte[] IV
    {
        get { return symm.IV; }
        set { symm.IV = value; }
    }

    #endregion

    #region Crypto

    public byte[] Encrypt(byte[] data) { return Encrypt(data, data.Length); }
    public byte[] Encrypt(byte[] data, int length)
    {
        try
        {
            // Create a MemoryStream.
            var ms = new MemoryStream();

            // Create a CryptoStream using the MemoryStream 
            // and the passed key and initialization vector (IV).
            var cs = new CryptoStream(ms,
                symm.CreateEncryptor(symm.Key, symm.IV),
                CryptoStreamMode.Write);

            // Write the byte array to the crypto stream and flush it.
            cs.Write(data, 0, length);
            cs.FlushFinalBlock();

            // Get an array of bytes from the 
            // MemoryStream that holds the 
            // encrypted data.
            byte[] ret = ms.ToArray();

            // Close the streams.
            cs.Close();
            ms.Close();

            // Return the encrypted buffer.
            return ret;
        }
        catch (CryptographicException ex)
        {
            Console.WriteLine("A cryptographic error occured: {0}", ex.Message);
        }
        return null;
    }

    public string EncryptString(string text)
    {
        return Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(text)));
    }

    public byte[] Decrypt(byte[] data) { return Decrypt(data, data.Length); }
    public byte[] Decrypt(byte[] data, int length)
    {
        try
        {
            // Create a new MemoryStream using the passed 
            // array of encrypted data.
            MemoryStream ms = new MemoryStream(data);

            // Create a CryptoStream using the MemoryStream 
            // and the passed key and initialization vector (IV).
            CryptoStream cs = new CryptoStream(ms,
                symm.CreateDecryptor(symm.Key, symm.IV),
                CryptoStreamMode.Read);

            // Create buffer to hold the decrypted data.
            byte[] result = new byte[length];

            // Read the decrypted data out of the crypto stream
            // and place it into the temporary buffer.
            cs.Read(result, 0, result.Length);
            return result;
        }
        catch (CryptographicException ex)
        {
            Console.WriteLine("A cryptographic error occured: {0}", ex.Message);
        }
        return null;
    }

    public string DecryptString(string data)
    {
        return Encoding.UTF8.GetString(Decrypt(Convert.FromBase64String(data))).TrimEnd('\0');
    }

    #endregion

}

and use it like this:

string message="A very secret message here.";
DataEncryptor keys=new DataEncryptor();
string encr=keys.EncryptString(message);

// later
string actual=keys.DecryptString(encr);

Netbeans - class does not have a main method

  1. Check for correct method declaration

public static void main(String [ ] args)

  1. Check netbeans project properties in Run > main Class

C++, how to declare a struct in a header file

Try this new source :

student.h

#include <iostream>

struct Student {
    std::string lastName;
    std::string firstName;
};

student.cpp

#include "student.h"

struct Student student;

Print in Landscape format

you cannot set this in javascript, you have to do this with html/css:

<style type="text/css" media="print">
  @page { size: landscape; }
</style>

EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?

Hibernate show real SQL

Worth noting that the code you see is sent to the database as is, the queries are sent separately to prevent SQL injection. AFAIK The ? marks are placeholders that are replaced by the number params by the database, not by hibernate.

What does 'super' do in Python?

What's the difference?

SomeBaseClass.__init__(self) 

means to call SomeBaseClass's __init__. while

super(Child, self).__init__()

means to call a bound __init__ from the parent class that follows Child in the instance's Method Resolution Order (MRO).

If the instance is a subclass of Child, there may be a different parent that comes next in the MRO.

Explained simply

When you write a class, you want other classes to be able to use it. super() makes it easier for other classes to use the class you're writing.

As Bob Martin says, a good architecture allows you to postpone decision making as long as possible.

super() can enable that sort of architecture.

When another class subclasses the class you wrote, it could also be inheriting from other classes. And those classes could have an __init__ that comes after this __init__ based on the ordering of the classes for method resolution.

Without super you would likely hard-code the parent of the class you're writing (like the example does). This would mean that you would not call the next __init__ in the MRO, and you would thus not get to reuse the code in it.

If you're writing your own code for personal use, you may not care about this distinction. But if you want others to use your code, using super is one thing that allows greater flexibility for users of the code.

Python 2 versus 3

This works in Python 2 and 3:

super(Child, self).__init__()

This only works in Python 3:

super().__init__()

It works with no arguments by moving up in the stack frame and getting the first argument to the method (usually self for an instance method or cls for a class method - but could be other names) and finding the class (e.g. Child) in the free variables (it is looked up with the name __class__ as a free closure variable in the method).

I prefer to demonstrate the cross-compatible way of using super, but if you are only using Python 3, you can call it with no arguments.

Indirection with Forward Compatibility

What does it give you? For single inheritance, the examples from the question are practically identical from a static analysis point of view. However, using super gives you a layer of indirection with forward compatibility.

Forward compatibility is very important to seasoned developers. You want your code to keep working with minimal changes as you change it. When you look at your revision history, you want to see precisely what changed when.

You may start off with single inheritance, but if you decide to add another base class, you only have to change the line with the bases - if the bases change in a class you inherit from (say a mixin is added) you'd change nothing in this class. Particularly in Python 2, getting the arguments to super and the correct method arguments right can be difficult. If you know you're using super correctly with single inheritance, that makes debugging less difficult going forward.

Dependency Injection

Other people can use your code and inject parents into the method resolution:

class SomeBaseClass(object):
    def __init__(self):
        print('SomeBaseClass.__init__(self) called')

class UnsuperChild(SomeBaseClass):
    def __init__(self):
        print('UnsuperChild.__init__(self) called')
        SomeBaseClass.__init__(self)

class SuperChild(SomeBaseClass):
    def __init__(self):
        print('SuperChild.__init__(self) called')
        super(SuperChild, self).__init__()

Say you add another class to your object, and want to inject a class between Foo and Bar (for testing or some other reason):

class InjectMe(SomeBaseClass):
    def __init__(self):
        print('InjectMe.__init__(self) called')
        super(InjectMe, self).__init__()

class UnsuperInjector(UnsuperChild, InjectMe): pass

class SuperInjector(SuperChild, InjectMe): pass

Using the un-super child fails to inject the dependency because the child you're using has hard-coded the method to be called after its own:

>>> o = UnsuperInjector()
UnsuperChild.__init__(self) called
SomeBaseClass.__init__(self) called

However, the class with the child that uses super can correctly inject the dependency:

>>> o2 = SuperInjector()
SuperChild.__init__(self) called
InjectMe.__init__(self) called
SomeBaseClass.__init__(self) called

Addressing a comment

Why in the world would this be useful?

Python linearizes a complicated inheritance tree via the C3 linearization algorithm to create a Method Resolution Order (MRO).

We want methods to be looked up in that order.

For a method defined in a parent to find the next one in that order without super, it would have to

  1. get the mro from the instance's type
  2. look for the type that defines the method
  3. find the next type with the method
  4. bind that method and call it with the expected arguments

The UnsuperChild should not have access to InjectMe. Why isn't the conclusion "Always avoid using super"? What am I missing here?

The UnsuperChild does not have access to InjectMe. It is the UnsuperInjector that has access to InjectMe - and yet cannot call that class's method from the method it inherits from UnsuperChild.

Both Child classes intend to call a method by the same name that comes next in the MRO, which might be another class it was not aware of when it was created.

The one without super hard-codes its parent's method - thus is has restricted the behavior of its method, and subclasses cannot inject functionality in the call chain.

The one with super has greater flexibility. The call chain for the methods can be intercepted and functionality injected.

You may not need that functionality, but subclassers of your code may.

Conclusion

Always use super to reference the parent class instead of hard-coding it.

What you intend is to reference the parent class that is next-in-line, not specifically the one you see the child inheriting from.

Not using super can put unnecessary constraints on users of your code.

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

What are some alternatives to ReSharper?

Keep in mind that with Visual Studio 2010 you may not need/want any addon. A lot of the ReSharper features were added into the Visual Studio 2010 core features. ReSharper, CodeRush, etc. have other features above and beyond Visual Studio for sure, but see what's been added vs. what you need. It could be that the core install takes care of what you are interested in now.

I personally use ReSharper 5 still as it has many uses, for me. What each coder finds most important though varies widely. You'll have to test each for yourself, but luckily all the alternatives have trial periods as well.

How to default to other directory instead of home directory

From a Pinned Start Menu Item in Windows 10

  1. Open the file location of the pinned shortcut
  2. Open the shortcut properties
    1. Remove --cd-to-home arg
    2. Update Start in path
  3. Re-pin to start menu via recently added

open file location screenshot

open shortcut properites screenshot

update shortcut properites screenshot

pin via recently added screnshot


Thanks to all the other answers for how to do this! Wanted to provide Win 10 instructions...

Commenting out code blocks in Atom

Multi-line comment can be made by selecting the lines and by pressing Ctrl+/ . and Now you can have many plugins for comments

1) comment - https://atom.io/packages/comment
2) block-comment-lines - https://atom.io/packages/block-comment-lines

better one is block-comment try that..

ToggleClass animate jQuery?

You should look at the toggle function found on jQuery. This will allow you to specify an easing method to define how the toggle works.

slideToggle will only slide up and down, not left/right if that's what you are looking for.

If you need the class to be toggled as well you can deifine that in the toggle function with a:

$(this).closest('article').toggle('slow', function() {
    $(this).toggleClass('expanded');
});

$(window).scrollTop() vs. $(document).scrollTop()

First, you need to understand the difference between window and document. The window object is a top level client side object. There is nothing above the window object. JavaScript is an object orientated language. You start with an object and apply methods to its properties or the properties of its object groups. For example, the document object is an object of the window object. To change the document's background color, you'd set the document's bgcolor property.

window.document.bgcolor = "red" 

To answer your question, There is no difference in the end result between window and document scrollTop. Both will give the same output.

Check working example at http://jsfiddle.net/7VRvj/6/

In general use document mainly to register events and use window to do things like scroll, scrollTop, and resize.

In Perl, how to remove ^M from a file?

This is what solved my problem. ^M is a carriage return, and it can be easily avoided in a Perl script.

while(<INPUTFILE>)
{
     chomp;
     chop($_) if ($_ =~ m/\r$/);
}

HTML5 input type range show range value

version with editable input:

<form>
    <input type="range" name="amountRange" min="0" max="20" value="0" oninput="this.form.amountInput.value=this.value" />
    <input type="number" name="amountInput" min="0" max="20" value="0" oninput="this.form.amountRange.value=this.value" />
</form>

http://jsfiddle.net/Xjxe6/

Android studio Gradle build speed up

After change this settings my compile time 10 mins reduced to 10 secs.

Step 1:

Settings(ctrl+Alt+S) ->

Build,Execution,Deployment ->

Compiler ->

type "--offline" in command-line Options box.

Step 2:

check the “Compile independent modules in parallel” checkbox.

& click Apply -> OK

enter image description here

Step 3: In your gradle.properties file -> Add following lines

org.gradle.jvmargs=-Xmx2048M -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
org.gradle.parallel=true
org.gradle.configureondemand=true
org.gradle.daemon=true

Update:

If you are using Android studio 2.0 or above try the Instant Run

Settings ? Build, Execution, Deployment ? Instant Run ? Enable Instant Run.

More info about Instant Run - https://developer.android.com/studio/run/index.html#instant-run

String to char array Java

A string to char array is as simple as

String str = "someString"; 
char[] charArray = str.toCharArray();

Can you explain a little more on what you are trying to do?

* Update *

if I am understanding your new comment, you can use a byte array and example is provided.

byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();

for (byte b : bytes) {
   System.out.format("0x%x ", b);
}

With the following output

0x65 0x10 0xf3 0x29

How to get next/previous record in MySQL?

next:

select * from foo where id = (select min(id) from foo where id > 4)

previous:

select * from foo where id = (select max(id) from foo where id < 4)

How can I get the root domain URI in ASP.NET?

If example Url is http://www.foobar.com/Page1

HttpContext.Current.Request.Url; //returns "http://www.foobar.com/Page1"


HttpContext.Current.Request.Url.Host; //returns "www.foobar.com"


HttpContext.Current.Request.Url.Scheme; //returns "http/https"


HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority); //returns "http://www.foobar.com"

'ls' in CMD on Windows is not recognized

Use the command dir to list all the directories and files in a directory; ls is a unix command.

How get sound input from microphone in python, and process it on the fly?

I know it's an old question, but if someone is looking here again... see https://python-sounddevice.readthedocs.io/en/0.4.1/index.html .

It has a nice example "Input to Ouput Pass-Through" here https://python-sounddevice.readthedocs.io/en/0.4.1/examples.html#input-to-output-pass-through .

... and a lot of other examples as well ...

Convert python datetime to epoch with strftime

import time
from datetime import datetime
now = datetime.now()

# same as above except keeps microseconds
time.mktime(now.timetuple()) + now.microsecond * 1e-6

(Sorry, it wouldn't let me comment on existing answer)

How to filter an array/object by checking multiple values

You can use .filter() method of the Array object:

var filtered = workItems.filter(function(element) {
   // Create an array using `.split()` method
   var cats = element.category.split(' ');

   // Filter the returned array based on specified filters
   // If the length of the returned filtered array is equal to
   // length of the filters array the element should be returned  
   return cats.filter(function(cat) {
       return filtersArray.indexOf(cat) > -1;
   }).length === filtersArray.length;
});

http://jsfiddle.net/6RBnB/

Some old browsers like IE8 doesn't support .filter() method of the Array object, if you are using jQuery you can use .filter() method of jQuery object.

jQuery version:

var filtered = $(workItems).filter(function(i, element) {
   var cats = element.category.split(' ');

    return $(cats).filter(function(_, cat) {
       return $.inArray(cat, filtersArray) > -1;
    }).length === filtersArray.length;
});

Breadth First Vs Depth First

Understanding the terms:

This picture should give you the idea about the context in which the words breadth and depth are used.

Understanding Breadth and Depth


Depth-First Search:

Depth-First Search

  • Depth-first search algorithm acts as if it wants to get as far away from the starting point as quickly as possible.

  • It generally uses a Stack to remember where it should go when it reaches a dead end.

  • Rules to follow: Push first vertex A on to the Stack

    1. If possible, visit an adjacent unvisited vertex, mark it as visited, and push it on the stack.
    2. If you can’t follow Rule 1, then, if possible, pop a vertex off the stack.
    3. If you can’t follow Rule 1 or Rule 2, you’re done.
  • Java code:

    public void searchDepthFirst() {
        // Begin at vertex 0 (A)
        vertexList[0].wasVisited = true;
        displayVertex(0);
        stack.push(0);
        while (!stack.isEmpty()) {
            int adjacentVertex = getAdjacentUnvisitedVertex(stack.peek());
            // If no such vertex
            if (adjacentVertex == -1) {
                stack.pop();
            } else {
                vertexList[adjacentVertex].wasVisited = true;
                // Do something
                stack.push(adjacentVertex);
            }
        }
        // Stack is empty, so we're done, reset flags
        for (int j = 0; j < nVerts; j++)
            vertexList[j].wasVisited = false;
    }
    
  • Applications: Depth-first searches are often used in simulations of games (and game-like situations in the real world). In a typical game you can choose one of several possible actions. Each choice leads to further choices, each of which leads to further choices, and so on into an ever-expanding tree-shaped graph of possibilities.


Breadth-First Search:

Breadth-First Search

  • The breadth-first search algorithm likes to stay as close as possible to the starting point.
  • This kind of search is generally implemented using a Queue.
  • Rules to follow: Make starting Vertex A the current vertex
    1. Visit the next unvisited vertex (if there is one) that’s adjacent to the current vertex, mark it, and insert it into the queue.
    2. If you can’t carry out Rule 1 because there are no more unvisited vertices, remove a vertex from the queue (if possible) and make it the current vertex.
    3. If you can’t carry out Rule 2 because the queue is empty, you’re done.
  • Java code:

    public void searchBreadthFirst() {
        vertexList[0].wasVisited = true;
        displayVertex(0);
        queue.insert(0);
        int v2;
        while (!queue.isEmpty()) {
            int v1 = queue.remove();
            // Until it has no unvisited neighbors, get one
            while ((v2 = getAdjUnvisitedVertex(v1)) != -1) {
                vertexList[v2].wasVisited = true;
                // Do something
                queue.insert(v2);
            }
        }
        // Queue is empty, so we're done, reset flags
        for (int j = 0; j < nVerts; j++) 
            vertexList[j].wasVisited = false;
    }
    
  • Applications: Breadth-first search first finds all the vertices that are one edge away from the starting point, then all the vertices that are two edges away, and so on. This is useful if you’re trying to find the shortest path from the starting vertex to a given vertex.

Hopefully that should be enough for understanding the Breadth-First and Depth-First searches. For further reading I would recommend the Graphs chapter from an excellent data structures book by Robert Lafore.

jquery stop child triggering parent event

Or, rather than having an extra event handler to prevent another handler, you can use the Event Object argument passed to your click event handler to determine whether a child was clicked. target will be the clicked element and currentTarget will be the .header div:

$(".header").click(function(e){
     //Do nothing if .header was not directly clicked
     if(e.target !== e.currentTarget) return;

     $(this).children(".children").toggle();
});

Setting Authorization Header of HttpClient

Using AuthenticationHeaderValue class of System.Net.Http assembly

public AuthenticationHeaderValue(
    string scheme,
    string parameter
)

we can set or update existing Authorization header for our httpclient like so:

httpclient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", TokenResponse.AccessToken);

What is an .axd file?

Those are not files (they don't exist on disk) - they are just names under which some HTTP handlers are registered. Take a look at the web.config in .NET Framework's directory (e.g. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config):

<configuration>
  <system.web>
    <httpHandlers>
      <add path="eurl.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
      <add path="trace.axd" verb="*" type="System.Web.Handlers.TraceHandler" validate="True" />
      <add path="WebResource.axd" verb="GET" type="System.Web.Handlers.AssemblyResourceLoader" validate="True" />
      <add verb="*" path="*_AppService.axd" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False" />
      <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False"/>
      <add path="*.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
    </httpHandlers>
  </system.web>
<configuration>

You can register your own handlers with a whatever.axd name in your application's web.config. While you can bind your handlers to whatever names you like, .axd has the upside of working on IIS6 out of the box by default (IIS6 passes requests for *.axd to the ASP.NET runtime by default). Using an arbitrary path for the handler, like Document.pdf (or really anything except ASP.NET-specific extensions), requires more configuration work. In IIS7 in integrated pipeline mode this is no longer a problem, as all requests are processed by the ASP.NET stack.

Difference between ref and out parameters in .NET

This The out and ref Paramerter in C# has some good examples.

The basic difference outlined is that out parameters don't need to be initialized when passed in, while ref parameters do.

jQuery Set Select Index

Select the item based on the value in the select list (especially if the option values have a space or weird character in it) by simply doing this:

$("#SelectList option").each(function () {
    if ($(this).val() == "1:00 PM")
        $(this).attr('selected', 'selected');
});

Also, if you have a dropdown (as opposed to a multi-select) you may want to do a break; so you don't get the first-value-found to be overwritten.

How to write URLs in Latex?

You just need to escape characters that have special meaning: # $ % & ~ _ ^ \ { }

So

http://stack_overflow.com/~foo%20bar#link

would be

http://stack\_overflow.com/\~foo\%20bar\#link

Absolute and Flexbox in React Native

The first step would be to add

position: 'absolute',

then if you want the element full width, add

left: 0,
right: 0,

then, if you want to put the element in the bottom, add

bottom: 0,
// don't need set top: 0

if you want to position the element at the top, replace bottom: 0 by top: 0

How to copy a huge table data into another table in SQL Server

I have been working with our DBA to copy an audit table with 240M rows to another database.

Using a simple select/insert created a huge tempdb file.

Using a the Import/Export wizard worked but copied 8M rows in 10min

Creating a custom SSIS package and adjusting settings copied 30M rows in 10Min

The SSIS package turned out to be the fastest and most efficent for our purposes

Earl

How do I combine 2 select statements into one?

If they are from the same table, I think UNION is the command you're looking for.

(If you'd ever need to select values from columns of different tables, you should look at JOIN instead...)

Difference between `npm start` & `node app.js`, when starting app?

From the man page, npm start:

runs a package's "start" script, if one was provided. If no version is specified, then it starts the "active" version.

Admittedly, that description is completely unhelpful, and that's all it says. At least it's more documented than socket.io.

Anyhow, what really happens is that npm looks in your package.json file, and if you have something like

"scripts": { "start": "coffee server.coffee" }

then it will do that. If npm can't find your start script, it defaults to:

node server.js

 

MySQL CONCAT returns NULL if any field contain NULL

To have the same flexibility in CONCAT_WS as in CONCAT (if you don't want the same separator between every member for instance) use the following:

SELECT CONCAT_WS("",affiliate_name,':',model,'-',ip,... etc)

grep's at sign caught as whitespace

No -P needed; -E is sufficient:

grep -E '(^|\s)abc(\s|$)' 

or even without -E:

grep '\(^\|\s\)abc\(\s\|$\)' 

text-align: right; not working for <label>

As stated in other answers, label is an inline element. However, you can apply display: inline-block to the label and then center with text-align.

#name_label {
    display: inline-block;
    width: 90%;
    text-align: right;
}

Why display: inline-block and not display: inline? For the same reason that you can't align label, it's inline.

Why display: inline-block and not display: block? You could use display: block, but it will be on another line. display: inline-block combines the properties of inline and block. It's inline, but you can also give it a width, height, and align it.

jQuery - adding elements into an array

Try this, at the end of the each loop, ids array will contain all the hexcodes.

var ids = [];

    $(document).ready(function($) {
    var $div = $("<div id='hexCodes'></div>").appendTo(document.body), code;
    $(".color_cell").each(function() {
        code = $(this).attr('id');
        ids.push(code);
        $div.append(code + "<br />");
    });



});

Dropdownlist validation in Asp.net Using Required field validator

<asp:RequiredFieldValidator InitialValue="-1" ID="Req_ID" Display="Dynamic" 
    ValidationGroup="g1" runat="server" ControlToValidate="ControlID"
    Text="*" ErrorMessage="ErrorMessage"></asp:RequiredFieldValidator>

Export and Import all MySQL databases at one time

Export all databases in Ubuntu

1 - mysqldump -u root -p --databases database1 database2 > ~/Desktop/databases_1_2.sql

OR

2 - mysqldump -u root -p --all_databases > ~/Desktop/all_databases.sql

enter image description here

Visual Studio replace tab with 4 spaces?

You can edit this behavior in:

Tools->Options->Text Editor->All Languages->Tabs

Change Tab to use "Insert Spaces" instead of "Keep Tabs".

Note you can also specify this per language if you wish to have different behavior in a specific language.

Basic HTML - how to set relative path to current folder?

<html>
    <head>
        <title>Page</title>
    </head>
    <body>
       <a href="./">Folder directory</a> 
    </body>
</html>

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

Try setting core.autocrlf value like this :

git config --global core.autocrlf true

How can prepared statements protect from SQL injection attacks?

ResultSet rs = statement.executeQuery("select * from foo where value = " + httpRequest.getParameter("filter");

Let’s assume you have that in a Servlet you right. If a malevolent person passed a bad value for 'filter' you might hack your database.

best way to preserve numpy arrays on disk

Another possibility to store numpy arrays efficiently is Bloscpack:

#!/usr/bin/python
import numpy as np
import bloscpack as bp
import time

n = 10000000

a = np.arange(n)
b = np.arange(n) * 10
c = np.arange(n) * -0.5
tsizeMB = sum(i.size*i.itemsize for i in (a,b,c)) / 2**20.

blosc_args = bp.DEFAULT_BLOSC_ARGS
blosc_args['clevel'] = 6
t = time.time()
bp.pack_ndarray_file(a, 'a.blp', blosc_args=blosc_args)
bp.pack_ndarray_file(b, 'b.blp', blosc_args=blosc_args)
bp.pack_ndarray_file(c, 'c.blp', blosc_args=blosc_args)
t1 = time.time() - t
print "store time = %.2f (%.2f MB/s)" % (t1, tsizeMB / t1)

t = time.time()
a1 = bp.unpack_ndarray_file('a.blp')
b1 = bp.unpack_ndarray_file('b.blp')
c1 = bp.unpack_ndarray_file('c.blp')
t1 = time.time() - t
print "loading time = %.2f (%.2f MB/s)" % (t1, tsizeMB / t1)

and the output for my laptop (a relatively old MacBook Air with a Core2 processor):

$ python store-blpk.py
store time = 0.19 (1216.45 MB/s)
loading time = 0.25 (898.08 MB/s)

that means that it can store really fast, i.e. the bottleneck is typically the disk. However, as the compression ratios are pretty good here, the effective speed is multiplied by the compression ratios. Here are the sizes for these 76 MB arrays:

$ ll -h *.blp
-rw-r--r--  1 faltet  staff   921K Mar  6 13:50 a.blp
-rw-r--r--  1 faltet  staff   2.2M Mar  6 13:50 b.blp
-rw-r--r--  1 faltet  staff   1.4M Mar  6 13:50 c.blp

Please note that the use of the Blosc compressor is fundamental for achieving this. The same script but using 'clevel' = 0 (i.e. disabling compression):

$ python bench/store-blpk.py
store time = 3.36 (68.04 MB/s)
loading time = 2.61 (87.80 MB/s)

is clearly bottlenecked by the disk performance.

Ruby, remove last N characters from a string?

If you're ok with creating class methods and want the characters you chop off, try this:

class String
  def chop_multiple(amount)
    amount.times.inject([self, '']){ |(s, r)| [s.chop, r.prepend(s[-1])] }
  end
end

hello, world = "hello world".chop_multiple 5
hello #=> 'hello '
world #=> 'world'

Find intersection of two nested lists?

c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
c3 = [list(set(i) & set(c1)) for i in c2]
c3
[[32, 13], [28, 13, 7], [1, 6]]

For me this is very elegant and quick way to to it :)

getting error while updating Composer

for php7 you can do that:

sudo apt-get install php-gd php-xml php7.0-mbstring

How to open Emacs inside Bash

I didn't like the alias solution for my purposes. For one, it didn't work for setting export EDITOR="emacs -nw".

But you can pass --without-x to configure and then just the regular old Emacs will always open in terminal.

curl http://gnu.mirrors.hoobly.com/emacs/emacs-25.3.tar.xz
tar -xvzf emacs-25.3.tar.xz && cd emacs-25.3
./configure --without-x
make && sudo make install

how to make a html iframe 100% width and height?

this code probable help you .

<iframe src="" onload="this.width=screen.width;this.height=screen.height;">

How to make a flex item not fill the height of the flex container?

When you create a flex container various default flex rules come into play.

Two of these default rules are flex-direction: row and align-items: stretch. This means that flex items will automatically align in a single row, and each item will fill the height of the container.

If you don't want flex items to stretch – i.e., like you wrote:

make its height the minimum required for holding its content

... then simply override the default with align-items: flex-start.

_x000D_
_x000D_
#a {_x000D_
  display: flex;_x000D_
  align-items: flex-start; /* NEW */_x000D_
}_x000D_
#a > div {_x000D_
  background-color: red;_x000D_
  padding: 5px;_x000D_
  margin: 2px;_x000D_
}_x000D_
#b {_x000D_
  height: auto;_x000D_
}
_x000D_
<div id="a">_x000D_
  <div id="b">left</div>_x000D_
  <div>_x000D_
    right<br>right<br>right<br>right<br>right<br>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here's an illustration from the flexbox spec that highlights the five values for align-items and how they position flex items within the container. As mentioned before, stretch is the default value.

enter image description here Source: W3C

Jquery: Find Text and replace

$('p:contains("dogsss")').text('dollsss');

CSS @font-face not working in ie

If you're still having troubles with this, here's your solution:

http://www.fontsquirrel.com/fontface/generator

It works far better/faster than any other font-generator and also gives an example for you to use.

Unable to cast object of type 'System.DBNull' to type 'System.String`

With a simple generic function you can make this very easy. Just do this:

return ConvertFromDBVal<string>(accountNumber);

using the function:

public static T ConvertFromDBVal<T>(object obj)
{
    if (obj == null || obj == DBNull.Value)
    {
        return default(T); // returns the default value for the type
    }
    else
    {
        return (T)obj;
    }
}

How to resolve a Java Rounding Double issue

So far the most elegant and most efficient way to do that in Java:

double newNum = Math.floor(num * 100 + 0.5) / 100;

Query to get the names of all tables in SQL Server 2008 Database

another way, will also work on MySQL and PostgreSQL

select TABLE_NAME from INFORMATION_SCHEMA.TABLES
where TABLE_TYPE = 'BASE TABLE'

PHP fwrite new line

How about you store it like this? Maybe in username:password format, so

sebastion:password123
anotheruser:password321

Then you can use list($username,$password) = explode(':',file_get_contents('users.txt')); to parse the data on your end.

Simple way to convert datarow array to datatable

.Net 3.5+ added DataTableExtensions, use DataTableExtensions.CopyToDataTable Method

For datarow array just use .CopyToDataTable() and it will return datatable.

For single datarow use

new DataRow[] { myDataRow }.CopyToDataTable()

CodeIgniter 404 Page Not Found, but why?

If your application is in sub-folder then the Folder name in directory and URL must be same (case-sensitive).

What is the best way to implement nested dictionaries?

I find setdefault quite useful; It checks if a key is present and adds it if not:

d = {}
d.setdefault('new jersey', {}).setdefault('mercer county', {})['plumbers'] = 3

setdefault always returns the relevant key, so you are actually updating the values of 'd' in place.

When it comes to iterating, I'm sure you could write a generator easily enough if one doesn't already exist in Python:

def iterateStates(d):
    # Let's count up the total number of "plumbers" / "dentists" / etc.
    # across all counties and states
    job_totals = {}

    # I guess this is the annoying nested stuff you were talking about?
    for (state, counties) in d.iteritems():
        for (county, jobs) in counties.iteritems():
            for (job, num) in jobs.iteritems():
                # If job isn't already in job_totals, default it to zero
                job_totals[job] = job_totals.get(job, 0) + num

    # Now return an iterator of (job, number) tuples
    return job_totals.iteritems()

# Display all jobs
for (job, num) in iterateStates(d):
    print "There are %d %s in total" % (job, num)

How to get all keys with their values in redis

I had the same problem, and I felt on your post.

I think the easiest way to solve this issue is by using redis Hashtable.

It allows you to save a Hash, with different fields and values associated with every field.

To get all the fiels and values client.HGETALLL does the trick. It returns an array of

all the fields followed by their values.

More informations here https://redis.io/commands/hgetall

How to use PowerShell select-string to find more than one pattern in a file?

You can specify multiple patterns in an array.

select-string VendorEnquiry,Failed C:\Logs

This works with -notmatch as well:

select-string -notmatch VendorEnquiry,Failed C:\Logs

In plain English, what does "git reset" do?

The post Reset Demystified in the blog Pro Git gives a very no-brainer explanation on git reset and git checkout.

After all the helpful discussion at the top of that post, the author reduces the rules to the following simple three steps:

That is basically it. The reset command overwrites these three trees in a specific order, stopping when you tell it to.

  1. Move whatever branch HEAD points to (stop if --soft)
  2. THEN, make the Index look like that (stop here unless --hard)
  3. THEN, make the Working Directory look like that

There are also --merge and --keep options, but I would rather keep things simpler for now - that will be for another article.

How to parse JSON Array (Not Json Object) in Android

public static void main(String[] args) throws JSONException {
    String str = "[{\"name\":\"name1\",\"url\":\"url1\"},{\"name\":\"name2\",\"url\":\"url2\"}]";

    JSONArray jsonarray = new JSONArray(str);


    for(int i=0; i<jsonarray.length(); i++){
        JSONObject obj = jsonarray.getJSONObject(i);

        String name = obj.getString("name");
        String url = obj.getString("url");

        System.out.println(name);
        System.out.println(url);
    }   
}   

Output:

name1
url1
name2
url2

How to apply filters to *ngFor?

A lot of you have great approaches, but the goal here is to be generic and defined a array pipe that is extremely reusable across all cases in relationship to *ngFor.

callback.pipe.ts (don't forget to add this to your module's declaration array)

import { PipeTransform, Pipe } from '@angular/core';

@Pipe({
    name: 'callback',
    pure: false
})
export class CallbackPipe implements PipeTransform {
    transform(items: any[], callback: (item: any) => boolean): any {
        if (!items || !callback) {
            return items;
        }
        return items.filter(item => callback(item));
    }
}

Then in your component, you need to implement a method with the following signuature (item: any) => boolean, in my case for example, I called it filterUser, that filters users' age that are greater than 18 years.

Your Component

@Component({
  ....
})
export class UsersComponent {
  filterUser(user: IUser) {
    return !user.age >= 18
  }
}

And last but not least, your html code will look like this:

Your HTML

<li *ngFor="let user of users | callback: filterUser">{{user.name}}</li>

As you can see, this Pipe is fairly generic across all array like items that need to be filter via a callback. In mycase, I found it to be very useful for *ngFor like scenarios.

Hope this helps!!!

codematrix

How to print spaces in Python?

rjust() and ljust()

test_string = "HelloWorld"

test_string.rjust(20)
'          HelloWorld'

test_string.ljust(20)
'HelloWorld          '

Get pixel color from canvas, on mousemove

I have a very simple working example of geting pixel color from canvas.

First some basic HTML:

<canvas id="myCanvas" width="400" height="250" style="background:red;" onmouseover="echoColor(event)">
</canvas>

Then JS to draw something on the Canvas, and to get color:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "black";
ctx.fillRect(10, 10, 50, 50);

function echoColor(e){
    var imgData = ctx.getImageData(e.pageX, e.pageX, 1, 1);
    red = imgData.data[0];
    green = imgData.data[1];
    blue = imgData.data[2];
    alpha = imgData.data[3];
    console.log(red + " " + green + " " + blue + " " + alpha);  
}

Here is a working example, just look at the console.

How to sort a Pandas DataFrame by index?

Dataframes have a sort_index method which returns a copy by default. Pass inplace=True to operate in place.

import pandas as pd
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df.sort_index(inplace=True)
print(df.to_string())

Gives me:

     A
1    4
29   2
100  1
150  5
234  3

JQuery to load Javascript file dynamically

I realize I am a little late here, (5 years or so), but I think there is a better answer than the accepted one as follows:

$("#addComment").click(function() {
    if(typeof TinyMCE === "undefined") {
        $.ajax({
            url: "tinymce.js",
            dataType: "script",
            cache: true,
            success: function() {
                TinyMCE.init();
            }
        });
    }
});

The getScript() function actually prevents browser caching. If you run a trace you will see the script is loaded with a URL that includes a timestamp parameter:

http://www.yoursite.com/js/tinymce.js?_=1399055841840

If a user clicks the #addComment link multiple times, tinymce.js will be re-loaded from a differently timestampped URL. This defeats the purpose of browser caching.

===

Alternatively, in the getScript() documentation there is a some sample code that demonstrates how to enable caching by creating a custom cachedScript() function as follows:

jQuery.cachedScript = function( url, options ) {

    // Allow user to set any option except for dataType, cache, and url
    options = $.extend( options || {}, {
        dataType: "script",
        cache: true,
        url: url
    });

    // Use $.ajax() since it is more flexible than $.getScript
    // Return the jqXHR object so we can chain callbacks
    return jQuery.ajax( options );
};

// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
    console.log( textStatus );
});

===

Or, if you want to disable caching globally, you can do so using ajaxSetup() as follows:

$.ajaxSetup({
    cache: true
});

How to print object array in JavaScript?

I use the below function to display a readout in firefox console log:

////        make printable string for console readout, recursively
var make_printable_object = function(ar_use)
{
////        internal arguments
var in_tab = arguments[1];
var st_return = arguments[2];
////        default vales when applicable
if (!in_tab) in_tab = 0;
if (!st_return) st_return = "";
////        add depth
var st_tab = "";
for (var i=0; i < in_tab; i++) st_tab = st_tab+"-~-~-";

////        traverse given depth and build string
for (var key in ar_use)
{
    ////        gather return type
    var st_returnType = typeof ar_use[key];
    ////        get current depth display
    var st_returnPrime = st_tab+ "["+key+"] ->"+ar_use[key]+"< is {"+st_returnType+"}";
    ////        remove linefeeds to avoid printout confusion
    st_returnPrime = st_returnPrime.replace(/(\r\n|\n|\r)/gm,"");
    ////        add line feed
    st_return = st_return+st_returnPrime+"\n";
    ////         stop at a depth of 15
    if (in_tab>15) return st_return;
    ////        if current value is an object call this function
    if ( (typeof ar_use[key] == "object") & (ar_use[key] != "null") & (ar_use[key] != null) ) st_return = make_printable_object(ar_use[key], in_tab+1, st_return);


}

////        return complete output
return st_return;

};

Example:

console.log( make_printable_object( some_object ) );

Alternatively, you can just replace:

st_return = st_return+st_returnPrime+"\n";

with

st_return = st_return+st_returnPrime+"<br/>";

to print out in a html page.

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

In My case the issue was fixed by changing the solution platform from AnyCPU to x86.

Node.js request CERT_HAS_EXPIRED

I had this problem on production with Heroku and locally while debugging on my macbook pro this morning.

After an hour of debugging, this resolved on its own both locally and on production. I'm not sure what fixed it, so that's a bit annoying. It happened right when I thought I did something, but reverting my supposed fix didn't bring the problem back :(

Interestingly enough, it appears my database service, MongoDb has been having server problems since this morning, so there's a good chance this was related to it.

enter image description here

What issues should be considered when overriding equals and hashCode in Java?

One gotcha I have found is where two objects contain references to each other (one example being a parent/child relationship with a convenience method on the parent to get all children).
These sorts of things are fairly common when doing Hibernate mappings for example.

If you include both ends of the relationship in your hashCode or equals tests it's possible to get into a recursive loop which ends in a StackOverflowException.
The simplest solution is to not include the getChildren collection in the methods.

Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;

Make sure that "android-support-v4.jar" is unchecked in Order and Export tab under Java Build Path

Follow the steps:

  1. Project Properties
  2. Java Build path
  3. Order and Export
  4. Uncheck "android-support-v4.jar"

How to remove all null elements from a ArrayList or String Array?

We can use iterator for the same to remove all the null values.

Iterator<Tourist> itr= tourists.iterator();
while(itr.hasNext()){
    if(itr.next() == null){
        itr.remove();
    }
}

Datagridview: How to set a cell in editing mode?

private void DgvRoomInformation_CellEnter(object sender, DataGridViewCellEventArgs e)
{
  if (DgvRoomInformation.CurrentCell.ColumnIndex == 4)  //example-'Column index=4'
  {
    DgvRoomInformation.BeginEdit(true);   
  }
}

Selenium and xPath - locating a link by containing text

@FindBy(xpath = "//button[@class='btn btn-primary' and contains(text(), 'Submit')]") private WebElementFacade submitButton;

public void clickOnSubmitButton() {
    submitButton.click();
}   

Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

If you are a student and new to Java there might be some issue going on with your web.xml file.

  1. Try removing the web.xml file.
  2. Secondly check that your path variables are properly set or not.
  3. Restart tomcat server Or your PC.

Your problem will be surely solved.

case statement in where clause - SQL Server

You don't need case in the where statement, just use parentheses and or:

Select * From Times
WHERE StartDate <= @Date AND EndDate >= @Date
AND (
    (@day = 'Monday' AND Monday = 1)
    OR (@day = 'Tuesday' AND Tuesday = 1)
    OR Wednesday = 1
)

Additionally, your syntax is wrong for a case. It doesn't append things to the string--it returns a single value. You'd want something like this, if you were actually going to use a case statement (which you shouldn't):

Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date)
AND 1 = CASE WHEN @day = 'Monday' THEN Monday
             WHEN @day = 'Tuesday' THEN Tuesday
             ELSE Wednesday
        END 

And just for an extra umph, you can use the between operator for your date:

where @Date between StartDate and EndDate

Making your final query:

select
    * 
from 
    Times
where
    @Date between StartDate and EndDate
    and (
        (@day = 'Monday' and Monday = 1)
        or (@day = 'Tuesday' and Tuesday = 1)
        or Wednesday = 1
    )

Move UIView up when the keyboard appears in iOS

try this one:-

 [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector (keyboardDidShow:)
                                                 name: UIKeyboardDidShowNotification object:nil];


[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector (keyboardDidHide:)
                                                 name: UIKeyboardDidHideNotification object:nil];

-(void) keyboardDidShow: (NSNotification *)notif
    {
        CGSize keyboardSize = [[[notif userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
        UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize.height+[self getTableView].tableFooterView.frame.size.height, 0.0);

        [self getTableView].contentInset = contentInsets;
        [self getTableView].scrollIndicatorInsets = contentInsets;

        CGRect rect = self.frame; rect.size.height -= keyboardSize.height;
        if (!CGRectContainsPoint(rect, self.frame.origin))
        {
            CGPoint scrollPoint = CGPointMake(0.0, self.frame.origin.y - (keyboardSize.height - self.frame.size.height));
            [[self getTableView] setContentOffset:scrollPoint animated:YES];
        }
    }

-(void) keyboardDidHide: (NSNotification *)notif
{
    UIEdgeInsets contentInsets = UIEdgeInsetsZero;
    [self getTableView].contentInset = contentInsets;
    [self getTableView].scrollIndicatorInsets = contentInsets;
}

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

json.loads will load a json string into a python dict, json.dumps will dump a python dict to a json string, for example:

>>> json_string = '{"favorited": false, "contributors": null}'
'{"favorited": false, "contributors": null}'
>>> value = json.loads(json_string)
{u'favorited': False, u'contributors': None}
>>> json_dump = json.dumps(value)
'{"favorited": false, "contributors": null}'

So that line is incorrect since you are trying to load a python dict, and json.loads is expecting a valid json string which should have <type 'str'>.

So if you are trying to load the json, you should change what you are loading to look like the json_string above, or you should be dumping it. This is just my best guess from the given information. What is it that you are trying to accomplish?

Also you don't need to specify the u before your strings, as @Cld mentioned in the comments.

Get distance between two points in canvas

To find the distance between 2 points, you need to find the length of the hypotenuse in a right angle triangle with a width and height equal to the vertical and horizontal distance:

Math.hypot(endX - startX, endY - startY)

Sum rows in data.frame or matrix

you can use rowSums

rowSums(data) should give you what you want.

@viewChild not working - cannot read property nativeElement of undefined

What happens is when these elements are called before the DOM is loaded these kind of errors come up. Always use:

 window.onload = function(){
     this.keywordsInput.nativeElement.focus();
 }

Solving a "communications link failure" with JDBC and MySQL

In my case,

  1. Change the remote machine mysql configuration at /etc/mysql/my.cnf: change bind-address = 127.0.0.1 to #bind-address = 127.0.0.1

  2. On the remote machine, change mysql user permissions with GRANT ALL PRIVILEGES ON *.* TO 'user'@'%' IDENTIFIED BY 'password';

  3. IMPORTANT: restart mysql on the remote machine: sudo /etc/init.d/mysql restart

Convert JsonObject to String

I think you need this :

Suppose you have Sample JSON like this :

{"ParamOne":"InnerParamOne":"InnerParamOneValue","InnerParamTwo":"InnerParamTwoValue","InnerParamThree":"InnerParamThreeValue","InnerParamFour":"InnerParamFourValue","InnerParamFive":"InnerParamFiveValue"}}

Converted to String :

String response = {\"ParamOne\":{\"InnerParamOne\":\"InnerParamOneValue\",\"InnerParamTwo\":\"InnerParamTwoValue\",\"InnerParamThree\":\"InnerParamThreeValue\",\"InnerParamFour\":\"InnerParamFourValue\",\"InnerParamFive\":\"InnerParamFiveValue\"}} ;

Just replace " by \"

Highlight all occurrence of a selected word?

Enable search highlighting:

:set hlsearch

Then search for the word:

/word<Enter>

Display alert message and redirect after click on accept

use this code to redirect the page

echo "<script>alert('There are no fields to generate a report');document.location='admin/ahm/panel'</script>";

How to set JAVA_HOME for multiple Tomcat instances?

For Debian distro we can override the setting via defaults

/etc/default/tomcat6

Set the JAVA_HOME pointing to the java version you want.

JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64

How do I read a text file of about 2 GB?

Try Glogg. the fast, smart log explorer.

I have opened log file of size around 2 GB, and the search is also very fast.

SQL Inner join more than two tables

try this method given below, modify to suit your need.

SELECT
  employment_status.staff_type,
  COUNT(monthly_pay_register.age),
  monthly_pay_register.BASIC_SALARY,
  monthly_pay_register.TOTAL_MONTHLY_ALLOWANCES,
  monthly_pay_register.MONTHLY_GROSS,
  monthly_pay_register.TOTAL_MONTHLY_DEDUCTIONS,
  monthly_pay_register.MONTHLY_PAY
FROM 
  (monthly_pay_register INNER JOIN deduction_logs 
ON
  monthly_pay_register.employee_info_employee_no = deduction_logs.employee_no)
INNER JOIN
  employment_status ON deduction_logs.employee_no = employment_status.employee_no
WHERE
  monthly_pay_register.`YEAR`=2017
and 
  monthly_pay_register.`MONTH`='may'

PHP Foreach Arrays and objects

Looping over arrays and objects is a pretty common task, and it's good that you're wanting to learn how to do it. Generally speaking you can do a foreach loop which cycles over each member, assigning it a new temporary name, and then lets you handle that particular member via that name:

foreach ($arr as $item) {
    echo $item->sm_id;
}

In this example each of our values in the $arr will be accessed in order as $item. So we can print our values directly off of that. We could also include the index if we wanted:

foreach ($arr as $index => $item) {
    echo "Item at index {$index} has sm_id value {$item->sm_id}";
}

what do these symbolic strings mean: %02d %01d?

The answer from Alexander refers to complete docs...

Your simple example from the question simply prints out these values with 2 digits - appending leading 0 if necessary.

How to read Excel cell having Date with Apache POI?

Yes, I understood your problem. If is difficult to identify cell has Numeric or Data value.

If you want data in format that shows in Excel, you just need to format cell using DataFormatter class.

DataFormatter dataFormatter = new DataFormatter();
String cellStringValue = dataFormatter.formatCellValue(row.getCell(0));
System.out.println ("Is shows data as show in Excel file" + cellStringValue);  // Here it automcatically format data based on that cell format.
// No need for extra efforts 

Get GMT Time in Java

Odds are good you did the right stuff on the back end in getting the date, but there's nothing to indicate that you didn't take that GMT time and format it according to your machine's current locale.

final Date currentTime = new Date();

final SimpleDateFormat sdf =
        new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");

// Give it to me in GMT time.
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("GMT time: " + sdf.format(currentTime));

The key is to use your own DateFormat, not the system provided one. That way you can set the DateFormat's timezone to what you wish, instead of it being set to the Locale's timezone.

jQuery: If this HREF contains

use this

$("a").each(function () {
    var href=$(this).prop('href');
    if (href.indexOf('?') > -1) {
        alert("Contains questionmark");
    }
});

How to list the certificates stored in a PKCS12 keystore with keytool?

If the keystore is PKCS12 type (.pfx) you have to specify it with -storetype PKCS12 (line breaks added for readability):

keytool -list -v -keystore <path to keystore.pfx> \
    -storepass <password> \
    -storetype PKCS12

.NET Global exception handler in console application

If you have a single-threaded application, you can use a simple try/catch in the Main function, however, this does not cover exceptions that may be thrown outside of the Main function, on other threads, for example (as noted in other comments). This code demonstrates how an exception can cause the application to terminate even though you tried to handle it in Main (notice how the program exits gracefully if you press enter and allow the application to exit gracefully before the exception occurs, but if you let it run, it terminates quite unhappily):

static bool exiting = false;

static void Main(string[] args)
{
   try
   {
      System.Threading.Thread demo = new System.Threading.Thread(DemoThread);
      demo.Start();
      Console.ReadLine();
      exiting = true;
   }
   catch (Exception ex)
   {
      Console.WriteLine("Caught an exception");
   }
}

static void DemoThread()
{
   for(int i = 5; i >= 0; i--)
   {
      Console.Write("24/{0} =", i);
      Console.Out.Flush();
      Console.WriteLine("{0}", 24 / i);
      System.Threading.Thread.Sleep(1000);
      if (exiting) return;
   }
}

You can receive notification of when another thread throws an exception to perform some clean up before the application exits, but as far as I can tell, you cannot, from a console application, force the application to continue running if you do not handle the exception on the thread from which it is thrown without using some obscure compatibility options to make the application behave like it would have with .NET 1.x. This code demonstrates how the main thread can be notified of exceptions coming from other threads, but will still terminate unhappily:

static bool exiting = false;

static void Main(string[] args)
{
   try
   {
      System.Threading.Thread demo = new System.Threading.Thread(DemoThread);
      AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
      demo.Start();
      Console.ReadLine();
      exiting = true;
   }
   catch (Exception ex)
   {
      Console.WriteLine("Caught an exception");
   }
}

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
   Console.WriteLine("Notified of a thread exception... application is terminating.");
}

static void DemoThread()
{
   for(int i = 5; i >= 0; i--)
   {
      Console.Write("24/{0} =", i);
      Console.Out.Flush();
      Console.WriteLine("{0}", 24 / i);
      System.Threading.Thread.Sleep(1000);
      if (exiting) return;
   }
}

So in my opinion, the cleanest way to handle it in a console application is to ensure that every thread has an exception handler at the root level:

static bool exiting = false;

static void Main(string[] args)
{
   try
   {
      System.Threading.Thread demo = new System.Threading.Thread(DemoThread);
      demo.Start();
      Console.ReadLine();
      exiting = true;
   }
   catch (Exception ex)
   {
      Console.WriteLine("Caught an exception");
   }
}

static void DemoThread()
{
   try
   {
      for (int i = 5; i >= 0; i--)
      {
         Console.Write("24/{0} =", i);
         Console.Out.Flush();
         Console.WriteLine("{0}", 24 / i);
         System.Threading.Thread.Sleep(1000);
         if (exiting) return;
      }
   }
   catch (Exception ex)
   {
      Console.WriteLine("Caught an exception on the other thread");
   }
}

Determining if an Object is of primitive type

For those who like terse code.

private static final Set<Class> WRAPPER_TYPES = new HashSet(Arrays.asList(
    Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class, Float.class, Double.class, Void.class));
public static boolean isWrapperType(Class clazz) {
    return WRAPPER_TYPES.contains(clazz);
}

How to embed a YouTube channel into a webpage

I quickly did this for anyone else coming onto this page:

<object width="425" height="344">
<param name="movie" value="http://www.youtube.com/v/u1zgFlCw8Aw?fs=1"</param>
<param name="allowFullScreen" value="true"></param>
<param name="allowScriptAccess" value="always"></param>
<embed src="http://www.youtube.com/v/u1zgFlCw8Aw?fs=1"
  type="application/x-shockwave-flash"
  allowfullscreen="true"
  allowscriptaccess="always"
  width="425" height="344">
</embed>
</object>

See the jsFiddle.

How to include a class in PHP

You can use either of the following:

include "class.twitter.php";

or

require "class.twitter.php";

Using require (or require_once if you want to ensure the class is only loaded once during execution) will cause a fatal error to be raised if the file doesn't exist, whereas include will only raise a warning. See http://php.net/require and http://php.net/include for more details

Authenticate Jenkins CI for Github private repository

Another option is to use GitHub personal access tokens:

  • Go to https://github.com/settings/tokens/new
  • Add repo scope
  • In Jenkins, add a GitHub source
  • Use Repository HTTPS URL
  • Add the HTTPS URL of the git repo (not the SSH one, eg. https://github.com/my-username/my-project.git)
  • Add credential
    • Kind: Username with Password
    • Username: the GitHub username
    • Password: the personal access token you created on GitHub
    • ID: something like github-token-for-my-username

I tested this on Jenkins ver. 2.222.1 and Jenkins GitHub plugin 1.29.5 with a private GitHub repo.

How do I return to an older version of our code in Subversion?

I think this is most suited:

Do the merging backward, for instance, if the committed code contains the revision from rev 5612 to 5616, just merge it backwards. It works in my end.

For instance:

svn merge -r 5616:5612 https://<your_svn_repository>/

It would contain a merged code back to former revision, then you could commit it.

Installation of SQL Server Business Intelligence Development Studio

If you have installed SQL 2005 express edition and want to install BIDS (Business Intelligence Development Studio) then go to here Microsoft SQL Server 2005 Express Edition Toolkit

This has an option to install BIDS on my machine, and is the only way l could get hold of BIDS for SQL Server 2005 express edition.

Also this package l think has also allowed me to install both BIDS 2005 & 2008 express edition on the same machine.

Launch an event when checking a checkbox in Angular2

You can use ngModel like

<input type="checkbox" [ngModel]="checkboxValue" (ngModelChange)="addProp($event)" data-md-icheck/>

To update the checkbox state by updating the property checkboxValue in your code and when the checkbox is changed by the user addProp() is called.

Window vs Page vs UserControl for WPF navigation?

A Window object is just what it sounds like: its a new Window for your application. You should use it when you want to pop up an entirely new window. I don't often use more than one Window in WPF because I prefer to put dynamic content in my main Window that changes based on user action.

A Page is a page inside your Window. It is mostly used for web-based systems like an XBAP, where you have a single browser window and different pages can be hosted in that window. It can also be used in Navigation Applications like sellmeadog said.

A UserControl is a reusable user-created control that you can add to your UI the same way you would add any other control. Usually I create a UserControl when I want to build in some custom functionality (for example, a CalendarControl), or when I have a large amount of related XAML code, such as a View when using the MVVM design pattern.

When navigating between windows, you could simply create a new Window object and show it

var NewWindow = new MyWindow();
newWindow.Show();

but like I said at the beginning of this answer, I prefer not to manage multiple windows if possible.

My preferred method of navigation is to create some dynamic content area using a ContentControl, and populate that with a UserControl containing whatever the current view is.

<Window x:Class="MyNamespace.MainWindow" ...>
    <DockPanel>
        <ContentControl x:Name="ContentArea" />
    </DockPanel>
</Window>

and in your navigate event you can simply set it using

ContentArea.Content = new MyUserControl();

But if you're working with WPF, I'd highly recommend the MVVM design pattern. I have a very basic example on my blog that illustrates how you'd navigate using MVVM, using this pattern:

<Window x:Class="SimpleMVVMExample.ApplicationView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:SimpleMVVMExample"
        Title="Simple MVVM Example" Height="350" Width="525">

   <Window.Resources>
      <DataTemplate DataType="{x:Type local:HomeViewModel}">
         <local:HomeView /> <!-- This is a UserControl -->
      </DataTemplate>
      <DataTemplate DataType="{x:Type local:ProductsViewModel}">
         <local:ProductsView /> <!-- This is a UserControl -->
      </DataTemplate>
   </Window.Resources>

   <DockPanel>
      <!-- Navigation Buttons -->
      <Border DockPanel.Dock="Left" BorderBrush="Black"
                                    BorderThickness="0,0,1,0">
         <ItemsControl ItemsSource="{Binding PageViewModels}">
            <ItemsControl.ItemTemplate>
               <DataTemplate>
                  <Button Content="{Binding Name}"
                          Command="{Binding DataContext.ChangePageCommand,
                             RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
                          CommandParameter="{Binding }"
                          Margin="2,5"/>
               </DataTemplate>
            </ItemsControl.ItemTemplate>
         </ItemsControl>
      </Border>

      <!-- Content Area -->
      <ContentControl Content="{Binding CurrentPageViewModel}" />
   </DockPanel>
</Window>

Screenshot1 Screenshot2

Using external images for CSS custom cursors

cursor:url('http://www.javascriptkit.com/dhtmltutors/cursor-hand.gif'), auto

NOTE 1: In some cases you should consider setting the offset (anchor):

cursor:url(http://www.javascriptkit.com/dhtmltutors/cursor-hand.gif) 10 3, auto;

in this exmple, we set offsetx to 10 and offsety to 3 (from top left), so the pointer finger will be anchor. fiddle: http://jsfiddle.net/5kxt1j98/ (you can see the difference by moving cursor to top left of container)


NOTE 2: THE MAX CURSOR SIZE IS 128*128, recommended one is below 32*32.

How can I specify a local gem in my Gemfile?

In order to use local gem repository in a Rails project, follow the steps below:

  1. Check if your gem folder is a git repository (the command is executed in the gem folder)

    git rev-parse --is-inside-work-tree
    
  2. Getting repository path (the command is executed in the gem folder)

    git rev-parse --show-toplevel
    
  3. Setting up a local override for the rails application

    bundle config local.GEM_NAME /path/to/local/git/repository
    

    where GEM_NAME is the name of your gem and /path/to/local/git/repository is the output of the command in point 2

  4. In your application Gemfile add the following line:

    gem 'GEM_NAME', :github => 'GEM_NAME/GEM_NAME', :branch => 'master'
    
  5. Running bundle install should give something like this:

    Using GEM_NAME (0.0.1) from git://github.com/GEM_NAME/GEM_NAME.git (at /path/to/local/git/repository) 
    

    where GEM_NAME is the name of your gem and /path/to/local/git/repository from point 2

  6. Finally, run bundle list, not gem list and you should see something like this:

    GEM_NAME (0.0.1 5a68b88)
    

    where GEM_NAME is the name of your gem


A few important cases I am observing using:

Rails 4.0.2  
ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux] 
Ubuntu 13.10  
RubyMine 6.0.3
  • It seems RubyMine is not showing local gems as an external library. More information about the bug can be found here and here
  • When I am changing something in the local gem, in order to be loaded in the rails application I should stop/start the rails server
  • If I am changing the version of the gem, stopping/starting the Rails server gives me an error. In order to fix it, I am specifying the gem version in the rails application Gemfile like this:

    gem 'GEM_NAME', '0.0.2', :github => 'GEM_NAME/GEM_NAME', :branch => 'master'
    

How to increase the max upload file size in ASP.NET?

I believe this line in the web.config will set the max upload size:

<system.web>

        <httpRuntime maxRequestLength="600000"/>
</system.web>

Detecting IE11 using CSS Capability/Feature Detection

I ran into the same problem with a Gravity Form (WordPress) in IE11. The form's column style "display: inline-grid" broke the layout; applying the answers above resolved the discrepancy!

@media all and (-ms-high-contrast:none){
  *::-ms-backdrop, .gfmc-column { display: inline-block;} /* IE11 */
}

How to remove spaces from a string using JavaScript?

This?

str = str.replace(/\s/g, '');

Example

_x000D_
_x000D_
var str = '/var/www/site/Brand new document.docx';_x000D_
_x000D_
document.write( str.replace(/\s/g, '') );
_x000D_
_x000D_
_x000D_


Update: Based on this question, this:

str = str.replace(/\s+/g, '');

is a better solution. It produces the same result, but it does it faster.

The Regex

\s is the regex for "whitespace", and g is the "global" flag, meaning match ALL \s (whitespaces).

A great explanation for + can be found here.

As a side note, you could replace the content between the single quotes to anything you want, so you can replace whitespace with any other string.

Using jquery to get all checked checkboxes with a certain class name

$("input[name='<your_name_of_selected_group_checkboxes>']:checked").val()

IndexOf function in T-SQL

One very small nit to pick:

The RFC for email addresses allows the first part to include an "@" sign if it is quoted. Example:

"john@work"@myemployer.com

This is quite uncommon, but could happen. Theoretically, you should split on the last "@" symbol, not the first:

SELECT LEN(EmailField) - CHARINDEX('@', REVERSE(EmailField)) + 1

More information:

http://en.wikipedia.org/wiki/Email_address

Safest way to convert float to integer in python?

You could use the round function. If you use no second parameter (# of significant digits) then I think you will get the behavior you want.

IDLE output.

>>> round(2.99999999999)
3
>>> round(2.6)
3
>>> round(2.5)
3
>>> round(2.4)
2

how to convert from int to char*?

Alright.. firstly I needed something that did what this question is asking, but I needed it FAST! Unfortunately the "better" way is nearly 600 lines of code!!! Pardon the name of it that doesn't have anything to do with what it's doing. Proper name was Integer64ToCharArray(int64_t value);

https://github.com/JeremyDX/All-Language-Testing-Code/blob/master/C%2B%2B%20Examples/IntegerToCharArrayTesting.cpp

Feel free to try cleaning that code up without hindering performance.

Input: Any signed 64 bit value from min to max range.

Example:

std::cout << "Test: " << AddDynamicallyToBuffer(LLONG_MAX) << '\n';
std::cout << "Test: " << AddDynamicallyToBuffer(LLONG_MIN) << '\n';

Output:

Test: 9223372036854775807
Test: -9223372036854775808

Original Speed Tests: (Integer64ToCharArray();)

Best case 1 digit value.

Loops: 100,000,000, Time Spent: 1,381(Milli), Time Per Loop 13(Nano)

Worse Case 20 Digit Value.

Loops: 100,000,000, Time Spent: 22,656(Milli), Time Per Loop 226(Nano

New Design Speed Tests: (AddDynamicallyToBuffer();)

Best case 1 digit value.

Loops: 100,000,000, Time Spent: 427(Milli), Time Per Loop 4(Nano)

32 Bit Worst Case - 11 digit Value.

Loops: 100,000,000, Time Spent: 1,991(Milli), Time Per Loop 19(Nano)

Negative 1 Trillion Worst Case - 14 digit Value.

Loops: 100,000,000, Time Spent: 5,681(Milli), Time Per Loop 56(Nano)

64 Bit Worse Case - 20 Digit Value.

Loops: 100,000,000, Time Spent: 13,148(Milli), Time Per Loop 131(Nano)

How It Works!

We Perform a Divide and Conquer technique and once we now the maximum length of the string we simply set each character value individually. As shown in above speed tests the larger lengths get big performance penalties, but it's still far faster then the original loop method and no code has actually changed between the two methods other then looping is no longer in use.

In my usage hence the name I return the offset instead and I don't edit a buffer of char arrays rather I begin updating vertex data and the function has an additional parameter for offset so it's not initialized to -1.

CSS: How to position two elements on top of each other, without specifying a height?

I had to set

Container_height = Element1_height = Element2_height

.Container {
    position: relative;
}

.ElementOne, .Container ,.ElementTwo{
    width: 283px;
    height: 71px;
}

.ElementOne {
    position:absolute;
}

.ElementTwo{
    position:absolute;
}

Use can use z-index to set which one to be on top.

Create a new RGB OpenCV image using Python?

The new cv2 interface for Python integrates numpy arrays into the OpenCV framework, which makes operations much simpler as they are represented with simple multidimensional arrays. For example, your question would be answered with:

import cv2  # Not actually necessary if you just want to create an image.
import numpy as np
blank_image = np.zeros((height,width,3), np.uint8)

This initialises an RGB-image that is just black. Now, for example, if you wanted to set the left half of the image to blue and the right half to green , you could do so easily:

blank_image[:,0:width//2] = (255,0,0)      # (B, G, R)
blank_image[:,width//2:width] = (0,255,0)

If you want to save yourself a lot of trouble in future, as well as having to ask questions such as this one, I would strongly recommend using the cv2 interface rather than the older cv one. I made the change recently and have never looked back. You can read more about cv2 at the OpenCV Change Logs.

How do I instantiate a JAXBElement<String> object?

When you imported the WSDL, you should have an ObjectFactory class which should have bunch of methods for creating various input parameters.

ObjectFactory factory = new ObjectFactory();
JAXBElement<String> createMessageDescription = factory.createMessageDescription("description");
message.setDescription(createMessageDescription);

How to get a Char from an ASCII Character Code in c#

You can simply write:

char c = (char) 2;

or

char c = Convert.ToChar(2);

or more complex option for ASCII encoding only

char[] characters = System.Text.Encoding.ASCII.GetChars(new byte[]{2});
char c = characters[0];

write newline into a file

Change the lines

if(nodeValue!=null)
    fop.write(nodeValue.getBytes());

fop.flush();

to

if(nodeValue!=null) {
    fop.write(nodeValue.getBytes());
    fop.write(System.getProperty("line.separator").getBytes());
}

fop.flush();

Update to address your edit:

In order to write each word on a different line, you need to split up your input string and then write each word separately.

private static void GetText(String nodeValue) throws IOException {

    if(!file3.exists()) {
        file3.createNewFile();
    }

    FileOutputStream fop=new FileOutputStream(file3,true);
    if(nodeValue!=null)
        for(final String s : nodeValue.split(" ")){
            fop.write(s.getBytes());
            fop.write(System.getProperty("line.separator").getBytes());
        }
    }

    fop.flush();
    fop.close();

}

How to debug heap corruption errors?

I had a similar problem - and it popped up quite randomly. Perhaps something was corrupt in the build files, but I ended up fixing it by cleaning the project first then rebuilding.

So in addition to the other responses given:

What sort of things can cause these errors? Something corrupt in the build file.

How do I debug them? Cleaning the project and rebuilding. If it's fixed, this was likely the problem.

Transform only one axis to log10 scale with ggplot2

I had a similar problem and this scale worked for me like a charm:

breaks = 10**(1:10)
scale_y_log10(breaks = breaks, labels = comma(breaks))

as you want the intermediate levels, too (10^3.5), you need to tweak the formatting:

breaks = 10**(1:10 * 0.5)
m <- ggplot(diamonds, aes(y = price, x = color)) + geom_boxplot()
m + scale_y_log10(breaks = breaks, labels = comma(breaks, digits = 1))

After executing::

enter image description here

how to evenly distribute elements in a div next to each other?

You can use justify.

This is similar to the other answers, except that the left and rightmost elements will be at the edges instead of being equally spaced - [a...b...c instead of .a..b..c.]

<div class="menu">
    <span>1</span>
    <span>2</span>
    <span>3</span>
</div>

<style>
.menu {text-align:justify;}
.menu:after { content:' '; display:inline-block; width: 100%; height: 0 }
.menu > span {display:inline-block} 
</style>

One gotcha is that you must leave spaces in between each element. [See the fiddle.]

There are two reasons to set the menu items to inline-block:

  1. If the element is by default a block level item (such as an <li>) the display must be set to inline or inline-block to stay in the same line.
  2. If the element has more than one word (<span>click here</span>), each word will be distributed evenly when set to inline, but only the elements will be distributed when set to inline-block.

See the JSFiddle

EDIT:
Now that flexbox has wide support (all non-IE, and IE 10+), there is a "better way".
Assuming the same element structure as above, all you need is:

<style>
    .menu { display: flex; justify-content: space-between; }
</style>

If you want the outer elements to be spaced as well, just switch space-between to space-around.
See the JSFiddle

Error importing SQL dump into MySQL: Unknown database / Can't create database

If you create your database in direct admin or cpanel, you must edit your sql with notepad or notepad++ and change CREATE DATABASE command to CREATE DATABASE IF NOT EXISTS in line22

Node.js - How to send data from html to express

Using http.createServer is very low-level and really not useful for creating web applications as-is.

A good framework to use on top of it is Express, and I would seriously suggest using it. You can install it using npm install express.

When you have, you can create a basic application to handle your form:

var express = require('express');
var bodyParser = require('body-parser');
var app     = express();

//Note that in version 4 of express, express.bodyParser() was
//deprecated in favor of a separate 'body-parser' module.
app.use(bodyParser.urlencoded({ extended: true })); 

//app.use(express.bodyParser());

app.post('/myaction', function(req, res) {
  res.send('You sent the name "' + req.body.name + '".');
});

app.listen(8080, function() {
  console.log('Server running at http://127.0.0.1:8080/');
});

You can make your form point to it using:

<form action="http://127.0.0.1:8080/myaction" method="post">

The reason you can't run Node on port 80 is because there's already a process running on that port (which is serving your index.html). You could use Express to also serve static content, like index.html, using the express.static middleware.

What is the maximum length of data I can put in a BLOB column in MySQL?

A BLOB can be 65535 bytes maximum. If you need more consider using a MEDIUMBLOB for 16777215 bytes or a LONGBLOB for 4294967295 bytes.

Hope, it will help you.

Header div stays at top, vertical scrolling div below with scrollbar only attached to that div

HTML:

?<div class="header">This is the header</div>
<div class="content">This is the content</div>?????????????????????????????????

CSS:

?.header
{
    height:50px;
}
.content
{
    position:absolute;
    top: 50px;
    left:0px;
    right:0px;
    bottom:0px;
    overflow-y:scroll;        
}?

SQLite UPSERT / UPDATE OR INSERT

This is a late answer. Starting from SQLIte 3.24.0, released on June 4, 2018, there is finally a support for UPSERT clause following PostgreSQL syntax.

INSERT INTO players (user_name, age)
  VALUES('steven', 32) 
  ON CONFLICT(user_name) 
  DO UPDATE SET age=excluded.age;

Note: For those having to use a version of SQLite earlier than 3.24.0, please reference this answer below (posted by me, @MarqueIV).

However if you do have the option to upgrade, you are strongly encouraged to do so as unlike my solution, the one posted here achieves the desired behavior in a single statement. Plus you get all the other features, improvements and bug fixes that usually come with a more recent release.

Convert data file to blob

As pointed in the comments, file is a blob:

file instanceof Blob; // true

And you can get its content with the file reader API https://developer.mozilla.org/en/docs/Web/API/FileReader

Read more: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

_x000D_
_x000D_
var input = document.querySelector('input[type=file]');
var textarea = document.querySelector('textarea');

function readFile(event) {
  textarea.textContent = event.target.result;
  console.log(event.target.result);
}

function changeFile() {
  var file = input.files[0];
  var reader = new FileReader();
  reader.addEventListener('load', readFile);
  reader.readAsText(file);
}

input.addEventListener('change', changeFile);
_x000D_
<input type="file">
<textarea rows="10" cols="50"></textarea>
_x000D_
_x000D_
_x000D_

c# - approach for saving user settings in a WPF application?

You can store your settings info as Strings of XML in the Settings.Default. Create some classes to store your configuration data and make sure they are [Serializable]. Then, with the following helpers, you can serialize instances of these objects--or List<T> (or arrays T[], etc.) of them--to String. Store each of these various strings in its own respective Settings.Default slot in your WPF application's Settings.

To recover the objects the next time the app starts, read the Settings string of interest and Deserialize to the expected type T (which this time must be explcitly specified as a type argument to Deserialize<T>).

public static String Serialize<T>(T t)
{
    using (StringWriter sw = new StringWriter())
    using (XmlWriter xw = XmlWriter.Create(sw))
    {
        new XmlSerializer(typeof(T)).Serialize(xw, t);
        return sw.GetStringBuilder().ToString();
    }
}

public static T Deserialize<T>(String s_xml)
{
    using (XmlReader xw = XmlReader.Create(new StringReader(s_xml)))
        return (T)new XmlSerializer(typeof(T)).Deserialize(xw);
}

How to convert a data frame column to numeric type?

To convert a data frame column to numeric you just have to do:-

factor to numeric:-

data_frame$column <- as.numeric(as.character(data_frame$column))

What's the syntax to import a class in a default package in Java?

You can't import classes from the default package. You should avoid using the default package except for very small example programs.

From the Java language specification:

It is a compile time error to import a type from the unnamed package.

There can be only one auto column

The full error message sounds:

ERROR 1075 (42000): Incorrect table definition; there can be only one auto column and it must be defined as a key

So add primary key to the auto_increment field:

CREATE TABLE book (
   id INT AUTO_INCREMENT primary key NOT NULL,
   accepted_terms BIT(1) NOT NULL,
   accepted_privacy BIT(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

How to change the name of a Django app?

If you use Pycharm, renaming an app is very easy with refactoring(Shift+F6 default) for all project files.
But make sure you delete the __pycache__ folders in the project directory & its sub-directories. Also be careful as it also renames comments too which you can exclude in the refactor preview window it will show you.
And you'll have to rename OldNameConfig(AppConfig): in apps.py of your renamed app in addition.

If you do not want to lose data of your database, you'll have to manually do it with query in database like the aforementioned answer.

Should I use PATCH or PUT in my REST API?

The PATCH method is the correct choice here as you're updating an existing resource - the group ID. PUT should only be used if you're replacing a resource in its entirety.

Further information on partial resource modification is available in RFC 5789. Specifically, the PUT method is described as follows:

Several applications extending the Hypertext Transfer Protocol (HTTP) require a feature to do partial resource modification. The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.

How to implement endless list with RecyclerView?

Although there are so many answers to the question, I would like to share our experience of creating the endless list view. We have recently implemented custom Carousel LayoutManager that can work in the cycle by scrolling the list infinitely as well as up to a certain point. Here is a detailed description on GitHub.

I suggest you take a look at this article with short but valuable recommendations on creating custom LayoutManagers: http://cases.azoft.com/create-custom-layoutmanager-android/

for each loop in groovy

This one worked for me:

def list = [1,2,3,4]
for(item in list){
    println item
}

Source: Wikia.

How to check if an object is defined?

You check if it's null in C# like this:

if(MyObject != null) {
  //do something
}

If you want to check against default (tough to understand the question on the info given) check:

if(MyObject != default(MyObject)) {
 //do something
}

How can I print out just the index of a pandas dataframe?

You can use lamba function:

index = df.index[lambda x : for x in df.index() ]
print(index)

REST API - Bulk Create or Update in single request

In a project I worked at we solved this problem by implement something we called 'Batch' requests. We defined a path /batch where we accepted json in the following format:

[  
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 1,
         binder: 1
      }
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 5,
         binder: 8
      }
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 6,
         binder: 3
      }
   },
]

The response have the status code 207 (Multi-Status) and looks like this:

[  
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 1,
         binder: 1
      }
      status: 200
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         error: {
            msg: 'A document with doc_number 5 already exists'
            ...
         }
      },
      status: 409
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 6,
         binder: 3
      },
      status: 200
   },
]

You could also add support for headers in this structure. We implemented something that proved useful which was variables to use between requests in a batch, meaning we can use the response from one request as input to another.

Facebook and Google have similar implementations:
https://developers.google.com/gmail/api/guides/batch
https://developers.facebook.com/docs/graph-api/making-multiple-requests

When you want to create or update a resource with the same call I would use either POST or PUT depending on the case. If the document already exist, do you want the entire document to be:

  1. Replaced by the document you send in (i.e. missing properties in request will be removed and already existing overwritten)?
  2. Merged with the document you send in (i.e. missing properties in request will not be removed and already existing properties will be overwritten)?

In case you want the behavior from alternative 1 you should use a POST and in case you want the behavior from alternative 2 you should use PUT.

http://restcookbook.com/HTTP%20Methods/put-vs-post/

As people already suggested you could also go for PATCH, but I prefer to keep API's simple and not use extra verbs if they are not needed.

Android Transparent TextView?

Use this:

android:background="@android:color/transparent"

How do you tell if a string contains another string in POSIX sh?

test $(echo "stringcontain" "ingcon" |awk '{ print index($1, $2) }') -gt 0 && echo "String 1 contain string 2"

--> output: String 1 contain string 2

How do you truncate all tables in a database using TSQL?

The hardest part of truncating all tables is removing and re-ading the foreign key constraints.

The following query creates the drop & create statements for each constraint relating to each table name in @myTempTable. If you would like to generate these for all the tables, you may simple use information schema to gather these table names instead.

DECLARE @myTempTable TABLE (tableName varchar(200))
INSERT INTO @myTempTable(tableName) VALUES
('TABLE_ONE'),
('TABLE_TWO'),
('TABLE_THREE')


-- DROP FK Contraints
SELECT 'alter table '+quotename(schema_name(ob.schema_id))+
  '.'+quotename(object_name(ob.object_id))+ ' drop constraint ' + quotename(fk.name) 
  FROM sys.objects ob INNER JOIN sys.foreign_keys fk ON fk.parent_object_id = ob.object_id
  WHERE fk.referenced_object_id IN 
      (
         SELECT so.object_id 
         FROM sys.objects so JOIN sys.schemas sc
         ON so.schema_id = sc.schema_id
         WHERE so.name IN (SELECT * FROM @myTempTable)  AND sc.name=N'dbo'  AND type in (N'U'))


 -- CREATE FK Contraints
 SELECT 'ALTER TABLE [PIMSUser].[dbo].[' +cast(c.name as varchar(255)) + '] WITH NOCHECK ADD CONSTRAINT ['+ cast(f.name as varchar(255)) +'] FOREIGN KEY (['+ cast(fc.name as varchar(255)) +'])
      REFERENCES [PIMSUser].[dbo].['+ cast(p.name as varchar(255)) +'] (['+cast(rc.name as varchar(255))+'])'
FROM  sysobjects f
      INNER JOIN sys.sysobjects c ON f.parent_obj = c.id
      INNER JOIN sys.sysreferences r ON f.id = r.constid
      INNER JOIN sys.sysobjects p ON r.rkeyid = p.id
      INNER JOIN sys.syscolumns rc ON r.rkeyid = rc.id and r.rkey1 = rc.colid
      INNER JOIN sys.syscolumns fc ON r.fkeyid = fc.id and r.fkey1 = fc.colid
WHERE 
      f.type = 'F'
      AND
      cast(p.name as varchar(255)) IN (SELECT * FROM @myTempTable)

I then just copy out the statements to run - but with a bit of dev effort you could use a cursor to run them dynamically.

clearing select using jquery

Here is a small jQuery plugin that (among other things) can empty an dropdown list.

Just write:

$('your-select-element').selectUtils('setEmpty');

Rename Pandas DataFrame Index

The currently selected answer does not mention the rename_axis method which can be used to rename the index and column levels.


Pandas has some quirkiness when it comes to renaming the levels of the index. There is also a new DataFrame method rename_axis available to change the index level names.

Let's take a look at a DataFrame

df = pd.DataFrame({'age':[30, 2, 12],
                       'color':['blue', 'green', 'red'],
                       'food':['Steak', 'Lamb', 'Mango'],
                       'height':[165, 70, 120],
                       'score':[4.6, 8.3, 9.0],
                       'state':['NY', 'TX', 'FL']},
                       index = ['Jane', 'Nick', 'Aaron'])

enter image description here

This DataFrame has one level for each of the row and column indexes. Both the row and column index have no name. Let's change the row index level name to 'names'.

df.rename_axis('names')

enter image description here

The rename_axis method also has the ability to change the column level names by changing the axis parameter:

df.rename_axis('names').rename_axis('attributes', axis='columns')

enter image description here

If you set the index with some of the columns, then the column name will become the new index level name. Let's append to index levels to our original DataFrame:

df1 = df.set_index(['state', 'color'], append=True)
df1

enter image description here

Notice how the original index has no name. We can still use rename_axis but need to pass it a list the same length as the number of index levels.

df1.rename_axis(['names', None, 'Colors'])

enter image description here

You can use None to effectively delete the index level names.


Series work similarly but with some differences

Let's create a Series with three index levels

s = df.set_index(['state', 'color'], append=True)['food']
s

       state  color
Jane   NY     blue     Steak
Nick   TX     green     Lamb
Aaron  FL     red      Mango
Name: food, dtype: object

We can use rename_axis similarly to how we did with DataFrames

s.rename_axis(['Names','States','Colors'])

Names  States  Colors
Jane   NY      blue      Steak
Nick   TX      green      Lamb
Aaron  FL      red       Mango
Name: food, dtype: object

Notice that the there is an extra piece of metadata below the Series called Name. When creating a Series from a DataFrame, this attribute is set to the column name.

We can pass a string name to the rename method to change it

s.rename('FOOOOOD')

       state  color
Jane   NY     blue     Steak
Nick   TX     green     Lamb
Aaron  FL     red      Mango
Name: FOOOOOD, dtype: object

DataFrames do not have this attribute and infact will raise an exception if used like this

df.rename('my dataframe')
TypeError: 'str' object is not callable

Prior to pandas 0.21, you could have used rename_axis to rename the values in the index and columns. It has been deprecated so don't do this

Browser detection

I would not advise hacking browser-specific things manually with JS. Either use a javascript library like "prototype" or "jquery", which will handle all the specific issues transparently.

Or use these libs to determine the browser type if you really must.

Also see Browser & version in prototype library?

PHP/MySQL insert row then get 'id'

The MySQL function LAST_INSERT_ID() does just what you need: it retrieves the id that was inserted during this session. So it is safe to use, even if there are other processes (other people calling the exact same script, for example) inserting values into the same table.

The PHP function mysql_insert_id() does the same as calling SELECT LAST_INSERT_ID() with mysql_query().

jQuery multiple events to trigger the same function

The answer by Tatu is how I would intuitively do it, but I have experienced some problems in Internet Explorer with this way of nesting/binding the events, even though it is done through the .on() method.

I havn't been able to pinpoint exactly which versions of jQuery this is the problem with. But I sometimes see the problem in the following versions:

  • 2.0.2
  • 1.10.1
  • 1.6.4
  • Mobile 1.3.0b1
  • Mobile 1.4.2
  • Mobile 1.2.0

My workaround have been to first define the function,

function myFunction() {
    ...
}

and then handle the events individually

// Call individually due to IE not handling binds properly
$(window).on("scroll", myFunction);
$(window).on("resize", myFunction);

This is not the prettiest solution, but it works for me, and I thought I would put it out there to help others that might stumble upon this issue

Unable to verify leaf signature

Following commands worked for me :

> npm config set strict-ssl false
> npm cache clean --force

The problem is that you are attempting to install a module from a repository with a bad or untrusted SSL[Secure Sockets Layer] certificate. Once you clean the cache, this problem will be resolved.You might need to turn it to true later on.

How to pass a parameter to routerLink that is somewhere inside the URL?

Maybe it is really late answer but if you want to navigate another page with param you can,

[routerLink]="['/user', user.id, 'details']"

also you shouldn't forget about routing config like ,

 [path: 'user/:id/details', component:userComponent, pathMatch: 'full']

C++ vector's insert & push_back difference

The functions have different purposes. vector::insert allows you to insert an object at a specified position in the vector, whereas vector::push_back will just stick the object on the end. See the following example:

using namespace std;
vector<int> v = {1, 3, 4};
v.insert(next(begin(v)), 2);
v.push_back(5);
// v now contains {1, 2, 3, 4, 5}

You can use insert to perform the same job as push_back with v.insert(v.end(), value).

How To fix white screen on app Start up?

You should read this great post by Cyril Mottier: Android App launching made gorgeous

You need to customise your Theme in style.xml and avoid to customise in your onCreate as ActionBar.setIcon/setTitle/etc.

See also the Documentation on Performance Tips by Google.

Use Trace View and Hierarchy Viewer to see the time to display your Views: Android Performance Optimization / Performance Tuning On Android

Use AsyncTask to display some views.

Entity Framework Refresh context?

Use the Refresh method:

context.Refresh(RefreshMode.StoreWins, yourEntity);

or in alternative dispose your current context and create a new one.

PostgreSQL: days/months/years between two dates

One more solution, version for the 'years' difference:

SELECT count(*) - 1 FROM (SELECT distinct(date_trunc('year', generate_series('2010-04-01'::timestamp, '2012-03-05', '1 week')))) x

    2

(1 row)

And the same trick for the months:

SELECT count(*) - 1 FROM (SELECT distinct(date_trunc('month', generate_series('2010-04-01'::timestamp, '2012-03-05', '1 week')))) x

   23

(1 row)

In real life query there can be some timestamp sequences grouped by hour/day/week/etc instead of generate_series.

This 'count(distinct(date_trunc('month', ts)))' can be used right in the 'left' side of the select:

SELECT sum(a - b)/count(distinct(date_trunc('month', c))) FROM d

I used generate_series() here just for the brevity.

Posting array from form

If you want everything in your post to be as $Variables you can use something like this:

foreach($_POST as $key => $value) { eval("$" . $key . " = " . $value"); }

How can I insert a line break into a <Text> component in React Native?

this is a nice question , you can do this in multiple ways First

<View>
    <Text>
        Hi this is first line  {\n}  hi this is second line 
    </Text>
</View>

which means you can use {\n} backslash n to break the line

Second

<View>
     <Text>
         Hi this is first line
     </Text>
     <View>
         <Text>
             hi this is second line 
         </Text>
     </View>
</View>

which means you can use another <View> component inside first <View> and wrap it around <Text> component

Happy Coding

Can't use System.Windows.Forms

Ensure Solution Explorer is visible In MS Studio 2008 Go to view and click Solution explorer

In Solution explorer go to Reference Right click on Reference and select Add Reference.. Select .NET tab Scroll down till you find System.Drawing -> select it -> click on OK button Do the same for System.Windows.Forms

When you run your form this will work

(eddie lives somewhere in time)

xxxxxx.exe is not a valid Win32 application

I had the same issue on Windows XP when running an application built with a static version of Qt 5.7.0 (MSVC 2013).

Adding the following line to the project's .pro file solved it:

QMAKE_LFLAGS_WINDOWS = /SUBSYSTEM:WINDOWS,5.01

How do I download and save a file locally on iOS using objective C?

Sometime ago I implemented an easy to use "download manager" library: PTDownloadManager. You could give it a shot!

DIV table colspan: how?

In order to get "colspan" functionality out of div based tabular layout, you need to abandon the use of the display:table | display:row styles. Especially in cases where each data item spans more than one row and you need different sized "cells" in each row.

What's the best way to build a string of delimited items in Java?

If you are using Spring MVC then you can try following steps.

import org.springframework.util.StringUtils;

List<String> groupIds = new List<String>;   
groupIds.add("a");    
groupIds.add("b");    
groupIds.add("c");

String csv = StringUtils.arrayToCommaDelimitedString(groupIds.toArray());

It will result to a,b,c

ExpressJS - throw er Unhandled error event

->check what’s running on port 8080 or what ever port u want to check

lsof -i @localhost:8080

if something is running u can close it or use some kill command to close it

adb shell command to make Android package uninstall dialog appear

Using ADB, you can use any of the following three commands:

adb shell am start -a android.intent.action.UNINSTALL_PACKAGE -d "package:PACKAGE"
adb shell am start -n com.android.packageinstaller/.UninstallerActivity -d "package:PACKAGE"
adb shell am start -a android.intent.action.DELETE -d "package:PACKAGE"

Replace PACKAGE with package name of the installed user app. The app mustn't be a device administrator for the command to work successfully. All of those commands would require user's confirmation for removal of app.

Details of the said command can be known by checking am's usage using adb shell am.

I got the info about those commands using Elixir 2 (use any equivalent app). I used it to show the activities of Package Installer app (the GUI that you see during installation and removal of apps) as well as the related intents. There you go.

The alternative way I used was: I attempted to uninstall the app using GUI until I was shown the final confirmation. I didn't confirm but execute the command

adb shell dumpsys activity recents   # for Android 4.4 and above
adb shell dumpsys activity activities # for Android 4.2.1

Among other things, it showed me useful details of the intent passed in the background. Example:

intent={act=android.intent.action.DELETE dat=package:com.bartat.android.elixir#com.bartat.android.elixir.MainActivity flg=0x10800000 cmp=com.android.packageinstaller/.UninstallerActivity}

Here, you can see the action, data, flag and component - enough for the goal.

How can I pass an argument to a PowerShell script?

Tested as working:

#Must be the first statement in your script (not coutning comments)
param([Int32]$step=30) 

$iTunes = New-Object -ComObject iTunes.Application

if ($iTunes.playerstate -eq 1)
{
  $iTunes.PlayerPosition = $iTunes.PlayerPosition + $step
}

Call it with

powershell.exe -file itunesForward.ps1 -step 15

Multiple parameters syntax (comments are optional, but allowed):

<#
    Script description.

    Some notes.
#>
param (
    # height of largest column without top bar
    [int]$h = 4000,
    
    # name of the output image
    [string]$image = 'out.png'
)

"Char cannot be dereferenced" error

A char doesn't have any methods - it's a Java primitive. You're looking for the Character wrapper class.

The usage would be:

if(Character.isLetter(ch)) { //... }

Where can I find the assembly System.Web.Extensions dll?

I had this problem myself. Most of the information I could find online was related to people having this problem with an ASP.NET web application. I was creating a Win Forms stand alone app so most of the advice wasn't helpful for me.

Turns out that the problem was that my project was set to use the ".NET 4 Framework Client Profile" as the target framework and the System.Web.Extensions reference was not in the list for adding. I changed the target to ".NET 4 Framework" and then the reference was available by the normal methods.

Here is what worked for me step by step:

  1. Right Click you project Select Properties
  2. Change your Target Framework to ".NET Framework 4"
  3. Do whatever you need to do to save the changes and close the preferences tab
  4. Right click on the References item in your Solution Explorer
  5. Choose Add Reference...
  6. In the .NET tab, scroll down to System.Web.Extensions and add it.

A keyboard shortcut to comment/uncomment the select text in Android Studio

On Mac you need cmd + / to comment and uncomment.

Equivalent of "continue" in Ruby

Ruby has two other loop/iteration control keywords: redo and retry. Read more about them, and the difference between them, at Ruby QuickTips.

Why can't Python find shared objects that are in directories in sys.path?

I use python setup.py build_ext -R/usr/local/lib -I/usr/local/include/libcalg-1.0 and the compiled .so file is under the build folder. you can type python setup.py --help build_ext to see the explanations of -R and -I

How do you uninstall the package manager "pip", if installed from source?

If you installed pip like this:

 - sudo apt install python-pip
 - sudo apt install python3-pip

Uninstall them like this:

 - sudo apt remove python-pip
 - sudo apt remove python3-pip

Angular - ng: command not found

If you have already installed @angular/cli

Then you only need to link it to npm using npm link @angular/cli

Otherwise first install angular by npm install @angular/cli and then link.

How to implement a tree data-structure in Java?

I wrote a tree library that plays nicely with Java8 and that has no other dependencies. It also provides a loose interpretation of some ideas from functional programming and lets you map/filter/prune/search the entire tree or subtrees.

https://github.com/RutledgePaulV/prune

The implementation doesn't do anything special with indexing and I didn't stray away from recursion, so it's possible that with large trees performance will degrade and you could blow the stack. But if all you need is a straightforward tree of small to moderate depth, I think it works well enough. It provides a sane (value based) definition of equality and it also has a toString implementation that lets you visualize the tree!

How to list active / open connections in Oracle?

Select count(1) From V$session
where status='ACTIVE'
/

Pandas Replace NaN with blank/empty string

Use a formatter, if you only want to format it so that it renders nicely when printed. Just use the df.to_string(... formatters to define custom string-formatting, without needlessly modifying your DataFrame or wasting memory:

df = pd.DataFrame({
    'A': ['a', 'b', 'c'],
    'B': [np.nan, 1, np.nan],
    'C': ['read', 'unread', 'read']})
print df.to_string(
    formatters={'B': lambda x: '' if pd.isnull(x) else '{:.0f}'.format(x)})

To get:

   A B       C
0  a      read
1  b 1  unread
2  c      read

How to automatically update an application without ClickOnce?

There are a lot of questions already about this, so I will refer you to those.

One thing you want to make sure to prevent the need for uninstallation, is that you use the same upgrade code on every release, but change the product code. These values are located in the Installshield project properties.

Some references:

How to correctly save instance state of Fragments in back stack?

On the latest support library none of the solutions discussed here are necessary anymore. You can play with your Activity's fragments as you like using the FragmentTransaction. Just make sure that your fragments can be identified either with an id or tag.

The fragments will be restored automatically as long as you don't try to recreate them on every call to onCreate(). Instead, you should check if savedInstanceState is not null and find the old references to the created fragments in this case.

Here is an example:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState == null) {
        myFragment = MyFragment.newInstance();
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.my_container, myFragment, MY_FRAGMENT_TAG)
                .commit();
    } else {
        myFragment = (MyFragment) getSupportFragmentManager()
                .findFragmentByTag(MY_FRAGMENT_TAG);
    }
...
}

Note however that there is currently a bug when restoring the hidden state of a fragment. If you are hiding fragments in your activity, you will need to restore this state manually in this case.

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

Here is how I do custom CSS for Internet Explorer:

In my JavaScript file:

function isIE () {
      var myNav = navigator.userAgent.toLowerCase();
      return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}

jQuery(document).ready(function(){
    if(var_isIE){
            if(var_isIE == 10){
                jQuery("html").addClass("ie10");
            }
            if(var_isIE == 8){
                jQuery("html").addClass("ie8");
                // you can also call here some function to disable things that 
                //are not supported in IE, or override browser default styles.
            }
        }
    });

And then in my CSS file, y define each different style:

.ie10 .some-class span{
    .......
}
.ie8 .some-class span{
    .......
}

How to measure time taken between lines of code in python?

Putting the code in a function, then using a decorator for timing is another option. (Source) The advantage of this method is that you define timer once and use it with a simple additional line for every function.

First, define timer decorator:

import functools
import time

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.perf_counter()
        value = func(*args, **kwargs)
        end_time = time.perf_counter()
        run_time = end_time - start_time
        print("Finished {} in {} secs".format(repr(func.__name__), round(run_time, 3)))
        return value

    return wrapper

Then, use the decorator while defining the function:

@timer
def doubled_and_add(num):
    res = sum([i*2 for i in range(num)])
    print("Result : {}".format(res))

Let's try:

doubled_and_add(100000)
doubled_and_add(1000000)

Output:

Result : 9999900000
Finished 'doubled_and_add' in 0.0119 secs
Result : 999999000000
Finished 'doubled_and_add' in 0.0897 secs

Note: I'm not sure why to use time.perf_counter instead of time.time. Comments are welcome.

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

By Changing The DbContext As Below;

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
    }

Just adding in OnModelCreating method call to base.OnModelCreating(modelBuilder); and it becomes fine. I am using EF6.

Special Thanks To #The Senator

How to read multiple Integer values from a single line of input in Java?

Better get the whole line as a string and then use StringTokenizer to get the numbers (using space as delimiter ) and then parse them as integers . This will work for n number of integers in a line .

    Scanner sc = new Scanner(System.in);
    List<Integer> l = new LinkedList<>(); // use linkedlist to save order of insertion
    StringTokenizer st = new StringTokenizer(sc.nextLine(), " "); // whitespace is the delimiter to create tokens
    while(st.hasMoreTokens())  // iterate until no more tokens
    {
        l.add(Integer.parseInt(st.nextToken()));  // parse each token to integer and add to linkedlist

    }

X11/Xlib.h not found in Ubuntu

Presume he's using the tutorial from http://www.arcsynthesis.org/gltut/ along with premake4.3 :-)

sudo apt-get install libx11-dev ................. for X11/Xlib.h
sudo apt-get install mesa-common-dev........ for GL/glx.h
sudo apt-get install libglu1-mesa-dev ..... for GL/glu.h
sudo apt-get install libxrandr-dev ........... for X11/extensions/Xrandr.h
sudo apt-get install libxi-dev ................... for X11/extensions/XInput.h

After which I could build glsdk_0.4.4 and examples without further issue.

Converting bool to text in C++

C++ has proper strings so you might as well use them. They're in the standard header string. #include <string> to use them. No more strcat/strcpy buffer overruns; no more missing null terminators; no more messy manual memory management; proper counted strings with proper value semantics.

C++ has the ability to convert bools into human-readable representations too. We saw hints at it earlier with the iostream examples, but they're a bit limited because they can only blast the text to the console (or with fstreams, a file). Fortunately, the designers of C++ weren't complete idiots; we also have iostreams that are backed not by the console or a file, but by an automatically managed string buffer. They're called stringstreams. #include <sstream> to get them. Then we can say:

std::string bool_as_text(bool b)
{
    std::stringstream converter;
    converter << std::boolalpha << b;   // flag boolalpha calls converter.setf(std::ios_base::boolalpha)
    return converter.str();
}

Of course, we don't really want to type all that. Fortunately, C++ also has a convenient third-party library named Boost that can help us out here. Boost has a nice function called lexical_cast. We can use it thus:

boost::lexical_cast<std::string>(my_bool)

Now, it's true to say that this is higher overhead than some macro; stringstreams deal with locales which you might not care about, and create a dynamic string (with memory allocation) whereas the macro can yield a literal string, which avoids that. But on the flip side, the stringstream method can be used for a great many conversions between printable and internal representations. You can run 'em backwards; boost::lexical_cast<bool>("true") does the right thing, for example. You can use them with numbers and in fact any type with the right formatted I/O operators. So they're quite versatile and useful.

And if after all this your profiling and benchmarking reveals that the lexical_casts are an unacceptable bottleneck, that's when you should consider doing some macro horror.

Send POST data via raw json with postman

Install Postman native app, Chrome extension has been deprecated. (Mine was opening in own window but still ran as Chrome app)

Test process.env with Jest

I think you could try this too:

const currentEnv = process.env;
process.env = { ENV_NODE: 'whatever' };

// test code...

process.env = currentEnv;

This works for me and you don't need module things

How to use refs in React with Typescript

Lacking a complete example, here is my little test script for getting user input when working with React and TypeScript. Based partially on the other comments and this link https://medium.com/@basarat/strongly-typed-refs-for-react-typescript-9a07419f807#.cdrghertm

/// <reference path="typings/react/react-global.d.ts" />

// Init our code using jquery on document ready
$(function () {
    ReactDOM.render(<ServerTime />, document.getElementById("reactTest"));
});

interface IServerTimeProps {
}

interface IServerTimeState {
    time: string;
}

interface IServerTimeInputs {
    userFormat?: HTMLInputElement;
}

class ServerTime extends React.Component<IServerTimeProps, IServerTimeState> {
    inputs: IServerTimeInputs = {};

    constructor() {
        super();
        this.state = { time: "unknown" }
    }

    render() {
        return (
            <div>
                <div>Server time: { this.state.time }</div>
                <input type="text" ref={ a => this.inputs.userFormat = a } defaultValue="s" ></input>
                <button onClick={ this._buttonClick.bind(this) }>GetTime</button>
            </div>
        );
    }

    // Update state with value from server
    _buttonClick(): void {
    alert(`Format:${this.inputs.userFormat.value}`);

        // This part requires a listening web server to work, but alert shows the user input
    jQuery.ajax({
        method: "POST",
        data: { format: this.inputs.userFormat.value },
        url: "/Home/ServerTime",
        success: (result) => {
            this.setState({ time : result });
        }
    });
}

}

Pointers, smart pointers or shared pointers?

Sydius outlined the types fairly well:

  • Normal pointers are just that - they point to some thing in memory somewhere. Who owns it? Only the comments will let you know. Who frees it? Hopefully the owner at some point.
  • Smart pointers are a blanket term that cover many types; I'll assume you meant scoped pointer which uses the RAII pattern. It is a stack-allocated object that wraps a pointer; when it goes out of scope, it calls delete on the pointer it wraps. It "owns" the contained pointer in that it is in charge of deleteing it at some point. They allow you to get a raw reference to the pointer they wrap for passing to other methods, as well as releasing the pointer, allowing someone else to own it. Copying them does not make sense.
  • Shared pointers is a stack-allocated object that wraps a pointer so that you don't have to know who owns it. When the last shared pointer for an object in memory is destructed, the wrapped pointer will also be deleted.

How about when you should use them? You will either make heavy use of scoped pointers or shared pointers. How many threads are running in your application? If the answer is "potentially a lot", shared pointers can turn out to be a performance bottleneck if used everywhere. The reason being that creating/copying/destructing a shared pointer needs to be an atomic operation, and this can hinder performance if you have many threads running. However, it won't always be the case - only testing will tell you for sure.

There is an argument (that I like) against shared pointers - by using them, you are allowing programmers to ignore who owns a pointer. This can lead to tricky situations with circular references (Java will detect these, but shared pointers cannot) or general programmer laziness in a large code base.

There are two reasons to use scoped pointers. The first is for simple exception safety and cleanup operations - if you want to guarantee that an object is cleaned up no matter what in the face of exceptions, and you don't want to stack allocate that object, put it in a scoped pointer. If the operation is a success, you can feel free to transfer it over to a shared pointer, but in the meantime save the overhead with a scoped pointer.

The other case is when you want clear object ownership. Some teams prefer this, some do not. For instance, a data structure may return pointers to internal objects. Under a scoped pointer, it would return a raw pointer or reference that should be treated as a weak reference - it is an error to access that pointer after the data structure that owns it is destructed, and it is an error to delete it. Under a shared pointer, the owning object can't destruct the internal data it returned if someone still holds a handle on it - this could leave resources open for much longer than necessary, or much worse depending on the code.

Regular Expressions and negating a whole character group

The regex [^ab] will match for example 'ab ab ab ab' but not 'ab', because it will match on the string ' a' or 'b '.

What language/scenario do you have? Can you subtract results from the original set, and just match ab?

If you are using GNU grep, and are parsing input, use the '-v' flag to invert your results, returning all non-matches. Other regex tools also have a 'return nonmatch' function, too.

If I understand correctly, you want everything except for those items which contain 'ab' anywhere.

Set Jackson Timezone for Date deserialization

If you really want Jackson to return a date with another time zone than UTC (and I myself have several good arguments for that, especially when some clients just don't get the timezone part) then I usually do:

ObjectMapper mapper = new ObjectMapper();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
dateFormat.setTimeZone(TimeZone.getTimeZone("CET"));
mapper.getSerializationConfig().setDateFormat(dateFormat);
// ... etc

It has no adverse effects on those that understand the timezone-p