Programs & Examples On #Jcarousellite

jcarousellite is a jQuery plugin for creating carousels. Its very lightweight

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

Composer update memory limit

The best solution for me is

COMPOSER_MEMORY_LIMIT=-1 composer require <package-name>

mentioned by @realtebo

Simple insecure two-way data "obfuscation"?

I've been using the accepted answer by Mark Brittingham and its has helped me a lot. Recently I had to send encrypted text to a different organization and that's where some issues came up. The OP does not require these options but since this is a popular question I'm posting my modification (Encrypt and Decrypt functions borrowed from here):

  1. Different IV for every message - Concatenates IV bytes to the cipher bytes before obtaining the hex. Of course this is a convention that needs to be conveyed to the parties receiving the cipher text.
  2. Allows two constructors - one for default RijndaelManaged values, and one where property values can be specified (based on mutual agreement between encrypting and decrypting parties)

Here is the class (test sample at the end):

/// <summary>
/// Based on https://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged(v=vs.110).aspx
/// Uses UTF8 Encoding
///  http://security.stackexchange.com/a/90850
/// </summary>
public class AnotherAES : IDisposable
{
    private RijndaelManaged rijn;

    /// <summary>
    /// Initialize algo with key, block size, key size, padding mode and cipher mode to be known.
    /// </summary>
    /// <param name="key">ASCII key to be used for encryption or decryption</param>
    /// <param name="blockSize">block size to use for AES algorithm. 128, 192 or 256 bits</param>
    /// <param name="keySize">key length to use for AES algorithm. 128, 192, or 256 bits</param>
    /// <param name="paddingMode"></param>
    /// <param name="cipherMode"></param>
    public AnotherAES(string key, int blockSize, int keySize, PaddingMode paddingMode, CipherMode cipherMode)
    {
        rijn = new RijndaelManaged();
        rijn.Key = Encoding.UTF8.GetBytes(key);
        rijn.BlockSize = blockSize;
        rijn.KeySize = keySize;
        rijn.Padding = paddingMode;
        rijn.Mode = cipherMode;
    }

    /// <summary>
    /// Initialize algo just with key
    /// Defaults for RijndaelManaged class: 
    /// Block Size: 256 bits (32 bytes)
    /// Key Size: 128 bits (16 bytes)
    /// Padding Mode: PKCS7
    /// Cipher Mode: CBC
    /// </summary>
    /// <param name="key"></param>
    public AnotherAES(string key)
    {
        rijn = new RijndaelManaged();
        byte[] keyArray = Encoding.UTF8.GetBytes(key);
        rijn.Key = keyArray;
    }

    /// <summary>
    /// Based on https://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged(v=vs.110).aspx
    /// Encrypt a string using RijndaelManaged encryptor.
    /// </summary>
    /// <param name="plainText">string to be encrypted</param>
    /// <param name="IV">initialization vector to be used by crypto algorithm</param>
    /// <returns></returns>
    public byte[] Encrypt(string plainText, byte[] IV)
    {
        if (rijn == null)
            throw new ArgumentNullException("Provider not initialized");

        // Check arguments.
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText cannot be null or empty");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV cannot be null or empty");
        byte[] encrypted;

        // Create a decrytor to perform the stream transform.
        using (ICryptoTransform encryptor = rijn.CreateEncryptor(rijn.Key, IV))
        {
            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {
                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }
        // Return the encrypted bytes from the memory stream.
        return encrypted;
    }//end EncryptStringToBytes

    /// <summary>
    /// Based on https://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged(v=vs.110).aspx
    /// </summary>
    /// <param name="cipherText">bytes to be decrypted back to plaintext</param>
    /// <param name="IV">initialization vector used to encrypt the bytes</param>
    /// <returns></returns>
    public string Decrypt(byte[] cipherText, byte[] IV)
    {
        if (rijn == null)
            throw new ArgumentNullException("Provider not initialized");

        // Check arguments.
        if (cipherText == null || cipherText.Length <= 0)
            throw new ArgumentNullException("cipherText cannot be null or empty");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("IV cannot be null or empty");

        // Declare the string used to hold the decrypted text.
        string plaintext = null;

        // Create a decrytor to perform the stream transform.
        using (ICryptoTransform decryptor = rijn.CreateDecryptor(rijn.Key, IV))
        {
            // Create the streams used for decryption.
            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {
                        // Read the decrypted bytes from the decrypting stream and place them in a string.
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }
        }

        return plaintext;
    }//end DecryptStringFromBytes

    /// <summary>
    /// Generates a unique encryption vector using RijndaelManaged.GenerateIV() method
    /// </summary>
    /// <returns></returns>
    public byte[] GenerateEncryptionVector()
    {
        if (rijn == null)
            throw new ArgumentNullException("Provider not initialized");

        //Generate a Vector
        rijn.GenerateIV();
        return rijn.IV;
    }//end GenerateEncryptionVector


    /// <summary>
    /// Based on https://stackoverflow.com/a/1344255
    /// Generate a unique string given number of bytes required.
    /// This string can be used as IV. IV byte size should be equal to cipher-block byte size. 
    /// Allows seeing IV in plaintext so it can be passed along a url or some message.
    /// </summary>
    /// <param name="numBytes"></param>
    /// <returns></returns>
    public static string GetUniqueString(int numBytes)
    {
        char[] chars = new char[62];
        chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
        byte[] data = new byte[1];
        using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
        {
            data = new byte[numBytes];
            crypto.GetBytes(data);
        }
        StringBuilder result = new StringBuilder(numBytes);
        foreach (byte b in data)
        {
            result.Append(chars[b % (chars.Length)]);
        }
        return result.ToString();
    }//end GetUniqueKey()

    /// <summary>
    /// Converts a string to byte array. Useful when converting back hex string which was originally formed from bytes.
    /// </summary>
    /// <param name="hex"></param>
    /// <returns></returns>
    public static byte[] StringToByteArray(String hex)
    {
        int NumberChars = hex.Length;
        byte[] bytes = new byte[NumberChars / 2];
        for (int i = 0; i < NumberChars; i += 2)
            bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
        return bytes;
    }//end StringToByteArray

    /// <summary>
    /// Dispose RijndaelManaged object initialized in the constructor
    /// </summary>
    public void Dispose()
    {
        if (rijn != null)
            rijn.Dispose();
    }//end Dispose()
}//end class

and..

Here is the test sample:

class Program
{
    string key;
    static void Main(string[] args)
    {
        Program p = new Program();

        //get 16 byte key (just demo - typically you will have a predetermined key)
        p.key = AnotherAES.GetUniqueString(16);

        string plainText = "Hello World!";

        //encrypt
        string hex = p.Encrypt(plainText);

        //decrypt
        string roundTrip = p.Decrypt(hex);

        Console.WriteLine("Round Trip: {0}", roundTrip);
    }

    string Encrypt(string plainText)
    {
        Console.WriteLine("\nSending (encrypt side)...");
        Console.WriteLine("Plain Text: {0}", plainText);
        Console.WriteLine("Key: {0}", key);
        string hex = string.Empty;
        string ivString = AnotherAES.GetUniqueString(16);
        Console.WriteLine("IV: {0}", ivString);
        using (AnotherAES aes = new AnotherAES(key))
        {
            //encrypting side
            byte[] IV = Encoding.UTF8.GetBytes(ivString);

            //get encrypted bytes (IV bytes prepended to cipher bytes)
            byte[] encryptedBytes = aes.Encrypt(plainText, IV);
            byte[] encryptedBytesWithIV = IV.Concat(encryptedBytes).ToArray();

            //get hex string to send with url
            //this hex has both IV and ciphertext
            hex = BitConverter.ToString(encryptedBytesWithIV).Replace("-", "");
            Console.WriteLine("sending hex: {0}", hex);
        }

        return hex;
    }

    string Decrypt(string hex)
    {
        Console.WriteLine("\nReceiving (decrypt side)...");
        Console.WriteLine("received hex: {0}", hex);
        string roundTrip = string.Empty;
        Console.WriteLine("Key " + key);
        using (AnotherAES aes = new AnotherAES(key))
        {
            //get bytes from url
            byte[] encryptedBytesWithIV = AnotherAES.StringToByteArray(hex);

            byte[] IV = encryptedBytesWithIV.Take(16).ToArray();

            Console.WriteLine("IV: {0}", System.Text.Encoding.Default.GetString(IV));

            byte[] cipher = encryptedBytesWithIV.Skip(16).ToArray();

            roundTrip = aes.Decrypt(cipher, IV);
        }
        return roundTrip;
    }
}

enter image description here

How do I rename all folders and files to lowercase on Linux?

The simplest approach I found on Mac OS X was to use the rename package from http://plasmasturm.org/code/rename/:

brew install rename
rename --force --lower-case --nows *

--force Rename even when a file with the destination name already exists.

--lower-case Convert file names to all lower case.

--nows Replace all sequences of whitespace in the filename with single underscore characters.

Recursively list files in Java

You can use below code to get a list of files of specific folder or directory recursively.

public static void main(String args[]) {

        recusiveList("D:");

    }

    public static void recursiveList(String path) {

        File f = new File(path);
        File[] fl = f.listFiles();
        for (int i = 0; i < fl.length; i++) {
            if (fl[i].isDirectory() && !fl[i].isHidden()) {
                System.out.println(fl[i].getAbsolutePath());
                recusiveList(fl[i].getAbsolutePath());
            } else {
                System.out.println(fl[i].getName());
            }
        }
    }

ERROR 1130 (HY000): Host '' is not allowed to connect to this MySQL server

Your root account, and this statement applies to any account, may only have been added with localhost access (which is recommended).

You can check this with:

SELECT host FROM mysql.user WHERE User = 'root';

If you only see results with localhost and 127.0.0.1, you cannot connect from an external source. If you see other IP addresses, but not the one you're connecting from - that's also an indication.

You will need to add the IP address of each system that you want to grant access to, and then grant privileges:

CREATE USER 'root'@'ip_address' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'ip_address';

If you see %, well then, there's another problem altogether as that is "any remote source". If however you do want any/all systems to connect via root, use the % wildcard to grant access:

CREATE USER 'root'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%';

Finally, reload the permissions, and you should be able to have remote access:

FLUSH PRIVILEGES;

How to delete selected text in the vi editor

I am using PuTTY and the vi editor. If I select five lines using my mouse and I want to delete those lines, how can I do that?

Forget the mouse. To remove 5 lines, either:

  • Go to the first line and type d5d (dd deletes one line, d5d deletes 5 lines) ~or~
  • Type Shift-v to enter linewise selection mode, then move the cursor down using j (yes, use h, j, k and l to move left, down, up, right respectively, that's much more efficient than using the arrows) and type d to delete the selection.

Also, how can I select the lines using my keyboard as I can in Windows where I press Shift and move the arrows to select the text? How can I do that in vi?

As I said, either use Shift-v to enter linewise selection mode or v to enter characterwise selection mode or Ctrl-v to enter blockwise selection mode. Then move with h, j, k and l.

I suggest spending some time with the Vim Tutor (run vimtutor) to get more familiar with Vim in a very didactic way.

See also

How to determine when a Git branch was created?

I found the best way: I always check the latest branch created by this way

git for-each-ref --sort=-committerdate refs/heads/

Reading data from XML

as per @Jon Skeet 's comment, you should use a XmlReader only if your file is very big. Here's how to use it. Assuming you have a Book class

public class Book {
    public string Title {get; set;}
    public string Author {get; set;}
}

you can read the XML file line by line with a small memory footprint, like this:

public static class XmlHelper {
    public static IEnumerable<Book> StreamBooks(string uri) {
        using (XmlReader reader = XmlReader.Create(uri)) {
            string title = null;
            string author = null;

            reader.MoveToContent();
            while (reader.Read()) {
                if (reader.NodeType == XmlNodeType.Element
                    && reader.Name == "Book") {
                    while (reader.Read()) {
                        if (reader.NodeType == XmlNodeType.Element &&
                            reader.Name == "Title") {
                            title = reader.ReadString();
                            break;
                        }
                    }
                    while (reader.Read()) {
                        if (reader.NodeType == XmlNodeType.Element &&
                            reader.Name == "Author") {
                            author =reader.ReadString();
                            break;
                        }
                    }
                    yield return new Book() {Title = title, Author = author};
                }
            }       
        }
    }

Example of usage:

string uri = @"c:\test.xml"; // your big XML file

foreach (var book in XmlHelper.StreamBooks(uri)) {
    Console.WriteLine("Title, Author: {0}, {1}", book.Title, book.Author);  
}

How do I create HTML table using jQuery dynamically?

You may use two options:

  1. createElement
  2. InnerHTML

Create Element is the fastest way (check here.):

$(document.createElement('table'));

InnerHTML is another popular approach:

$("#foo").append("<div>hello world</div>"); // Check similar for table too.

Check a real example on How to create a new table with rows using jQuery and wrap it inside div.

There may be other approaches as well. Please use this as a starting point and not as a copy-paste solution.

Edit:

Check Dynamic creation of table with DOM

Edit 2:

IMHO, you are mixing object and inner HTML. Let's try with a pure inner html approach:

function createProviderFormFields(id, labelText, tooltip, regex) {
    var tr = '<tr>' ;
         // create a new textInputBox  
           var textInputBox = '<input type="text" id="' + id + '" name="' + id + '" title="' + tooltip + '" />';  
        // create a new Label Text
            tr += '<td>' + labelText  + '</td>';
            tr += '<td>' + textInputBox + '</td>';  
    tr +='</tr>';
    return tr;
}

Maven and Spring Boot - non resolvable parent pom - repo.spring.io (Unknown host)

If you are using docker service and you have switched to other network. You need to restart docker service.

service docker restart

This solved my problem in docker.

Text Editor For Linux (Besides Vi)?

I've just started using OSX. Free editors of note that I've discovered:

  • Komodo by ActiveState. No debugger or regex editor (although one comes with Python, i.e. redemo.py) in free version but perfectly usable.
  • ERIC, written in PyQT.
  • Eclipse with PyDev is my preferred option for editing Python on all platforms. Nice clean GUI, decent debugger. Good syntax parsing etc.

How to use img src in vue.js?

Try this:

<img v-bind:src="'/media/avatars/' + joke.avatar" /> 

Don't forget single quote around your path string. also in your data check you have correctly defined image variable.

joke: {
  avatar: 'image.jpg'
}

A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output

Add vertical scroll bar to panel

Below is the code that implements custom vertical scrollbar. The important detail here is to know when scrollbar is needed by calculating how much space is consumed by the controls that you add to the panel.

panelUserInput.SuspendLayout();
panelUserInput.Controls.Clear();
panelUserInput.AutoScroll = false;
panelUserInput.VerticalScroll.Visible = false;

// here you'd be adding controls

int x = 20, y = 20, height = 0;
for (int inx = 0; inx < numControls; inx++ )
{
    // this example uses textbox control
    TextBox txt = new TextBox();
    txt.Location = new System.Drawing.Point(x, y);
    // add whatever details you need for this control
    // before adding it to the panel
    panelUserInput.Controls.Add(txt);
    height = y + txt.Height;
    y += 25;
}
if (height > panelUserInput.Height)
{
    VScrollBar bar = new VScrollBar();
    bar.Dock = DockStyle.Right;
    bar.Scroll += (sender, e) => { panelUserInput.VerticalScroll.Value =  bar.Value; };
    bar.Top = 0;
    bar.Left = panelUserInput.Width - bar.Width;
    bar.Height = panelUserInput.Height;
    bar.Visible = true;
    panelUserInput.Controls.Add(bar);
}
panelUserInput.ResumeLayout();

// then update the form
this.PerformLayout();

OkHttp Post Body as JSON

In okhttp v4.* I got it working that way


// import the extensions!
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody

// ...

json : String = "..."

val JSON : MediaType = "application/json; charset=utf-8".toMediaType()
val jsonBody: RequestBody = json.toRequestBody(JSON)

// go on with Request.Builder() etc

creating a table in ionic

enter image description here

.html file

<ion-card-content>
<div class='summary_row'>
      <div  class='summarycell'>Header 1</div>
      <div  class='summarycell'>Header 2</div>
      <div  class='summarycell'>Header 3</div>
      <div  class='summarycell'>Header 4</div>
      <div  class='summarycell'>Header 5</div>
      <div  class='summarycell'>Header 6</div>
      <div  class='summarycell'>Header 7</div>

    </div>
    <div  class='summary_row'>
      <div  class='summarycell'>
        Cell1
      </div>
      <div  class='summarycell'>
          Cell2
      </div>
        <div  class='summarycell'>
            Cell3
          </div>

      <div  class='summarycell'>
        Cell5
      </div>
      <div  class='summarycell'>
          Cell6
        </div>
        <div  class='summarycell'>
            Cell7
          </div>
          <div  class='summarycell'>
              Cell8
            </div>
    </div>

.scss file

_x000D_
_x000D_
.row{_x000D_
    display: flex;_x000D_
    flex-wrap: wrap;_x000D_
    width: max-content;_x000D_
}_x000D_
.row:first-child .summarycell{_x000D_
    font-weight: bold;_x000D_
    text-align: center;_x000D_
}_x000D_
.cell{_x000D_
    overflow: auto;_x000D_
    word-wrap: break-word;_x000D_
    width: 27vw;_x000D_
    border: 1px solid #b3b3b3;_x000D_
    padding: 10px;_x000D_
    text-align: right;_x000D_
}_x000D_
.cell:nth-child(2){_x000D_
}_x000D_
.cell:first-child{_x000D_
    width:41vw;_x000D_
    text-align: left;_x000D_
}
_x000D_
_x000D_
_x000D_

Regex to validate date format dd/mm/yyyy

The regex you pasted does not validate leap years correctly, but there is one that does in the same post. I modified it to take dd/mm/yyyy, dd-mm-yyyy or dd.mm.yyyy.

^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[13-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$

I tested it a bit in the link Arun provided in his answer and also here and it seems to work.

Edit February 14th 2019: I've removed a comma that was in the regex which allowed dates like 29-0,-11

Find ALL tweets from a user (not just the first 3,200)

The only way to see more is to start saving them before the user's tweet count hits 3200. Services which show more than 3200 tweets have saved them in their own dbs. There's currently no way to get more than that through any Twitter API.

http://www.quora.com/Is-there-a-way-to-get-more-than-3200-tweets-from-a-twitter-user-using-Twitters-API-or-scraping

https://dev.twitter.com/discussions/276

Note from that second link: "…the 3,200 limit is for browsing the timeline only. Tweets can always be requested by their ID using the GET statuses/show/:id method."

How set the android:gravity to TextView from Java side in Android

Solved this by doing a few things, first getting the height of my TextView and diving it by the text size to get the total amount of lines possible with the TextView.

int maxLines = (int) TextView.getHeight() / (int) TextView.getTextSize();

After you get this value you need to set your TextView maxLines to this new value.

TextView.setMaxLines(maxLines);

Set the Gravity to Bottom once the maximum amount of lines has been exceeded and it will scroll down automatically.

if (TextView.getLineCount() >= maxLines) {
    TextView.setGravity(Gravity.BOTTOM);
}

In order for this to work correctly, you must use append() to the TextView, If you setText() this will not work.

TextView.append("Your Text");

The benefit of this method is that this can be used dynamically regardless of the height of your TextView and the text size. If you decide to make modifications to your layout this code would still work.

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

The best way to handle the LazyInitializationException is to fetch it upon query time, like this:

select t
from Topic t
left join fetch t.comments

You should ALWAYS avoid the following anti-patterns:

Therefore, make sure that your FetchType.LAZY associations are initialized at query time or within the original @Transactional scope using Hibernate.initialize for secondary collections.

Angularjs action on click of button

The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.

Instead you could try the following approach. Change your markup to the following:

<div ng-controller="myAppController" style="text-align:center">
  <p style="font-size:28px;">Enter Quantity:
      <input type="text" ng-model="quantity"/>
  </p>
  <button ng-click="calculateQuantity()">Calculate</button>
  <h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>

Next, update your controller:

myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantity=1;
  $scope.quantityResult = 0;

  $scope.calculateQuantity = function() {
    $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  };
});

Here's a JSBin example that demonstrates the above approach.

The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.

This would involve updating the template to add an ng-change on the input, and an ng-if on the result:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>

and

<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

In the controller add:

$scope.showQuantityResult = false;

$scope.calculateQuantity = function() {
  $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  $scope.showQuantityResult = true;
};

$scope.hideQuantityResult = function() {
  $scope.showQuantityResult = false;
}; 

These updates can be seen in this JSBin demo.

MySQL dump by query

MySQL Workbench also has this feature neatly in the GUI. Simply run a query, click the save icon next to Export/Import:

enter image description here

Then choose "SQL INSERT statements (*.sql)" in the list.

enter image description here

Enter a name, click save, confirm the table name and you will have your dump file.

How to insert TIMESTAMP into my MySQL table?

In addition to checking your table setup to confirm that the field is set to NOT NULL with a default of CURRENT_TIMESTAMP, you can insert date/time values from PHP by writing them in a string format compatible with MySQL.

 $timestamp = date("Y-m-d H:i:s");

This will give you the current date and time in a string format that you can insert into MySQL.

What precisely does 'Run as administrator' do?

Okay, let's re-iterate...

The actual question (and an excellent one at that)

"What does 'run as admin' do that being a member of the administrators group does not?"

(Answer)1. It allows you to call on administrator rights while under a user session.

Note: The question is wrongly put; one is a command and the other is a group object to apply policies.

Open a command prompt and type runas /?.

This will list all the switches the runas command line can use.

As for the Administrators Group this is based on GPEDIT or SECPOL and whether or not a Domain administrator is present or not or a network is present or not.

Usually these things will apply restrictions on computers that the administrators group is not affected by.

The question should be

What does runas admin do that run as user does not?

OR

What does the Administrator group do that a customized user group can't?

You are mixing apples and oranges.

What do all of Scala's symbolic operators mean?

I consider a modern IDE to be critical for understanding large scala projects. Since these operators are also methods, in intellij idea I just control-click or control-b into the definitions.

You can control-click right into a cons operator (::) and end up at the scala javadoc saying "Adds an element at the beginning of this list." In user-defined operators, this becomes even more critical, since they could be defined in hard-to-find implicits... your IDE knows where the implicit was defined.

Inserting multiple rows in mysql

// db table name / blog_post / menu /  site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO product_cate (site_title, sub_title) 
  VALUES ('$site_title', '$sub_title')";

// db table name / blog_post / menu /  site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO menu (menu_title, sub_menu)
  VALUES ('$menu_title', '$sub_menu', )";

// db table name / blog_post /  menu /  site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO blog_post (post_title, post_des, post_img)
  VALUES ('$post_title ', '$post_des', '$post_img')";

Compare two DataFrames and output their differences side-by-side

The first part is similar to Constantine, you can get the boolean of which rows are empty*:

In [21]: ne = (df1 != df2).any(1)

In [22]: ne
Out[22]:
0    False
1     True
2     True
dtype: bool

Then we can see which entries have changed:

In [23]: ne_stacked = (df1 != df2).stack()

In [24]: changed = ne_stacked[ne_stacked]

In [25]: changed.index.names = ['id', 'col']

In [26]: changed
Out[26]:
id  col
1   score         True
2   isEnrolled    True
    Comment       True
dtype: bool

Here the first entry is the index and the second the columns which has been changed.

In [27]: difference_locations = np.where(df1 != df2)

In [28]: changed_from = df1.values[difference_locations]

In [29]: changed_to = df2.values[difference_locations]

In [30]: pd.DataFrame({'from': changed_from, 'to': changed_to}, index=changed.index)
Out[30]:
               from           to
id col
1  score       1.11         1.21
2  isEnrolled  True        False
   Comment     None  On vacation

* Note: it's important that df1 and df2 share the same index here. To overcome this ambiguity, you can ensure you only look at the shared labels using df1.index & df2.index, but I think I'll leave that as an exercise.

How to pull specific directory with git

It's not possible. You need pull all repository or nothing.

Get Absolute URL from Relative path (refactored method)

check the following code to retrieve absolute Url :

Page.Request.Url.AbsoluteUri

I hope to be useful.

Cannot redeclare function php

You (or Joomla) is likely including this file multiple times. Enclose your function in a conditional block:

if (!function_exists('parseDate')) {
    // ... proceed to declare your function
}

How to expand/collapse a diff sections in Vimdiff?

ctrl + w, w as mentioned can be used for navigating from pane to pane.

Now you can select a particular change alone and paste it to the other pane as follows.Here I am giving an eg as if I wanted to change my piece of code from pane 1 to pane 2 and currently my cursor is in pane1

  • Use Shift-v to highlight a line and use up or down keys to select the piece of code you require and continue from step 3 written below to paste your changes in the other pane.

  • Use visual mode and then change it

    1 click 'v' this will take you to visual mode 2 use up or down key to select your required code 3 click on ,Esc' escape key 4 Now use 'yy' to copy or 'dd' to cut the change 5 do 'ctrl + w, w' to navigate to pane2 6 click 'p' to paste your change where you require

Error: More than one module matches. Use skip-import option to skip importing the component into the closest module

Angular CLI: 6.0.8
Node: 10.4.0
OS: linux x64
Angular: 6.0.4

In case there is a feature module (e.g. manager.module.ts inside the e.g. "/manager" sub-folder) with the routing module externalized into the separate NgModule (e.g. manager-routing.module.ts) the error message:

More than one module matches. Use skip-import option to skip importing the component into the closest module.

does not appear and the component is properly generated and added to the manager.module.ts module.

BUT BE CAREFUL the naming convention! the name of the routing module must terminate with "-routing"!

If the routing module is given a name like e.g. manager-router.module.ts, CLI will complain with the error message and expect you to provide --module option to automatically add the component import:

ng generate component some-name --module=manager.module.ts

or

ng generate component some-name --skip-import

if you prefer to add the import of the component manually

Can I embed a custom font in an iPhone application?

For iOS 3.2 and above: Use the methods provided by several above, which are:

  1. Add your font file (for example, Chalkduster.ttf) to Resources folder of the project in XCode.
  2. Open info.plist and add a new key called UIAppFonts. The type of this key should be array.
  3. Add your custom font name to this array including extension ("Chalkduster.ttf").
  4. Use [UIFont fontWithName:@"Real Font Name" size:16] in your application.

BUT The "Real Font Name" is not always the one you see in Fontbook. The best way is to ask your device which fonts it sees and what the exact names are.

I use the uifont-name-grabber posted at: uifont-name-grabber

Just drop the fonts you want into the xcode project, add the file name to its plist, and run it on the device you are building for, it will email you a complete font list using the names that UIFont fontWithName: expects.

Missing maven .m2 folder

Use mvn -X or mvn --debug to find out from which different locations Maven reads settings.xml. This switch activates debug logging. Just check the first lines of mvn --debug | findstr /i /c:using /c:reading.


Right, Maven uses the Java system property user.home as location for the .m2 folder.

But user.home does not always resolve to %USERPROFILE%\.m2. If you have moved the location of your Desktop folder to another place, user.home might resolve to the parent directory of this new Desktop folder. This happens when using Windows Vista or a more recent Windows together with Java 7 or any older Java version.

The blog post Java’s “user.home” is Wrong on Windows describes it very well and gives links to the official bug reports. The bug is marked as resolved in Java 8. The comment of the blog's visitor Lars proposes a nice workaround.

How do I create a new column from the output of pandas groupby().sum()?

You want to use transform this will return a Series with the index aligned to the df so you can then add it as a new column:

In [74]:

df = pd.DataFrame({'Date': ['2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05', '2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05'], 'Sym': ['aapl', 'aapl', 'aapl', 'aapl', 'aaww', 'aaww', 'aaww', 'aaww'], 'Data2': [11, 8, 10, 15, 110, 60, 100, 40],'Data3': [5, 8, 6, 1, 50, 100, 60, 120]})
?
df['Data4'] = df['Data3'].groupby(df['Date']).transform('sum')
df
Out[74]:
   Data2  Data3        Date   Sym  Data4
0     11      5  2015-05-08  aapl     55
1      8      8  2015-05-07  aapl    108
2     10      6  2015-05-06  aapl     66
3     15      1  2015-05-05  aapl    121
4    110     50  2015-05-08  aaww     55
5     60    100  2015-05-07  aaww    108
6    100     60  2015-05-06  aaww     66
7     40    120  2015-05-05  aaww    121

Bash function to find newest file matching pattern

This is a possible implementation of the required Bash function:

# Print the newest file, if any, matching the given pattern
# Example usage:
#   newest_matching_file 'b2*'
# WARNING: Files whose names begin with a dot will not be checked
function newest_matching_file
{
    # Use ${1-} instead of $1 in case 'nounset' is set
    local -r glob_pattern=${1-}

    if (( $# != 1 )) ; then
        echo 'usage: newest_matching_file GLOB_PATTERN' >&2
        return 1
    fi

    # To avoid printing garbage if no files match the pattern, set
    # 'nullglob' if necessary
    local -i need_to_unset_nullglob=0
    if [[ ":$BASHOPTS:" != *:nullglob:* ]] ; then
        shopt -s nullglob
        need_to_unset_nullglob=1
    fi

    newest_file=
    for file in $glob_pattern ; do
        [[ -z $newest_file || $file -nt $newest_file ]] \
            && newest_file=$file
    done

    # To avoid unexpected behaviour elsewhere, unset nullglob if it was
    # set by this function
    (( need_to_unset_nullglob )) && shopt -u nullglob

    # Use printf instead of echo in case the file name begins with '-'
    [[ -n $newest_file ]] && printf '%s\n' "$newest_file"

    return 0
}

It uses only Bash builtins, and should handle files whose names contain newlines or other unusual characters.

What is the difference between a framework and a library?

Library:

It is just a collection of routines (functional programming) or class definitions(object oriented programming). The reason behind is simply code reuse, i.e. get the code that has already been written by other developers. The classes or routines normally define specific operations in a domain specific area. For example, there are some libraries of mathematics which can let developer just call the function without redo the implementation of how an algorithm works.

Framework:

In framework, all the control flow is already there, and there are a bunch of predefined white spots that we should fill out with our code. A framework is normally more complex. It defines a skeleton where the application defines its own features to fill out the skeleton. In this way, your code will be called by the framework when appropriately. The benefit is that developers do not need to worry about if a design is good or not, but just about implementing domain specific functions.

Library,Framework and your Code image representation:

Library,Framework and your Code image relation

KeyDifference:

The key difference between a library and a framework is “Inversion of Control”. When you call a method from a library, you are in control. But with a framework, the control is inverted: the framework calls you. Source.

Relation:

Both of them defined API, which is used for programmers to use. To put those together, we can think of a library as a certain function of an application, a framework as the skeleton of the application, and an API is connector to put those together. A typical development process normally starts with a framework, and fill out functions defined in libraries through API.

SQL Current month/ year question

How about:

Select *
from some_table st
where st.month = to_char(sysdate,'MM') and
    st.year = to_char(sysdate,'YYYY');

should work in Oracle. What database are you using? I ask because not all databases have the same date functions.

No shadow by default on Toolbar?

The correct answer will be to add
android:backgroundTint="#ff00ff" to the tool bar with android:background="@android:color/white"

If you use other color then white for the background it will remove the shadow. Nice one Google!

'printf' with leading zeros in C

Your format specifier is incorrect. From the printf() man page on my machine:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

Output:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

How to obtain the start time and end time of a day?

I think the easiest would be something like:

// Joda Time

DateTime dateTime=new DateTime(); 

StartOfDayMillis = dateTime.withMillis(System.currentTimeMillis()).withTimeAtStartOfDay().getMillis();
EndOfDayMillis = dateTime.withMillis(StartOfDayMillis).plusDays(1).minusSeconds(1).getMillis();

These millis can be then converted into Calendar,Instant or LocalDate as per your requirement with Joda Time.

How to combine two or more querysets in a Django view?

The big downside of your current approach is its inefficiency with large search result sets, as you have to pull down the entire result set from the database each time, even though you only intend to display one page of results.

In order to only pull down the objects you actually need from the database, you have to use pagination on a QuerySet, not a list. If you do this, Django actually slices the QuerySet before the query is executed, so the SQL query will use OFFSET and LIMIT to only get the records you will actually display. But you can't do this unless you can cram your search into a single query somehow.

Given that all three of your models have title and body fields, why not use model inheritance? Just have all three models inherit from a common ancestor that has title and body, and perform the search as a single query on the ancestor model.

Verify ImageMagick installation

EDIT: The info and script below only applies to iMagick class - which is not added by default with ImageMagick!!!

If I want to know if imagemagick is installed and actually working as a php extension, I paste this snippet into a web accessible file

<?php

error_reporting(E_ALL); 
ini_set( 'display_errors','1');

/* Create a new imagick object */
$im = new Imagick();

/* Create new image. This will be used as fill pattern */
$im->newPseudoImage(50, 50, "gradient:red-black");

/* Create imagickdraw object */
$draw = new ImagickDraw();

/* Start a new pattern called "gradient" */
$draw->pushPattern('gradient', 0, 0, 50, 50);

/* Composite the gradient on the pattern */
$draw->composite(Imagick::COMPOSITE_OVER, 0, 0, 50, 50, $im);

/* Close the pattern */
$draw->popPattern();

/* Use the pattern called "gradient" as the fill */
$draw->setFillPatternURL('#gradient');

/* Set font size to 52 */
$draw->setFontSize(52);

/* Annotate some text */
$draw->annotation(20, 50, "Hello World!");

/* Create a new canvas object and a white image */
$canvas = new Imagick();
$canvas->newImage(350, 70, "white");

/* Draw the ImagickDraw on to the canvas */
$canvas->drawImage($draw);

/* 1px black border around the image */
$canvas->borderImage('black', 1, 1);

/* Set the format to PNG */
$canvas->setImageFormat('png');

/* Output the image */
header("Content-Type: image/png");
echo $canvas;
?>

You should see a hello world graphic:

enter image description here

How do I hide javascript code in a webpage?

I'm not sure there's a way to hide that information. No matter what you do to obfuscate or hide whatever you're doing in JavaScript, it still comes down to the fact that your browser needs to load it in order to use it. Modern browsers have web debugging/analysis tools out of the box that make extracting and viewing scripts trivial (just hit F12 in Chrome, for example).

If you're worried about exposing some kind of trade secret or algorithm, then your only recourse is to encapsulate that logic in a web service call and have your page invoke that functionality via AJAX.

How to compare binary files to check if they are the same?

My favourite ones using xxd hex-dumper from the vim package :

1) using vimdiff (part of vim)

#!/bin/bash
FILE1="$1"
FILE2="$2"
vimdiff <( xxd "$FILE1" ) <( xxd "$FILE2" )

2) using diff

#!/bin/bash
FILE1=$1
FILE2=$2
diff -W 140 -y <( xxd $FILE1 ) <( xxd $FILE2 ) | colordiff | less -R -p '  \|  '

Combine two OR-queries with AND in Mongoose

It's probably easiest to create your query object directly as:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

How to get the max of two values in MySQL?

To get the maximum value of a column across a set of rows:

SELECT MAX(column1) FROM table; -- expect one result

To get the maximum value of a set of columns, literals, or variables for each row:

SELECT GREATEST(column1, 1, 0, @val) FROM table; -- expect many results

GCC: array type has incomplete element type

It's the array that's causing trouble in:

void print_graph(g_node graph_node[], double weight[][], int nodes);

The second and subsequent dimensions must be given:

void print_graph(g_node graph_node[], double weight[][32], int nodes);

Or you can just give a pointer to pointer:

void print_graph(g_node graph_node[], double **weight, int nodes);

However, although they look similar, those are very different internally.

If you're using C99, you can use variably-qualified arrays. Quoting an example from the C99 standard (section §6.7.5.2 Array Declarators):

void fvla(int m, int C[m][m]); // valid: VLA with prototype scope

void fvla(int m, int C[m][m])  // valid: adjusted to auto pointer to VLA
{
    typedef int VLA[m][m];     // valid: block scope typedef VLA
    struct tag {
        int (*y)[n];           // invalid: y not ordinary identifier
        int z[n];              // invalid: z not ordinary identifier
    };
    int D[m];                  // valid: auto VLA
    static int E[m];           // invalid: static block scope VLA
    extern int F[m];           // invalid: F has linkage and is VLA
    int (*s)[m];               // valid: auto pointer to VLA
    extern int (*r)[m];        // invalid: r has linkage and points to VLA
    static int (*q)[m] = &B;   // valid: q is a static block pointer to VLA
}

Question in comments

[...] In my main(), the variable I am trying to pass into the function is a double array[][], so how would I pass that into the function? Passing array[0][0] into it gives me incompatible argument type, as does &array and &array[0][0].

In your main(), the variable should be:

double array[10][20];

or something faintly similar; maybe

double array[][20] = { { 1.0, 0.0, ... }, ... };

You should be able to pass that with code like this:

typedef struct graph_node
{
    int X;
    int Y;
    int active;
} g_node;

void print_graph(g_node graph_node[], double weight[][20], int nodes);

int main(void)
{
    g_node g[10];
    double array[10][20];
    int n = 10;

    print_graph(g, array, n);
    return 0;
}

That compiles (to object code) cleanly with GCC 4.2 (i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.9.00)) and also with GCC 4.7.0 on Mac OS X 10.7.3 using the command line:

/usr/bin/gcc -O3 -g -std=c99 -Wall -Wextra -c zzz.c

Simple bubble sort c#

public static void BubbleSort(int[] a)
    {

       for (int i = 1; i <= a.Length - 1; ++i)

            for (int j = 0; j < a.Length - i; ++j)

                if (a[j] > a[j + 1])


                    Swap(ref a[j], ref a[j + 1]);

    }

    public static void Swap(ref int x, ref int y)
    {
        int temp = x;
        x = y;
        y = temp;
    }

How to check whether a given string is valid JSON in Java

IMHO, the most elegant way is using the Java API for JSON Processing (JSON-P), one of the JavaEE standards that conforms to the JSR 374.

try(StringReader sr = new StringReader(jsonStrn)) {
    Json.createReader(sr).readObject();
} catch(JsonParsingException e) {
    System.out.println("The given string is not a valid json");
    e.printStackTrace();
}

Using Maven, add the dependency on JSON-P:

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1.4</version>
</dependency>

Visit the JSON-P official page for more informations.

Android Studio is slow (how to speed up)?

It's not compiling that's hurting me here, it's the typing. I could disable all the smart features and be back to notepad++ like TomTsagk suggested in a comment. For today I need more cores and RAM.

Playing devil's advocate I'd argue that typing shouldn't require a 16Gb PC octacore PC. Liked Sajan Rana's advice but things are so slow here it felt mostly a placebo.

To be fair I am using 1.4RC1, which is just short of being in the stable branch. Turning the internet off helped a little. The new feature of simultaneous Design (Preview) and Text views working with XML layouts is very helpful.

No, it is ridiculous. Never leave the stable channel.

How do I set an ASP.NET Label text from code behind on page load?

If you are just placing the code on the page, usually the code behind will get an auto generated field you to use like @Oded has shown.

In other cases, you can always use this code:

Label myLabel = this.FindControl("myLabel") as Label; // this is your Page class

if(myLabel != null)
   myLabel.Text = "SomeText";

Java Multiple Inheritance

I have a stupid idea:

public class Pegasus {
    private Horse horseFeatures; 
    private Bird birdFeatures; 

   public Pegasus(Horse horse, Bird bird) {
     this.horseFeatures = horse;
     this.birdFeatures = bird;
   }

  public void jump() {
    horseFeatures.jump();
  }

  public void fly() {
    birdFeatures.fly();
  }
}

is it possible to update UIButton title/text programmatically?

for swift :

button.setTitle("Swift", forState: UIControlState.Normal)                   

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

Pass Javascript variable to PHP via ajax

Pass the data like this to the ajax call (http://api.jquery.com/jQuery.ajax/):

data: { userID : userID }

And in your PHP do this:

if(isset($_POST['userID']))
{
    $uid = $_POST['userID'];

    // Do whatever you want with the $uid
}

isset() function's purpose is to check wheter the given variable exists, not to get its value.

Convert Mercurial project to Git

This would be better as a comment, sorry I do not have commenting permissions.

@mar10 comment was the missing piece I needed to do this.

Note that '/path/to/old/mercurial_repo' must be a path on the file system (not a URL), so you have to clone the original repository before. – mar10 Dec 27 '13 at 16:30

This comment was in regards to the answer that solved this for me, https://stackoverflow.com/a/10710294/2148757 which is the same answer as the one marked correct here, https://stackoverflow.com/a/16037861/2148757

This moved our hg project to git with the commit history intact.

int to string in MySQL

If you have a column called "col1" which is int, you cast it to String like this:

CONVERT(col1,char)

e.g. this allows you to check an int value is containing another value (here 9) like this:

CONVERT(col1,char) LIKE '%9%'

Erase the current printed console line

You can use VT100 escape codes. Most terminals, including xterm, are VT100 aware. For erasing a line, this is ^[[2K. In C this gives:

printf("%c[2K", 27);

Select by partial string from a pandas DataFrame

There are answers before this which accomplish the asked feature, anyway I would like to show the most generally way:

df.filter(regex=".*STRING_YOU_LOOK_FOR.*")

This way let's you get the column you look for whatever the way is wrote.

( Obviusly, you have to write the proper regex expression for each case )

Check object empty

I have a way, you guys tell me how good it is.

Create a new object of the class and compare it with your object (which you want to check for emptiness).

To be correctly able to do it :

Override the hashCode() and equals() methods of your model class and also of the classes, objects of whose are members of your class, for example :

Person class (primary model class) :

public class Person {

    private int age;
    private String firstName;
    private String lastName;
    private Address address;

    //getters and setters

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((address == null) ? 0 : address.hashCode());
        result = prime * result + age;
        result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
        result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (address == null) {
            if (other.address != null)
                return false;
        } else if (!address.equals(other.address))
            return false;
        if (age != other.age)
            return false;
        if (firstName == null) {
            if (other.firstName != null)
                return false;
        } else if (!firstName.equals(other.firstName))
            return false;
        if (lastName == null) {
            if (other.lastName != null)
                return false;
        } else if (!lastName.equals(other.lastName))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Person [age=" + age + ", firstName=" + firstName + ", lastName=" + lastName + ", address=" + address
                + "]";
    }

}

Address class (used inside Person class) :

public class Address {

    private String line1;
    private String line2;

    //getters and setters

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((line1 == null) ? 0 : line1.hashCode());
        result = prime * result + ((line2 == null) ? 0 : line2.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Address other = (Address) obj;
        if (line1 == null) {
            if (other.line1 != null)
                return false;
        } else if (!line1.equals(other.line1))
            return false;
        if (line2 == null) {
            if (other.line2 != null)
                return false;
        } else if (!line2.equals(other.line2))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Address [line1=" + line1 + ", line2=" + line2 + "]";
    }

}

Now in the main class :

    Person person1 = new Person();
    person1.setAge(20);

    Person person2 = new Person();

    Person person3 = new Person();

if(person1.equals(person2)) --> this will be false

if(person2.equals(person3)) --> this will be true

I hope this is the best way instead of putting if conditions on each and every member variables.

Let me know !

How can I define an array of objects?

 var xxxx : { [key:number]: MyType };

JAX-RS / Jersey how to customize error handling?

Jersey throws an com.sun.jersey.api.ParamException when it fails to unmarshall the parameters so one solution is to create an ExceptionMapper that handles these types of exceptions:

@Provider
public class ParamExceptionMapper implements ExceptionMapper<ParamException> {
    @Override
    public Response toResponse(ParamException exception) {
        return Response.status(Status.BAD_REQUEST).entity(exception.getParameterName() + " incorrect type").build();
    }
}

Change value of input onchange?

for jQuery we can use below:

by input name:

$('input[name="textboxname"]').val('some value');

by input class:

$('input[type=text].textboxclass').val('some value');

by input id:

$('#textboxid').val('some value');

MySQL Removing Some Foreign keys

The foreign keys are there to ensure data integrity, so you can't drop a column as long as it's part of a foreign key. You need to drop the key first.

I would think the following query would do it:

ALTER TABLE assignmentStuff DROP FOREIGN KEY assignmentIDX;

How to fix Terminal not loading ~/.bashrc on OS X Lion

Renaming .bashrc to .profile (or soft-linking the latter to the former) should also do the trick. See here.

jQuery: How can I create a simple overlay?

Here's a fully encapsulated version which adds an overlay (including a share button) to any IMG element where data-photo-overlay='true.

JSFiddle http://jsfiddle.net/wloescher/7y6UX/19/

HTML

<img id="my-photo-id" src="http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png" alt="Photo" data-photo-overlay="true" />

CSS

#photoOverlay {
    background: #ccc;
    background: rgba(0, 0, 0, .5);
    display: none;
    height: 50px;
    left: 0;
    position: absolute;
    text-align: center;
    top: 0;
    width: 50px;
    z-index: 1000;
}

#photoOverlayShare {
    background: #fff;
    border: solid 3px #ccc;
    color: #ff6a00;
    cursor: pointer;
    display: inline-block;
    font-size: 14px;
    margin-left: auto;
    margin: 15px;
    padding: 5px;
    position: absolute;
    left: calc(100% - 100px);
    text-transform: uppercase;
    width: 50px;
}

JavaScript

(function () {
    // Add photo overlay hover behavior to selected images
    $("img[data-photo-overlay='true']").mouseenter(showPhotoOverlay);

    // Create photo overlay elements
    var _isPhotoOverlayDisplayed = false;
    var _photoId;
    var _photoOverlay = $("<div id='photoOverlay'></div>");
    var _photoOverlayShareButton = $("<div id='photoOverlayShare'>Share</div>");

    // Add photo overlay events
    _photoOverlay.mouseleave(hidePhotoOverlay);
    _photoOverlayShareButton.click(sharePhoto);

    // Add photo overlay elements to document
    _photoOverlay.append(_photoOverlayShareButton);
    _photoOverlay.appendTo(document.body);

    // Show photo overlay
    function showPhotoOverlay(e) {
        // Get sender 
        var sender = $(e.target || e.srcElement);

        // Check to see if overlay is already displayed
        if (!_isPhotoOverlayDisplayed) {
            // Set overlay properties based on sender
            _photoOverlay.width(sender.width());
            _photoOverlay.height(sender.height());

            // Position overlay on top of photo
            if (sender[0].x) {
                _photoOverlay.css("left", sender[0].x + "px");
                _photoOverlay.css("top", sender[0].y) + "px";
            }
            else {
                // Handle IE incompatibility
                _photoOverlay.css("left", sender.offset().left);
                _photoOverlay.css("top", sender.offset().top);
            }

            // Get photo Id
            _photoId = sender.attr("id");

            // Show overlay
            _photoOverlay.animate({ opacity: "toggle" });
            _isPhotoOverlayDisplayed = true;
        }
    }

    // Hide photo overlay
    function hidePhotoOverlay(e) {
        if (_isPhotoOverlayDisplayed) {
            _photoOverlay.animate({ opacity: "toggle" });
            _isPhotoOverlayDisplayed = false;
        }
    }

    // Share photo
    function sharePhoto() {
        alert("TODO: Share photo. [PhotoId = " + _photoId + "]");
        }
    }
)();

How to delete rows in tables that contain foreign keys to other tables

First, as a one-time data-scrubbing exercise, delete the orphaned rows e.g.

DELETE 
  FROM ReferencingTable 
 WHERE NOT EXISTS (
                   SELECT * 
                     FROM MainTable AS T1
                    WHERE T1.pk_col_1 = ReferencingTable.pk_col_1
                  );

Second, as a one-time schema-alteration exercise, add the ON DELETE CASCADE referential action to the foreign key on the referencing table e.g.

ALTER TABLE ReferencingTable DROP 
   CONSTRAINT fk__ReferencingTable__MainTable;

ALTER TABLE ReferencingTable ADD 
   CONSTRAINT fk__ReferencingTable__MainTable 
      FOREIGN KEY (pk_col_1)
      REFERENCES MainTable (pk_col_1)
      ON DELETE CASCADE;

Then, forevermore, rows in the referencing tables will automatically be deleted when their referenced row is deleted.

How to convert Hexadecimal #FFFFFF to System.Drawing.Color

You can do

var color =  System.Drawing.ColorTranslator.FromHtml("#FFFFFF");

Or this (you will need the System.Windows.Media namespace)

var color = (Color)ColorConverter.ConvertFromString("#FFFFFF");

What does the keyword "transient" mean in Java?

Transient variables in Java are never serialized.

Text in HTML Field to disappear when clicked?

What you want to do is use the HTML5 attribute placeholder which lets you set a default value for your input box:

<input type="text" name="inputBox" placeholder="enter your text here">

This should achieve what you're looking for. However, be careful because the placeholder attribute is not supported in Internet Explorer 9 and earlier versions.

Shell script : How to cut part of a string

A perl-solution:

perl -nE 'say $1 if /id=(\d+)/' filename

HTML5 Audio stop function

first you have to set an id for your audio element

in your js :

var ply = document.getElementById('player');

var oldSrc = ply.src;// just to remember the old source

ply.src = "";// to stop the player you have to replace the source with nothing

Pass an array of integers to ASP.NET Web API?

My solution was to create an attribute to validate strings, it does a bunch of extra common features, including regex validation that you can use to check for numbers only and then later I convert to integers as needed...

This is how you use:

public class MustBeListAndContainAttribute : ValidationAttribute
{
    private Regex regex = null;
    public bool RemoveDuplicates { get; }
    public string Separator { get; }
    public int MinimumItems { get; }
    public int MaximumItems { get; }

    public MustBeListAndContainAttribute(string regexEachItem,
        int minimumItems = 1,
        int maximumItems = 0,
        string separator = ",",
        bool removeDuplicates = false) : base()
    {
        this.MinimumItems = minimumItems;
        this.MaximumItems = maximumItems;
        this.Separator = separator;
        this.RemoveDuplicates = removeDuplicates;

        if (!string.IsNullOrEmpty(regexEachItem))
            regex = new Regex(regexEachItem, RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var listOfdValues = (value as List<string>)?[0];

        if (string.IsNullOrWhiteSpace(listOfdValues))
        {
            if (MinimumItems > 0)
                return new ValidationResult(this.ErrorMessage);
            else
                return null;
        };

        var list = new List<string>();

        list.AddRange(listOfdValues.Split(new[] { Separator }, System.StringSplitOptions.RemoveEmptyEntries));

        if (RemoveDuplicates) list = list.Distinct().ToList();

        var prop = validationContext.ObjectType.GetProperty(validationContext.MemberName);
        prop.SetValue(validationContext.ObjectInstance, list);
        value = list;

        if (regex != null)
            if (list.Any(c => string.IsNullOrWhiteSpace(c) || !regex.IsMatch(c)))
                return new ValidationResult(this.ErrorMessage);

        return null;
    }
}

How do I vertical center text next to an image in html/css?

Since most of the answers to this question are between 2009 and 2014 (except for a comment in 2018), there should be an update to this.

I found a solution to the wrap-text problem brought up by Spongman on Jun 11 '14 at 23:20. He has an example here: jsfiddle.net/vPpD4

If you add the following in the CSS under the div tag in the jsfiddle.net/vPpD4 example, you get the desired wrap-text effect that I think Spongman was asking about. I don't know how far back this is applicable, but this works in all of the current (as of Dec 2020/Jan 2021) browsers available for Windows computers. Note: I have not tested this on the Apple Safari browser. I have also not tested this on any mobile devices.

    div img { 
        float: left;
    }
    .clearfix::after {
        content: ""; 
        clear: both;
        display: table;
    }

I also added a border around the image, just so that the reader will understand where the edge of the image is and why the text wraps as it does. The resulting example looks is here: http://jsfiddle.net/tqg7hLzk/

How to create a secure random AES key in Java?

Lots of good advince in the other posts. This is what I use:

Key key;
SecureRandom rand = new SecureRandom();
KeyGenerator generator = KeyGenerator.getInstance("AES");
generator.init(256, rand);
key = generator.generateKey();

If you need another randomness provider, which I sometime do for testing purposes, just replace rand with

MySecureRandom rand = new MySecureRandom();

Delaying AngularJS route change until model loaded to prevent flicker

I like darkporter's idea because it will be easy for a dev team new to AngularJS to understand and worked straight away.

I created this adaptation which uses 2 divs, one for loader bar and another for actual content displayed after data is loaded. Error handling would be done elsewhere.

Add a 'ready' flag to $scope:

$http({method: 'GET', url: '...'}).
    success(function(data, status, headers, config) {
        $scope.dataForView = data;      
        $scope.ready = true;  // <-- set true after loaded
    })
});

In html view:

<div ng-show="!ready">

    <!-- Show loading graphic, e.g. Twitter Boostrap progress bar -->
    <div class="progress progress-striped active">
        <div class="bar" style="width: 100%;"></div>
    </div>

</div>

<div ng-show="ready">

    <!-- Real content goes here and will appear after loading -->

</div>

See also: Boostrap progress bar docs

json call with C#

In your code you don't get the HttpResponse, so you won't see what the server side sends you back.

you need to get the Response similar to the way you get (make) the Request. So

public static bool SendAnSMSMessage(string message)
{
  var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
  httpWebRequest.ContentType = "text/json";
  httpWebRequest.Method = "POST";

  using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
  {
    string json = "{ \"method\": \"send\", " +
                      "  \"params\": [ " +
                      "             \"IPutAGuidHere\", " +
                      "             \"[email protected]\", " +
                      "             \"MyTenDigitNumberWasHere\", " +
                      "             \"" + message + "\" " +
                      "             ] " +
                      "}";

    streamWriter.Write(json);
  }
  var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
  using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
  {
    var responseText = streamReader.ReadToEnd();
    //Now you have your response.
    //or false depending on information in the response
    return true;        
  }
}

I also notice in the pennysms documentation that they expect a content type of "text/json" and not "application/json". That may not make a difference, but it's worth trying in case it doesn't work.

How to download all files (but not HTML) from a website using wget?

This downloaded the entire website for me:

wget --no-clobber --convert-links --random-wait -r -p -E -e robots=off -U mozilla http://site/path/

How to get a URL parameter in Express?

Express 4.x

To get a URL parameter's value, use req.params

app.get('/p/:tagId', function(req, res) {
  res.send("tagId is set to " + req.params.tagId);
});

// GET /p/5
// tagId is set to 5

If you want to get a query parameter ?tagId=5, then use req.query

app.get('/p', function(req, res) {
  res.send("tagId is set to " + req.query.tagId);
});

// GET /p?tagId=5
// tagId is set to 5

Express 3.x

URL parameter

app.get('/p/:tagId', function(req, res) {
  res.send("tagId is set to " + req.param("tagId"));
});

// GET /p/5
// tagId is set to 5

Query parameter

app.get('/p', function(req, res) {
  res.send("tagId is set to " + req.query("tagId"));
});

// GET /p?tagId=5
// tagId is set to 5

PHP namespaces and "use"

If you need to order your code into namespaces, just use the keyword namespace:

file1.php

namespace foo\bar;

In file2.php

$obj = new \foo\bar\myObj();

You can also use use. If in file2 you put

use foo\bar as mypath;

you need to use mypath instead of bar anywhere in the file:

$obj  = new mypath\myObj();

Using use foo\bar; is equal to use foo\bar as bar;.

How to read and write INI file with Python3?

This can be something to start with:

import configparser

config = configparser.ConfigParser()
config.read('FILE.INI')
print(config['DEFAULT']['path'])     # -> "/path/name/"
config['DEFAULT']['path'] = '/var/shared/'    # update
config['DEFAULT']['default_message'] = 'Hey! help me!!'   # create

with open('FILE.INI', 'w') as configfile:    # save
    config.write(configfile)

You can find more at the official configparser documentation.

How do you rename a MongoDB database?

In the case you put all your data in the admin database (you shouldn't), you'll notice db.copyDatabase() won't work because your user requires a lot of privileges you probably don't want to give it. Here is a script to copy the database manually:

use old_db
db.getCollectionNames().forEach(function(collName) {
    db[collName].find().forEach(function(d){
        db.getSiblingDB('new_db')[collName].insert(d); 
    }) 
});

How can I make a div stick to the top of the screen once it's been scrolled to?

In javascript you can do:

var element = document.getElementById("myid");
element.style.position = "fixed";
element.style.top = "0%";

Javascript switch vs. if...else if...else

Is there a preformance difference in Javascript between a switch statement and an if...else if....else?

I don't think so, switch is useful/short if you want prevent multiple if-else conditions.

Is the behavior of switch and if...else if...else different across browsers? (FireFox, IE, Chrome, Opera, Safari)

Behavior is same across all browsers :)

Angular IE Caching issue for $http

The correct, server-side, solution: Better Way to Prevent IE Cache in AngularJS?

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
public ActionResult Get()
{
    // return your response
}

How would you implement an LRU cache in Java?

Have a look at ConcurrentSkipListMap. It should give you log(n) time for testing and removing an element if it is already contained in the cache, and constant time for re-adding it.

You'd just need some counter etc and wrapper element to force ordering of the LRU order and ensure recent stuff is discarded when the cache is full.

How to add double quotes to a string that is inside a variable?

So you are essentially asking how to store doublequotes within a string variable? Two solutions for that:

var string1 = @"""inside quotes""";
var string2 = "\"inside quotes\"";

In order to perhaps make it a bit more clear what happens:

var string1 = @"before ""inside"" after";
var string2 = "before \"inside\" after";

Internet Access in Ubuntu on VirtualBox

I could get away with the following solution (works with Ubuntu 14 guest VM on Windows 7 host or Ubuntu 9.10 Casper guest VM on host Windows XP x86):

  1. Go to network connections -> Virtual Box Host-Only Network -> Select "Properties"
  2. Check VirtualBox Bridged Networking Driver
  3. Come to VirtualBox Manager, choose the network adapter as Bridged Adapter and Name to the device in Step #1.
  4. Restart the VM.

Entity framework left join

Please make your life easier (don't use join into group):

var query = from ug in UserGroups
            from ugp in UserGroupPrices.Where(x => x.UserGroupId == ug.Id).DefaultIfEmpty()
            select new 
            { 
                UserGroupID = ug.UserGroupID,
                UserGroupName = ug.UserGroupName,
                Price = ugp != null ? ugp.Price : 0 //this is to handle nulls as even when Price is non-nullable prop it may come as null from SQL (result of Left Outer Join)
            };

How may I sort a list alphabetically using jQuery?

$(".list li").sort(asc_sort).appendTo('.list');
//$("#debug").text("Output:");
// accending sort
function asc_sort(a, b){
    return ($(b).text()) < ($(a).text()) ? 1 : -1;    
}

// decending sort
function dec_sort(a, b){
    return ($(b).text()) > ($(a).text()) ? 1 : -1;    
}

live demo : http://jsbin.com/eculis/876/edit

Android Studio Stuck at Gradle Download on create new project

Android Studio comes with Gradle, but it does not have the command line gradle functionality.

How do I use variables in Oracle SQL Developer?

I am using the SQL-Developer in Version 3.2. The other stuff didn't work for me, but this did:

define value1 = 'sysdate'

SELECT &&value1 from dual;

Also it's the slickest way presented here, yet.

(If you omit the "define"-part you'll be prompted for that value)

Casting LinkedHashMap to Complex Object

There is a good solution to this issue:

import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper objectMapper = new ObjectMapper();

***DTO premierDriverInfoDTO = objectMapper.convertValue(jsonString, ***DTO.class); 

Map<String, String> map = objectMapper.convertValue(jsonString, Map.class);

Why did this issue occur? I guess you didn't specify the specific type when converting a string to the object, which is a class with a generic type, such as, User <T>.

Maybe there is another way to solve it, using Gson instead of ObjectMapper. (or see here Deserializing Generic Types with GSON)

Gson gson = new GsonBuilder().create();

Type type = new TypeToken<BaseResponseDTO<List<PaymentSummaryDTO>>>(){}.getType();

BaseResponseDTO<List<PaymentSummaryDTO>> results = gson.fromJson(jsonString, type);

BigDecimal revenue = results.getResult().get(0).getRevenue();

What is the purpose of the "role" attribute in HTML?

Most of the roles you see were defined as part of ARIA 1.0, and then later incorporated into HTML via supporting specs like HTML-AAM. Some of the new HTML5 elements (dialog, main, etc.) are even based on the original ARIA roles.

http://www.w3.org/TR/wai-aria/

There are a few primary reasons to use roles in addition to your native semantic element.

Reason #1. Overriding the role where no host language element is appropriate or, for various reasons, a less semantically appropriate element was used.

In this example, a link was used, even though the resulting functionality is more button-like than a navigation link.

<a href="#" role="button" aria-label="Delete item 1">Delete</a>
<!-- Note: href="#" is just a shorthand here, not a recommended technique. Use progressive enhancement when possible. -->

Screen readers users will hear this as a button (as opposed to a link), and you can use a CSS attribute selector to avoid class-itis and div-itis.

[role="button"] {
  /* style these as buttons w/o relying on a .button class */
}

[Update 7 years later: removed the * selector to make some commenters happy, since the old browser quirk that required universal selector on attribute selectors is unnecessary in 2020.]

Reason #2. Backing up a native element's role, to support browsers that implemented the ARIA role but haven't yet implemented the native element's role.

For example, the "main" role has been supported in browsers for many years, but it's a relatively recent addition to HTML5, so many browsers don't yet support the semantic for <main>.

<main role="main">…</main>

This is technically redundant, but helps some users and doesn't harm any. In a few years, this technique will likely become unnecessary for main.

Reason #3. Update 7 years later (2020): As at least one commenter pointed out, this is now very useful for custom elements, and some spec work is underway to define the default accessibility role of a web component. Even if/once that API is standardized, there may be need to override the default role of a component.

Note/Reply

You also wrote:

I see some people make up their own. Is that allowed or a correct use of the role attribute?

That's an allowed use of the attribute unless a real role is not included. Browsers will apply the first recognized role in the token list.

<span role="foo link note bar">...</a>

Out of the list, only link and note are valid roles, and so the link role will be applied in the platform accessibility API because it comes first. If you use custom roles, make sure they don't conflict with any defined role in ARIA or the host language you're using (HTML, SVG, MathML, etc.)

Why are elementwise additions much faster in separate loops than in a combined loop?

I cannot replicate the results discussed here.

I don't know if poor benchmark code is to blame, or what, but the two methods are within 10% of each other on my machine using the following code, and one loop is usually just slightly faster than two - as you'd expect.

Array sizes ranged from 2^16 to 2^24, using eight loops. I was careful to initialize the source arrays so the += assignment wasn't asking the FPU to add memory garbage interpreted as a double.

I played around with various schemes, such as putting the assignment of b[j], d[j] to InitToZero[j] inside the loops, and also with using += b[j] = 1 and += d[j] = 1, and I got fairly consistent results.

As you might expect, initializing b and d inside the loop using InitToZero[j] gave the combined approach an advantage, as they were done back-to-back before the assignments to a and c, but still within 10%. Go figure.

Hardware is Dell XPS 8500 with generation 3 Core i7 @ 3.4 GHz and 8 GB memory. For 2^16 to 2^24, using eight loops, the cumulative time was 44.987 and 40.965 respectively. Visual C++ 2010, fully optimized.

PS: I changed the loops to count down to zero, and the combined method was marginally faster. Scratching my head. Note the new array sizing and loop counts.

// MemBufferMystery.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <string>
#include <time.h>

#define  dbl    double
#define  MAX_ARRAY_SZ    262145    //16777216    // AKA (2^24)
#define  STEP_SZ           1024    //   65536    // AKA (2^16)

int _tmain(int argc, _TCHAR* argv[]) {
    long i, j, ArraySz = 0,  LoopKnt = 1024;
    time_t start, Cumulative_Combined = 0, Cumulative_Separate = 0;
    dbl *a = NULL, *b = NULL, *c = NULL, *d = NULL, *InitToOnes = NULL;

    a = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
    b = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
    c = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
    d = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
    InitToOnes = (dbl *)calloc( MAX_ARRAY_SZ, sizeof(dbl));
    // Initialize array to 1.0 second.
    for(j = 0; j< MAX_ARRAY_SZ; j++) {
        InitToOnes[j] = 1.0;
    }

    // Increase size of arrays and time
    for(ArraySz = STEP_SZ; ArraySz<MAX_ARRAY_SZ; ArraySz += STEP_SZ) {
        a = (dbl *)realloc(a, ArraySz * sizeof(dbl));
        b = (dbl *)realloc(b, ArraySz * sizeof(dbl));
        c = (dbl *)realloc(c, ArraySz * sizeof(dbl));
        d = (dbl *)realloc(d, ArraySz * sizeof(dbl));
        // Outside the timing loop, initialize
        // b and d arrays to 1.0 sec for consistent += performance.
        memcpy((void *)b, (void *)InitToOnes, ArraySz * sizeof(dbl));
        memcpy((void *)d, (void *)InitToOnes, ArraySz * sizeof(dbl));

        start = clock();
        for(i = LoopKnt; i; i--) {
            for(j = ArraySz; j; j--) {
                a[j] += b[j];
                c[j] += d[j];
            }
        }
        Cumulative_Combined += (clock()-start);
        printf("\n %6i miliseconds for combined array sizes %i and %i loops",
                (int)(clock()-start), ArraySz, LoopKnt);
        start = clock();
        for(i = LoopKnt; i; i--) {
            for(j = ArraySz; j; j--) {
                a[j] += b[j];
            }
            for(j = ArraySz; j; j--) {
                c[j] += d[j];
            }
        }
        Cumulative_Separate += (clock()-start);
        printf("\n %6i miliseconds for separate array sizes %i and %i loops \n",
                (int)(clock()-start), ArraySz, LoopKnt);
    }
    printf("\n Cumulative combined array processing took %10.3f seconds",
            (dbl)(Cumulative_Combined/(dbl)CLOCKS_PER_SEC));
    printf("\n Cumulative seperate array processing took %10.3f seconds",
        (dbl)(Cumulative_Separate/(dbl)CLOCKS_PER_SEC));
    getchar();

    free(a); free(b); free(c); free(d); free(InitToOnes);
    return 0;
}

I'm not sure why it was decided that MFLOPS was a relevant metric. I though the idea was to focus on memory accesses, so I tried to minimize the amount of floating point computation time. I left in the +=, but I am not sure why.

A straight assignment with no computation would be a cleaner test of memory access time and would create a test that is uniform irrespective of the loop count. Maybe I missed something in the conversation, but it is worth thinking twice about. If the plus is left out of the assignment, the cumulative time is almost identical at 31 seconds each.

Named capturing groups in JavaScript regex?

In ES6 you can use array destructuring to catch your groups:

let text = '27 months';
let regex = /(\d+)\s*(days?|months?|years?)/;
let [, count, unit] = regex.exec(text) || [];

// count === '27'
// unit === 'months'

Notice:

  • the first comma in the last let skips the first value of the resulting array, which is the whole matched string
  • the || [] after .exec() will prevent a destructuring error when there are no matches (because .exec() will return null)

Remove the first character of a string

Your problem seems unclear. You say you want to remove "a character from a certain position" then go on to say you want to remove a particular character.

If you only need to remove the first character you would do:

s = ":dfa:sif:e"
fixed = s[1:]

If you want to remove a character at a particular position, you would do:

s = ":dfa:sif:e"
fixed = s[0:pos]+s[pos+1:]

If you need to remove a particular character, say ':', the first time it is encountered in a string then you would do:

s = ":dfa:sif:e"
fixed = ''.join(s.split(':', 1))

Split output of command by columns using Bash?

Getting the correct line (example for line no. 6) is done with head and tail and the correct word (word no. 4) can be captured with awk:

command|head -n 6|tail -n 1|awk '{print $4}'

HtmlEncode from Class Library

Import System.Web Or call the System.Web.HttpUtility which contains it

You will need to add the reference to the DLL if it isn't there already

string TestString = "This is a <Test String>.";
string EncodedString = System.Web.HttpUtility.HtmlEncode(TestString);

You need to use a Theme.AppCompat theme (or descendant) with this activity

go to your styles and put the parent

parent="Theme.AppCompat"

instead of

parent="@android:style/Theme.Holo.Light"

undefined reference to 'std::cout'

Makefiles

If you're working with a makefile and you ended up here like me, then this is probably what you're looking or:

If you're using a makefile, then you need to change cc as shown below

my_executable : main.o
    cc -o my_executable main.o

to

CC = g++

my_executable : main.o
    $(CC) -o my_executable main.o

UIView bottom border?

Swift 4

If you need a really adaptive solution (for all screen sizes), then this is it:

/**
* Extends UIView with shortcut methods
*
* @author Alexander Volkov
* @version 1.0
*/
extension UIView {

    /// Adds bottom border to the view with given side margins
    ///
    /// - Parameters:
    ///   - color: the border color
    ///   - margins: the left and right margin
    ///   - borderLineSize: the size of the border
    func addBottomBorder(color: UIColor = UIColor.red, margins: CGFloat = 0, borderLineSize: CGFloat = 1) {
        let border = UIView()
        border.backgroundColor = color
        border.translatesAutoresizingMaskIntoConstraints = false
        self.addSubview(border)
        border.addConstraint(NSLayoutConstraint(item: border,
                                                attribute: .height,
                                                relatedBy: .equal,
                                                toItem: nil,
                                                attribute: .height,
                                                multiplier: 1, constant: borderLineSize))
        self.addConstraint(NSLayoutConstraint(item: border,
                                              attribute: .bottom,
                                              relatedBy: .equal,
                                              toItem: self,
                                              attribute: .bottom,
                                              multiplier: 1, constant: 0))
        self.addConstraint(NSLayoutConstraint(item: border,
                                              attribute: .leading,
                                              relatedBy: .equal,
                                              toItem: self,
                                              attribute: .leading,
                                              multiplier: 1, constant: margins))
        self.addConstraint(NSLayoutConstraint(item: border,
                                              attribute: .trailing,
                                              relatedBy: .equal,
                                              toItem: self,
                                              attribute: .trailing,
                                              multiplier: 1, constant: margins))
    }
}

How to stop (and restart) the Rails Server?

I had to restart the rails application on the production so I looked for an another answer. I have found it below:

http://wiki.ocssolutions.com/Restarting_a_Rails_Application_Using_Passenger

Convert a list of objects to an array of one of the object's properties

For everyone who is stuck with .NET 2.0, like me, try the following way (applicable to the example in the OP):

ConfigItemList.ConvertAll<string>(delegate (ConfigItemType ci) 
{ 
   return ci.Name; 
}).ToArray();

where ConfigItemList is your list variable.

Android: How to Programmatically set the size of a Layout

my sample code

wv = (WebView) findViewById(R.id.mywebview);
wv.getLayoutParams().height = LayoutParams.MATCH_PARENT; // LayoutParams: android.view.ViewGroup.LayoutParams
// wv.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
wv.requestLayout();//It is necesary to refresh the screen

Converting JSON data to Java object

What's wrong with the standard stuff?

JSONObject jsonObject = new JSONObject(someJsonString);
JSONArray jsonArray = jsonObject.getJSONArray("someJsonArray");
String value = jsonArray.optJSONObject(i).getString("someJsonValue");

Resync git repo with new .gitignore file

I know this is an old question, but gracchus's solution doesn't work if file names contain spaces. VonC's solution to file names with spaces is to not remove them utilizing --ignore-unmatch, then remove them manually, but this will not work well if there are a lot.

Here is a solution that utilizes bash arrays to capture all files.

# Build bash array of the file names
while read -r file; do 
    rmlist+=( "$file" )
done < <(git ls-files -i --exclude-standard)

git rm –-cached "${rmlist[@]}"

git commit -m 'ignore update'

Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments

UPDATE:

onActivityCreated() is deprecated from API Level 28.


onCreate():

The onCreate() method in a Fragment is called after the Activity's onAttachFragment() but before that Fragment's onCreateView().
In this method, you can assign variables, get Intent extras, and anything else that doesn't involve the View hierarchy (i.e. non-graphical initialisations). This is because this method can be called when the Activity's onCreate() is not finished, and so trying to access the View hierarchy here may result in a crash.

onCreateView():

After the onCreate() is called (in the Fragment), the Fragment's onCreateView() is called. You can assign your View variables and do any graphical initialisations. You are expected to return a View from this method, and this is the main UI view, but if your Fragment does not use any layouts or graphics, you can return null (happens by default if you don't override).

onActivityCreated():

As the name states, this is called after the Activity's onCreate() has completed. It is called after onCreateView(), and is mainly used for final initialisations (for example, modifying UI elements). This is deprecated from API level 28.


To sum up...
... they are all called in the Fragment but are called at different times.
The onCreate() is called first, for doing any non-graphical initialisations. Next, you can assign and declare any View variables you want to use in onCreateView(). Afterwards, use onActivityCreated() to do any final initialisations you want to do once everything has completed.


If you want to view the official Android documentation, it can be found here:

There are also some slightly different, but less developed questions/answers here on Stack Overflow:

<button> vs. <input type="button" />. Which to use?

As far as CSS styling is concerned the <button type="submit" class="Btn">Example</button> is better as it gives you the ability to use CSS :before and :after pseudo classes which can help.

Due to the <input type="button"> visually rendering different to an <a> or <span> when styled with classes in certain situations I avoid them.

It's very worth noting the current top answer was written in 2009. IE6 isn't a concern now days so <button type="submit">Wins</button> styling consistency in my eyes comes out on top.

SQL WHERE condition is not equal to?

Look back to formal logic and algebra. An expression like

A & B & (D | E)

may be negated in a couple of ways:

  • The obvious way:

    !( A & B & ( D | E ) )
    
  • The above can also be restated, you just need to remember some properties of logical expressions:

    • !( A & B ) is the equivalent of (!A | !B).
    • !( A | B ) is the equivalent of (!A & !B).
    • !( !A ) is the equivalent of (A).

    Distribute the NOT (!) across the entire expression to which it applies, inverting operators and eliminating double negatives as you go along:

        !A | !B | ( !D & !E )
    

So, in general, any where clause may be negated according to the above rules. The negation of this

select *
from foo
where      test-1
  and      test-2
  and (    test-3
        OR test-4
      )

is

select *
from foo
where NOT(          test-1
           and      test-2
           and (    test-3
                 OR test-4
               )
         )

or

select *
from foo
where        not test-1
  OR         not test-2
  OR   (     not test-3
         and not test-4
       )

Which is better? That's a very context-sensitive question. Only you can decide that.

Be aware, though, that the use of NOT can affect what the optimizer can or can't do. You might get a less than optimal query plan.

jQuery checkbox change and click event

Late answer, but you can also use on("change")

_x000D_
_x000D_
$('#check').on('change', function() {
     var checked = this.checked
    $('span').html(checked.toString())
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="check"> <span>Check me!</span>
_x000D_
_x000D_
_x000D_

How can I extract substrings from a string in Perl?

This just requires a small change to my last answer:

my ($guid, $scheme, $star) = $line =~ m{
    The [ ] Scheme [ ] GUID: [ ]
    ([a-zA-Z0-9-]+)          #capture the guid
    [ ]
    \(  (.+)  \)             #capture the scheme 
    (?:
        [ ]
        ([*])                #capture the star 
    )?                       #if it exists
}x;

Matplotlib 2 Subplots, 1 Colorbar

Shared colormap and colorbar

This is for the more complex case where the values are not just between 0 and 1; the cmap needs to be shared instead of just using the last one.

import numpy as np
from matplotlib.colors import Normalize
import matplotlib.pyplot as plt
import matplotlib.cm as cm
fig, axes = plt.subplots(nrows=2, ncols=2)
cmap=cm.get_cmap('viridis')
normalizer=Normalize(0,4)
im=cm.ScalarMappable(norm=normalizer)
for i,ax in enumerate(axes.flat):
    ax.imshow(i+np.random.random((10,10)),cmap=cmap,norm=normalizer)
    ax.set_title(str(i))
fig.colorbar(im, ax=axes.ravel().tolist())
plt.show()

Removing cordova plugins from the project

cordova platform rm android

cordova plugin rm cordova-plugin-firebase

cordova platform add android

ionic 2 - Error Could not find an installed version of Gradle either in Android Studio

For windows users:

Download gradle binary from the link in the answer Gradle Download

Extract the zip file to 'C:\Gradle' or somewhere else

open Edit Environment variable dialog from start menu > Search

Click 'New' under system variables and add as below

Variable Name GRADLE_HOME Variable Value C:\Gradle\gradle-4.0.1

Then choose PATH variable from system variable list

append the gradle path to variable value like this C:\Gradle\gradle-4.0.1\bin

then press win Key+R type cmd then enter > in command terminal type gradle -v

if the setup is correct you will see the gradle installation details

Postgres: INSERT if does not exist already

I know this question is from a while ago, but thought this might help someone. I think the easiest way to do this is via a trigger. E.g.:

Create Function ignore_dups() Returns Trigger
As $$
Begin
    If Exists (
        Select
            *
        From
            hundred h
        Where
            -- Assuming all three fields are primary key
            h.name = NEW.name
            And h.hundred_slug = NEW.hundred_slug
            And h.status = NEW.status
    ) Then
        Return NULL;
    End If;
    Return NEW;
End;
$$ Language plpgsql;

Create Trigger ignore_dups
    Before Insert On hundred
    For Each Row
    Execute Procedure ignore_dups();

Execute this code from a psql prompt (or however you like to execute queries directly on the database). Then you can insert as normal from Python. E.g.:

sql = "Insert Into hundreds (name, name_slug, status) Values (%s, %s, %s)"
cursor.execute(sql, (hundred, hundred_slug, status))

Note that as @Thomas_Wouters already mentioned, the code above takes advantage of parameters rather than concatenating the string.

Connect Android to WiFi Enterprise network EAP(PEAP)

Thanks for enlightening us Cypawer.

I also tried this app https://play.google.com/store/apps/details?id=com.oneguyinabasement.leapwifi

and it worked flawlessly.

Leap Wifi Connector

Adding a Method to an Existing Object Instance

There are at least two ways for attach a method to an instance without types.MethodType:

>>> class A:
...  def m(self):
...   print 'im m, invoked with: ', self

>>> a = A()
>>> a.m()
im m, invoked with:  <__main__.A instance at 0x973ec6c>
>>> a.m
<bound method A.m of <__main__.A instance at 0x973ec6c>>
>>> 
>>> def foo(firstargument):
...  print 'im foo, invoked with: ', firstargument

>>> foo
<function foo at 0x978548c>

1:

>>> a.foo = foo.__get__(a, A) # or foo.__get__(a, type(a))
>>> a.foo()
im foo, invoked with:  <__main__.A instance at 0x973ec6c>
>>> a.foo
<bound method A.foo of <__main__.A instance at 0x973ec6c>>

2:

>>> instancemethod = type(A.m)
>>> instancemethod
<type 'instancemethod'>
>>> a.foo2 = instancemethod(foo, a, type(a))
>>> a.foo2()
im foo, invoked with:  <__main__.A instance at 0x973ec6c>
>>> a.foo2
<bound method instance.foo of <__main__.A instance at 0x973ec6c>>

Useful links:
Data model - invoking descriptors
Descriptor HowTo Guide - invoking descriptors

Linear Layout and weight in Android

Try setting the layout_width of both buttons to "0dip" and the weight of both buttons to 0.5

Convert javascript object or array to json for ajax data

I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:

var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";

console.log( JSON.stringify(display) );

This will print:

["none","block","none"]

This is how JSON actually serializes array. However what you want to see is something like:

{"0":"none","1":"block","2":"none"}

To get this format you want to serialize object, not array. So let's rewrite above code like this:

var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";

console.log( JSON.stringify(display2) );

This will print in the format you want.

You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console

ImportError: cannot import name NUMPY_MKL

yes,Just reinstall numpy,it works.

default select option as blank

In order to show please select a value in drop down and hide it after some value is selected . please use the below code.

it will also support required validation.

_x000D_
_x000D_
<select class="form-control" required>_x000D_
<option disabled selected value style="display:none;">--Please select a value</option>_x000D_
              <option >Data 1</option>_x000D_
              <option >Data 2</option>_x000D_
              <option >Data 3</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

"pip install json" fails on Ubuntu

json is a built-in module, you don't need to install it with pip.

How to send FormData objects with Ajax-requests in jQuery?

There are a few yet to be mentioned techniques available for you. Start with setting the contentType property in your ajax params.

Building on pradeek's example:

$('form').submit(function (e) {
    var data;

    data = new FormData();
    data.append('file', $('#file')[0].files[0]);

    $.ajax({
        url: 'http://hacheck.tel.fer.hr/xml.pl',
        data: data,
        processData: false,
        type: 'POST',

        // This will override the content type header, 
        // regardless of whether content is actually sent.
        // Defaults to 'application/x-www-form-urlencoded'
        contentType: 'multipart/form-data', 

        //Before 1.5.1 you had to do this:
        beforeSend: function (x) {
            if (x && x.overrideMimeType) {
                x.overrideMimeType("multipart/form-data");
            }
        },
        // Now you should be able to do this:
        mimeType: 'multipart/form-data',    //Property added in 1.5.1

        success: function (data) {
            alert(data);
        }
    });

    e.preventDefault();
});

In some cases when forcing jQuery ajax to do non-expected things, the beforeSend event is a great place to do it. For a while people were using beforeSend to override the mimeType before that was added into jQuery in 1.5.1. You should be able to modify just about anything on the jqXHR object in the before send event.

How do I check if an object's type is a particular subclass in C++?

 

class Base
{
  public: virtual ~Base() {}
};

class D1: public Base {};

class D2: public Base {};

int main(int argc,char* argv[]);
{
  D1   d1;
  D2   d2;

  Base*  x = (argc > 2)?&d1:&d2;

  if (dynamic_cast<D2*>(x) == nullptr)
  {
    std::cout << "NOT A D2" << std::endl;
  }
  if (dynamic_cast<D1*>(x) == nullptr)
  {
    std::cout << "NOT A D1" << std::endl;
  }
}

How to start MySQL server on windows xp

Type

C:\> "C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld" --console

to start the sql server and then test the client connection.

How can I start an interactive console for Perl?

Under Debian/Ubuntu:

$ sudo apt-get install libdevel-repl-perl
$ re.pl

$ sudo apt-get install libapp-repl-perl
$ iperl

How to see remote tags?

You can list the tags on remote repository with ls-remote, and then check if it's there. Supposing the remote reference name is origin in the following.

git ls-remote --tags origin

And you can list tags local with tag.

git tag

You can compare the results manually or in script.

How to determine the encoding of text?

Here is an example of reading and taking at face value a chardet encoding prediction, reading n_lines from the file in the event it is large.

chardet also gives you a probability (i.e. confidence) of it's encoding prediction (haven't looked how they come up with that), which is returned with its prediction from chardet.predict(), so you could work that in somehow if you like.

def predict_encoding(file_path, n_lines=20):
    '''Predict a file's encoding using chardet'''
    import chardet

    # Open the file as binary data
    with open(file_path, 'rb') as f:
        # Join binary lines for specified number of lines
        rawdata = b''.join([f.readline() for _ in range(n_lines)])

    return chardet.detect(rawdata)['encoding']

Float a div in top right corner without overlapping sibling header

This worked for me:

h1 {
    display: inline;
    overflow: hidden;
}
div {
    position: relative;
    float: right;
}

It's similar to the approach of the media object, by Stubbornella.

Edit: As they comment below, you need to place the element that's going to float before the element that's going to wrap (the one in your first fiddle)

How can I truncate a datetime in SQL Server?

In SQl 2005 your trunc_date function could be written like this.

(1)

CREATE FUNCTION trunc_date(@date DATETIME)
RETURNS DATETIME
AS
BEGIN
    CAST(FLOOR( CAST( @date AS FLOAT ) )AS DATETIME)
END

The first method is much much cleaner. It uses only 3 method calls including the final CAST() and performs no string concatenation, which is an automatic plus. Furthermore, there are no huge type casts here. If you can imagine that Date/Time stamps can be represented, then converting from dates to numbers and back to dates is a fairly easy process.

(2)

CREATE FUNCTION trunc_date(@date DATETIME)
RETURNS DATETIME
AS
BEGIN
      SELECT CONVERT(varchar, @date,112)
END

If you are concerned about microsoft's implementation of datetimes (2) or (3) might be ok.

(3)

CREATE FUNCTION trunc_date(@date DATETIME)
RETURNS DATETIME
AS
BEGIN
SELECT CAST((STR( YEAR( @date ) ) + '/' +STR( MONTH( @date ) ) + '/' +STR( DAY(@date ) )
) AS DATETIME
END

Third, the more verbose method. This requires breaking the date into its year, month, and day parts, putting them together in "yyyy/mm/dd" format, then casting that back to a date. This method involves 7 method calls including the final CAST(), not to mention string concatenation.

Convert a CERT/PEM certificate to a PFX certificate

If you have a self-signed certificate generated by makecert.exe on a Windows machine, you will get two files: cert.pvk and cert.cer. These can be converted to a pfx using pvk2pfx

pvk2pfx is found in the same location as makecert (e.g. C:\Program Files (x86)\Windows Kits\10\bin\x86 or similar)

pvk2pfx -pvk cert.pvk -spc cert.cer -pfx cert.pfx

How to prove that a problem is NP complete?

In order to prove that a problem L is NP-complete, we need to do the following steps:

  1. Prove your problem L belongs to NP (that is that given a solution you can verify it in polynomial time)
  2. Select a known NP-complete problem L'
  3. Describe an algorithm f that transforms L' into L
  4. Prove that your algorithm is correct (formally: x ? L' if and only if f(x) ? L )
  5. Prove that algo f runs in polynomial time

Javascript onclick hide div

Simple & Best way:

onclick="parentNode.remove()"

Deletes the complete parent from html

How to POST a JSON object to a JAX-RS service

The answer was surprisingly simple. I had to add a Content-Type header in the POST request with a value of application/json. Without this header Jersey did not know what to do with the request body (in spite of the @Consumes(MediaType.APPLICATION_JSON) annotation)!

How can I change the color of my prompt in zsh (different from normal text)?

man zshall and search for PROMPT EXPANSION

After reading the existing answers here, several of them are conflicting. I've tried the various approaches on systems running zsh 4.2 and 5+ and found that the reason these answers are conflicting is that they do not say which version of ZSH they are targeted at. Different versions use different syntax for this and some of them require various autoloads.

So, the best bet is probably to man zshall and search for PROMPT EXPANSION to find out all the rules for your particular installation of zsh. Note in the comments, things like "I use Ubuntu 11.04 or 10.4 or OSX" Are not very meaningful as it's unclear which version of ZSH you are using. Ubuntu 11.04 does not imply a newer version of ZSH than ubuntu 10.04. There may be any number of reasons that an older version was installed. For that matter a newer version of ZSH does not imply which syntax to use without knowing which version of ZSH it is.

Binding List<T> to DataGridView in WinForm

List does not implement IBindingList so the grid does not know about your new items.

Bind your DataGridView to a BindingList<T> instead.

var list = new BindingList<Person>(persons);
myGrid.DataSource = list;

But I would even go further and bind your grid to a BindingSource

var list = new List<Person>()
{
    new Person { Name = "Joe", },
    new Person { Name = "Misha", },
};
var bindingList = new BindingList<Person>(list);
var source = new BindingSource(bindingList, null);
grid.DataSource = source;

SSLHandshakeException: No subject alternative names present

Thanks,Bruno for giving me heads up on Common Name and Subject Alternative Name. As we figured out certificate was generated with CN with DNS name of network and asked for regeneration of new certificate with Subject Alternative Name entry i.e. san=ip:10.0.0.1. which is the actual solution.

But, we managed to find out a workaround with which we can able to run on development phase. Just add a static block in the class from which we are making ssl connection.

static {
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
        {
            public boolean verify(String hostname, SSLSession session)
            {
                // ip address of the service URL(like.23.28.244.244)
                if (hostname.equals("23.28.244.244"))
                    return true;
                return false;
            }
        });
}

If you happen to be using Java 8, there is a much slicker way of achieving the same result:

static {
    HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("127.0.0.1"));
}

What is Teredo Tunneling Pseudo-Interface?

Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.

If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)

How to use 'git pull' from the command line?

Open up your git bash and type

echo $HOME

This shall be the same folder as you get when you open your command window (cmd) and type

echo %USERPROFILE%

And – of course – the .ssh folder shall be present on THAT directory.

jQuery access input hidden value

If you have an asp.net HiddenField you need to:

To access HiddenField Value:

$('#<%=HF.ClientID%>').val()  // HF = your hiddenfield ID

To set HiddenFieldValue

$('#<%=HF.ClientID%>').val('some value')   // HF = your hiddenfield ID

C++ static virtual members?

This question is over a decade old, but it looks like it gets a good amount of traffic, so I wanted to post an alternative using modern C++ features that I haven't seen anywhere else.

This solution uses CRTP and SFINAE to perform static dispatching. That, in itself, is nothing new, but all such implementations I've found lack strict signature checking for "overrides." This implementation requires that the "overriding" method signature exactly matches that of the "overridden" method. This behavior more closely resembles that of virtual functions, while also allowing us to effectively overload and "override" a static method.

Note that I put override in quotes because, strictly speaking, we're not technically overriding anything. Instead, we're calling a dispatch method X with signature Y that forwards all of its arguments to T::X, where T is to the first type among a list of types such that T::X exists with signature Y. This list of types considered for dispatching can be anything, but generally would include a default implementation class and the derived class.

Implementation

#include <experimental/type_traits>

template <template <class...> class Op, class... Types>
struct dispatcher;

template <template <class...> class Op, class T>
struct dispatcher<Op, T> : std::experimental::detected_t<Op, T> {};

template <template <class...> class Op, class T, class... Types>
struct dispatcher<Op, T, Types...>
  : std::experimental::detected_or_t<
    typename dispatcher<Op, Types...>::type, Op, T> {};


// Helper to convert a signature to a function pointer
template <class Signature> struct function_ptr;

template <class R, class... Args> struct function_ptr<R(Args...)> {
    using type = R (*)(Args...);
};


// Macro to simplify creation of the dispatcher
// NOTE: This macro isn't smart enough to handle creating an overloaded
//       dispatcher because both dispatchers will try to use the same
//       integral_constant type alias name. If you want to overload, do it
//       manually or make a smarter macro that can somehow put the signature in
//       the integral_constant type alias name.
#define virtual_static_method(name, signature, ...)                            \
    template <class VSM_T>                                                     \
    using vsm_##name##_type = std::integral_constant<                          \
        function_ptr<signature>::type, &VSM_T::name>;                          \
                                                                               \
    template <class... VSM_Args>                                               \
    static auto name(VSM_Args&&... args)                                       \
    {                                                                          \
        return dispatcher<vsm_##name##_type, __VA_ARGS__>::value(              \
            std::forward<VSM_Args>(args)...);                                  \
    }

Example Usage

#include <iostream>

template <class T>
struct Base {
    // Define the default implementations
    struct defaults {
        static std::string alpha() { return "Base::alpha"; };
        static std::string bravo(int) { return "Base::bravo"; }
    };

    // Create the dispatchers
    virtual_static_method(alpha, std::string(void), T, defaults);
    virtual_static_method(bravo, std::string(int), T, defaults);
    
    static void where_are_the_turtles() {
        std::cout << alpha() << std::endl;  // Derived::alpha
        std::cout << bravo(1) << std::endl; // Base::bravo
    }
};

struct Derived : Base<Derived> {
    // Overrides Base::alpha
    static std::string alpha(){ return "Derived::alpha"; }

    // Does not override Base::bravo because signatures differ (even though
    // int is implicitly convertible to bool)
    static std::string bravo(bool){ return "Derived::bravo"; }
};

int main() {
    Derived::where_are_the_turtles();
}

MySQL - How to select rows where value is in array?

By the time the query gets to SQL you have to have already expanded the list. The easy way of doing this, if you're using IDs from some internal, trusted data source, where you can be 100% certain they're integers (e.g., if you selected them from your database earlier) is this:

$sql = 'SELECT * WHERE id IN (' . implode(',', $ids) . ')';

If your data are coming from the user, though, you'll need to ensure you're getting only integer values, perhaps most easily like so:

$sql = 'SELECT * WHERE id IN (' . implode(',', array_map('intval', $ids)) . ')';

scatter plot in matplotlib

Maybe something like this:

import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

EDIT:

Let me see if I understand you correctly now:

You have:

       test1 | test2 | test3
test3 |   1   |   0  |  1

test4 |   0   |   1  |  0

test5 |   1   |   1  |  0

Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.

Let's say you results are stored in a 2-D list:

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

We want to transform them into two variables so we are able to plot them.

And I believe this code will give you what you are looking for:

import matplotlib
import pylab


results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)       


matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

Notice that I do need to import pylab, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.

How to remove all non-alpha numeric characters from a string in MySQL?

From a performance point of view, (and on the assumption that you read more than you write)

I think the best way would be to pre calculate and store a stripped version of the column, This way you do the transform less.

You can then put an index on the new column and get the database to do the work for you.

How to remove an element slowly with jQuery?

All the answers are good, but I found they all lacked that professional "polish".

I came up with this, fading out, sliding up, then removing:

$target.fadeTo(1000, 0.01, function(){ 
    $(this).slideUp(150, function() {
        $(this).remove(); 
    }); 
});

Error sending json in POST to web API service

It require to include Content-Type:application/json in web api request header section when not mention any content then by default it is Content-Type:text/plain passes to request.

Best way to test api on postman tool.

Centering a canvas

Same codes from Nickolay above, but tested on IE9 and chrome (and removed the extra rendering):

window.onload = window.onresize = function() {
   var canvas = document.getElementById('canvas');
   var viewportWidth = window.innerWidth;
   var viewportHeight = window.innerHeight;
   var canvasWidth = viewportWidth * 0.8;
   var canvasHeight = canvasWidth / 2;

   canvas.style.position = "absolute";
   canvas.setAttribute("width", canvasWidth);
   canvas.setAttribute("height", canvasHeight);
   canvas.style.top = (viewportHeight - canvasHeight) / 2 + "px";
   canvas.style.left = (viewportWidth - canvasWidth) / 2 + "px";
}

HTML:

<body>
  <canvas id="canvas" style="background: #ffffff">
     Canvas is not supported.
  </canvas>
</body>

The top and left offset only works when I add px.

Read lines from a text file but skip the first two lines

Open sFileName For Input As iFileNum

Dim LineNum As Long
LineNum = 0

Do While Not EOF(iFileNum)
  LineNum = LineNum + 1
  Line Input #iFileNum, Fields
  If LineNum > 2 Then
    DoStuffWith(Fields)
  End If
Loop

git stash blunder: git stash pop and ended up with merge conflicts

If, like me, what you usually want is to overwrite the contents of the working directory with that of the stashed files, and you still get a conflict, then what you want is to resolve the conflict using git checkout --theirs -- . from the root.

After that, you can git reset to bring all the changes from the index to the working directory, since apparently in case of conflict the changes to non-conflicted files stay in the index.

You may also want to run git stash drop [<stash name>] afterwards, to get rid of the stash, because git stash pop doesn't delete it in case of conflicts.

Java naming convention for static final variables

There is no "right" way -- there are only conventions. You've stated the most common convention, and the one that I follow in my own code: all static finals should be in all caps. I imagine other teams follow other conventions.

How can I add to a List's first position?

Use Insert method: list.Insert(0, item);

Check if a file is executable

Take a look at the various test operators (this is for the test command itself, but the built-in BASH and TCSH tests are more or less the same).

You'll notice that -x FILE says FILE exists and execute (or search) permission is granted.

BASH, Bourne, Ksh, Zsh Script

if [[ -x "$file" ]]
then
    echo "File '$file' is executable"
else
    echo "File '$file' is not executable or found"
fi

TCSH or CSH Script:

if ( -x "$file" ) then
    echo "File '$file' is executable"
else
    echo "File '$file' is not executable or found"
endif

To determine the type of file it is, try the file command. You can parse the output to see exactly what type of file it is. Word 'o Warning: Sometimes file will return more than one line. Here's what happens on my Mac:

$ file /bin/ls    
/bin/ls: Mach-O universal binary with 2 architectures
/bin/ls (for architecture x86_64):  Mach-O 64-bit executable x86_64
/bin/ls (for architecture i386):    Mach-O executable i386

The file command returns different output depending upon the OS. However, the word executable will be in executable programs, and usually the architecture will appear too.

Compare the above to what I get on my Linux box:

$ file /bin/ls
/bin/ls: ELF 64-bit LSB executable, AMD x86-64, version 1 (SYSV), for GNU/Linux 2.6.9, dynamically linked (uses shared libs), stripped

And a Solaris box:

$ file /bin/ls
/bin/ls:        ELF 32-bit MSB executable SPARC Version 1, dynamically linked, stripped

In all three, you'll see the word executable and the architecture (x86-64, i386, or SPARC with 32-bit).


Addendum

Thank you very much, that seems the way to go. Before I mark this as my answer, can you please guide me as to what kind of script shell check I would have to perform (ie, what kind of parsing) on 'file' in order to check whether I can execute a program ? If such a test is too difficult to make on a general basis, I would at least like to check whether it's a linux executable or osX (Mach-O)

Off the top of my head, you could do something like this in BASH:

if [ -x "$file" ] && file "$file" | grep -q "Mach-O"
then
    echo "This is an executable Mac file"
elif [ -x "$file" ] && file "$file" | grep -q "GNU/Linux"
then
    echo "This is an executable Linux File"
elif [ -x "$file" ] && file "$file" | grep q "shell script"
then
    echo "This is an executable Shell Script"
elif [ -x "$file" ]
then
    echo "This file is merely marked executable, but what type is a mystery"
else
    echo "This file isn't even marked as being executable"
fi

Basically, I'm running the test, then if that is successful, I do a grep on the output of the file command. The grep -q means don't print any output, but use the exit code of grep to see if I found the string. If your system doesn't take grep -q, you can try grep "regex" > /dev/null 2>&1.

Again, the output of the file command may vary from system to system, so you'll have to verify that these will work on your system. Also, I'm checking the executable bit. If a file is a binary executable, but the executable bit isn't on, I'll say it's not executable. This may not be what you want.

Can I change a column from NOT NULL to NULL without dropping it?

For MYSQL

ALTER TABLE myTable MODIFY myColumn {DataType} NULL

Select values of checkbox group with jQuery

Use .map() (adapted from the example at http://api.jquery.com/map/):

var values = $("input[name='user_group[]']:checked").map(function(index,domElement) {
    return $(domElement).val();
});

How do I redirect in expressjs while passing some context?

we can use express-session to send the required data

when you initialise the app

const express = require('express');
const app = express();
const session = require('express-session');
app.use(session({secret: 'mySecret', resave: false, saveUninitialized: false}));

so before redirection just save the context for the session

app.post('/category', function(req, res) {
    // add your context here 
req.session.context ='your context here' ;
    res.redirect('/');
});

Now you can get the context anywhere for the session. it can get just by req.session.context

app.get('/', function(req, res) {

    // So prepare the context
var context=req.session.context;
    res.render('home.jade', context);
});

Efficient way to add spaces between characters in a string

The most efficient way is to take input make the logic and run

so the code is like this to make your own space maker

need = input("Write a string:- ")
result = ''
for character in need:
   result = result + character + ' '
print(result)    # to rid of space after O

but if you want to use what python give then use this code

need2 = input("Write a string:- ")

print(" ".join(need2))

Eclipse: How to install a plugin manually?

You can try this

click Help>Install New Software on the menu bar

enter image description here

enter image description here

enter image description here

enter image description here

Removing duplicate rows in Notepad++

Since Notepad++ Version 6 you can use this regex in the search and replace dialogue:

^(.*?)$\s+?^(?=.*^\1$)

and replace with nothing. This leaves from all duplicate rows the last occurrence in the file.

No sorting is needed for that and the duplicate rows can be anywhere in the file!

You need to check the options "Regular expression" and ". matches newline":

Notepad++ Replace dialogue

  • ^ matches the start of the line.

  • (.*?) matches any characters 0 or more times, but as few as possible (It matches exactly on row, this is needed because of the ". matches newline" option). The matched row is stored, because of the brackets around and accessible using \1

  • $ matches the end of the line.

  • \s+?^ this part matches all whitespace characters (newlines!) till the start of the next row ==> This removes the newlines after the matched row, so that no empty row is there after the replacement.

  • (?=.*^\1$) this is a positive lookahead assertion. This is the important part in this regex, a row is only matched (and removed), when there is exactly the same row following somewhere else in the file.

how to call service method from ng-change of select in angularjs?

You have at least two issues in your code:

  • ng-change="getScoreData(Score)

    Angular doesn't see getScoreData method that refers to defined service

  • getScoreData: function (Score, callback)

    We don't need to use callback since GET returns promise. Use then instead.

Here is a working example (I used random address only for simulation):

HTML

<select ng-model="score"
        ng-change="getScoreData(score)" 
        ng-options="score as score.name for score in  scores"></select>
    <pre>{{ScoreData|json}}</pre> 

JS

var fessmodule = angular.module('myModule', ['ngResource']);

fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {

    $scope.scores = [{
        name: 'Bukit Batok Street 1',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
    }, {
        name: 'London 8',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
    }];

    $scope.getScoreData = function(score) {
        ScoreDataService.getScoreData(score).then(function(result) {
            $scope.ScoreData = result;
        }, function(result) {
            alert("Error: No data returned");
        });
    };

});

fessmodule.$inject = ['$scope', 'ScoreDataService'];

fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {

    var factory = {
        getScoreData: function(score) {
            console.log(score);
            var data = $http({
                method: 'GET',
                url: score.URL
            });


            return data;
        }
    }
    return factory;
}]);

Demo Fiddle

Python sys.argv lists and indexes

let's say on the command-line you have:

C:\> C:\Documents and Settings\fred\My Documents\Downloads\google-python-exercises
\google-python-exercises\hello.py John

to make it easier to read, let's just shorten this to:

C:\> hello.py John

argv represents all the items that come along via the command-line input, but counting starts at zero (0) not one (1): in this case, "hello.py" is element 0, "John" is element 1

in other words, sys.argv[0] == 'hello.py' and sys.argv[1] == 'John' ... but look, how many elements is this? 2, right! so even though the numbers are 0 and 1, there are 2 elements here.

len(sys.argv) >= 2 just checks whether you entered at least two elements. in this case, we entered exactly 2.

now let's translate your code into English:

define main() function:
    if there are at least 2 elements on the cmd-line:
        set 'name' to the second element located at index 1, e.g., John
    otherwise there is only 1 element... the program name, e.g., hello.py:
        set 'name' to "World" (since we did not get any useful user input)
    display 'Hello' followed by whatever i assigned to 'name'

so what does this mean? it means that if you enter:

  • "hello.py", the code outputs "Hello World" because you didn't give a name
  • "hello.py John", the code outputs "Hello John" because you did
  • "hello.py John Paul", the code still outputs "Hello John" because it does not save nor use sys.argv[2], which was "Paul" -- can you see in this case that len(sys.argv) == 3 because there are 3 elements in the sys.argv list?

latex large division sign in a math formula

A possible soluttion that requires tweaking, but is very flexible is to use one of \big, \Big, \bigg,\Bigg in front of your division sign - these will make it progressively larger. For your formula, I think

  $\frac{a_1}{a_2} \Big/ \frac{b_1}{b_2}$

looks nicer than \middle\ which is automatically sized and IMHO is a bit too large.

Codesign error: Provisioning profile cannot be found after deleting expired profile

Unfortunately this approach didn't work out for me. But here's a fix which worked for me (to get this to work you need a working project file on Subversion or so):

I did roll back to an working version of my project file. As it isn't possible to revert with Xcode (Where is the 'Revert' option in Xcode 4's Source Control?) - I used Tortoise, my Windows machine and this Tutorial (http://tortoisesvn.net/docs/nightly/TortoiseSVN_en/tsvn-howto-rollback.html) to roll back to an older project file.

As the Tutorial didn't work out for me, I just used Tortoise to save the working revision of my project file to an usb stick to port it to my mac. After that I replaced the new broken project file with the old working one, cleaned and it worked like a charm!

How can I find out if an .EXE has Command-Line Options?

The easiest way would be to use use ProcessExplorer but it would still require some searching.

Make sure your exe is running and open ProcessExplorer. In ProcessExplorer find the name of your binary file and double click it to show properties. Click the Strings tab. Search down the list of string found in the binary file. Most strings will be garbage so they can be ignored. Search for anything that might possibly resemble a command line switch. Test this switch from the command line and see if it does anything.

Note that it might be your binary simply has no command line switches.

For reference here is the above steps applied to the Chrome executable. The command line switches accepted by Chrome can be seen in the list:

Process explorer analyzing Chrome.exe

How to make unicode string with python3

In a Python 2 program that I used for many years there was this line:

ocd[i].namn=unicode(a[:b], 'utf-8')

This did not work in Python 3.

However, the program turned out to work with:

ocd[i].namn=a[:b]

I don't remember why I put unicode there in the first place, but I think it was because the name can contains Swedish letters åäöÅÄÖ. But even they work without "unicode".

How to avoid a System.Runtime.InteropServices.COMException?

I got this exception while coping a object(variable) Matrix Array into Excel sheet. The solution to this is, Matrix array Index(i,j) must start from (0,0) whereas Excel sheet should start with Matrix Array index (i,j) from (1,1) .

I hope you this concept.

How to compare 2 dataTables

 public static bool AreTablesTheSame( DataTable tbl1, DataTable tbl2)
 {
    if (tbl1.Rows.Count != tbl2.Rows.Count || tbl1.Columns.Count != tbl2.Columns.Count)
                return false;


    for ( int i = 0; i < tbl1.Rows.Count; i++)
    {
        for ( int c = 0; c < tbl1.Columns.Count; c++)
        {
            if (!Equals(tbl1.Rows[i][c] ,tbl2.Rows[i][c]))
                        return false;
        }
     }
     return true;
  }

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

While it's true that @RequestBody must map to a single object, that object can be a Map, so this gets you a good way to what you are attempting to achieve (no need to write a one off backing object):

@RequestMapping(value = "/Test", method = RequestMethod.POST)
@ResponseBody
public boolean getTest(@RequestBody Map<String, String> json) {
   //json.get("str1") == "test one"
}

You can also bind to Jackson's ObjectNode if you want a full JSON tree:

public boolean getTest(@RequestBody ObjectNode json) {
   //json.get("str1").asText() == "test one"

How can I repeat a character in Bash?

Another mean to repeat an arbitrary string n times:

Pros:

  • Works with POSIX shell.
  • Output can be assigned to a variable.
  • Repeats any string.
  • Very fast even with very large repeats.

Cons:

  • Requires Gnu Core Utils's yes command.
#!/usr/bin/sh
to_repeat='='
repeat_count=80
yes "$to_repeat" | tr -d '\n' | head -c "$repeat_count"

With an ANSI terminal and US-ASCII characters to repeat. You can use an ANSI CSI escape sequence. It is the fastest way to repeat a character.

#!/usr/bin/env bash

char='='
repeat_count=80
printf '%c\e[%db' "$char" "$repeat_count"

Or statically:

Print a line of 80 times =:

printf '=\e[80b\n'

Limitations:

  • Not all terminals understands the repeat_char ANSI CSI sequence.
  • Only US-ASCII or single-byte ISO characters can be repeated.
  • Repeat stops at last column, so you can use a large value to fill a whole line regardless of terminal width.
  • The repeat is only for display. Capturing output into a shell variable will not expand the repeat_char ANSI CSI sequence into the repeated character.

ASP.Net MVC 4 Form with 2 submit buttons/actions

That's what we have in our applications:
Attribute

public class HttpParamActionAttribute : ActionNameSelectorAttribute
{
    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
    {
        if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
            return true;

        var request = controllerContext.RequestContext.HttpContext.Request;
        return request[methodInfo.Name] != null;
    }
}

Actions decorated with it:


[HttpParamAction]
public ActionResult Save(MyModel model)
{
    // ...
}

[HttpParamAction]
public ActionResult Publish(MyModel model)
{
    // ...
}

HTML/Razor

@using (@Html.BeginForm())
{
    <!-- form content here -->
    <input type="submit" name="Save" value="Save" />
    <input type="submit" name="Publish" value="Publish" />
}

name attribute of submit button should match action/method name

This way you do not have to hard-code urls in javascript

sending email via php mail function goes to spam

One thing that I have observed is likely the email address you're providing is not a valid email address at the domain. like [email protected]. The email should be existing at Google Domain. I had alot of issues before figuring that out myself... Hope it helps.

How can you float: right in React Native?

you can use following these component to float right

alignItems aligns children in the cross direction. For example, if children are flowing vertically, alignItems controls how they align horizontally.

alignItems: 'flex-end'

justifyContent aligns children in the main direction. For example, if children are flowing vertically, justifyContent controls how they align vertically.

justifyContent: 'flex-end'

alignSelf controls how a child aligns in the cross direction,

alignSelf : 'flex-end'

How to connect HTML Divs with Lines?

Create a div that is the line with the code like this:

CSS

div#lineHorizontal {
    background-color: #000;
    width: //the width of the line or how far it goes sidewards;
    height: 2px;
    display: inline-block;
    margin: 0px;
 }
div#block {
    background-color: #777;
    display: inline-block;
    margin: 0px;
}

HTML

<div id="block">
</div>
<div id="lineHorizontal">
</div>
<div id="block">
</div>

This will display a block with a horizontal line to another block.

On mobile devices you could use (caniuse.com/transforms2d)

iOS change navigation bar title font and color

There is nothing wrong with the other answers. I'm just sharing the storyboard version for setting the font.

1. Select Your Navigation Bar within your Navigation Controller

navbar

2. Change the Title Font in the Attributes Inspector

title-font

(You will likely need to toggle the Bar Tint for the Navigation Bar before Xcode picks up the new font)

Notes (Caveats)

Verified that this does work on Xcode 7.1.1+. (See the Samples below)

  1. You do need to toggle the nav bar tint before the font takes effect (seems like a bug in Xcode; you can switch it back to default and font will stick)
  2. If you choose a system font ~ Be sure to make sure the size is not 0.0 (Otherwise the new font will be ignored)

size

  1. Seems like this works with no problem when only one NavBar is in the view hierarchy. It appears that secondary NavBars in the same stack are ignored. (Note that if you show the master navigation controller's navBar all the other custom navBar settings are ignored).

Gotchas (deux)

Some of these are repeated which means they are very likely worth noting.

  1. Sometimes the storyboard xml gets corrupt. This requires you to review the structure in Storyboard as Source Code mode (right click the storyboard file > Open As ...)
  2. In some cases the navigationItem tag associated with user defined runtime attribute was set as an xml child of the view tag instead of the view controller tag. If so remove it from between the tags for proper operation.
  3. Toggle the NavBar Tint to ensure the custom font is used.
  4. Verify the size parameter of the font unless using a dynamic font style
  5. View hierarchy will override the settings. It appears that one font per stack is possible.

Result

navbar-italic

Samples

Handling Custom Fonts

Note ~ A nice checklist can be found from the Code With Chris website and you can see the sample download project.

If you have your own font and want to use that in your storyboard, then there is a decent set of answers on the following SO Question. One answer identifies these steps.

  1. Get you custom font file(.ttf,.ttc)
  2. Import the font files to your Xcode project
  3. In the app-info.plist,add a key named Fonts provided by application.It's an array type , add all your font file names to the array,note:including the file extension.
  4. In the storyboard , on the NavigationBar go to the Attribute Inspector,click the right icon button of the Font select area.In the popup panel , choose Font to Custom, and choose the Family of you embeded font name.

Custom Font Workaround

So Xcode naturally looks like it can handle custom fonts on UINavigationItem but that feature is just not updating properly (The font selected is ignored).

UINavigationItem

To workaround this:

One way is to fix using the storyboard and adding a line of code: First add a UIView (UIButton, UILabel, or some other UIView subclass) to the View Controller (Not the Navigation Item...Xcode is not currently allowing one to do that). After you add the control you can modify the font in the storyboard and add a reference as an outlet to your View Controller. Just assign that view to the UINavigationItem.titleView. You could also set the text name in code if necessary. Reported Bug (23600285).

@IBOutlet var customFontTitleView: UIButton!

//Sometime later...    
self.navigationItem.titleView = customFontTitleView

Can't choose class as main class in IntelliJ

Select the folder containing the package tree of these classes, right-click and choose "Mark Directory as -> Source Root"

Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?

For Saturday and Sunday You can do something like this

             $('#orderdate').datepicker({
                               daysOfWeekDisabled: [0,6]
                 });

How to change MySQL data directory?

  1. Stop MySQL using the following command:

    sudo /etc/init.d/mysql stop
    
  2. Copy the existing data directory (default located in /var/lib/mysql) using the following command:

    sudo cp -R -p /var/lib/mysql /newpath
    
  3. edit the MySQL configuration file with the following command:

    sudo gedit /etc/mysql/my.cnf   # or perhaps /etc/mysql/mysql.conf.d/mysqld.cnf
    
  4. Look for the entry for datadir, and change the path (which should be /var/lib/mysql) to the new data directory.

  5. In the terminal, enter the command:

    sudo gedit /etc/apparmor.d/usr.sbin.mysqld
    
  6. Look for lines beginning with /var/lib/mysql. Change /var/lib/mysql in the lines with the new path.

  7. Save and close the file.

  8. Restart the AppArmor profiles with the command:

    sudo /etc/init.d/apparmor reload
    
  9. Restart MySQL with the command:

    sudo /etc/init.d/mysql restart
    
  10. Now login to MySQL and you can access the same databases you had before.

jinja2.exceptions.TemplateNotFound error

I think you shouldn't prepend themesDir. You only pass the filename of the template to flask, it will then look in a folder called templates relative to your python file.

Counting lines, words, and characters within a text file using Python

Functions that might be helpful:

  • open("file").read() which reads the contents of the whole file at once
  • 'string'.splitlines() which separates lines from each other (and discards empty lines)

By using len() and those functions you could accomplish what you're doing.

Laravel stylesheets and javascript don't load for non-base routes

i suggest you put it on route filter before on {project}/application/routes.php

Route::filter('before', function()
{
    // Do stuff before every request to your application...    
    Asset::add('jquery', 'js/jquery-2.0.0.min.js');
    Asset::add('style', 'template/style.css');
    Asset::add('style2', 'css/style.css');

});

and using blade template engine

{{ Asset::styles() }}
{{ Asset::scripts(); }}

or more on laravel managing assets docs

How to overcome TypeError: unhashable type: 'list'

Note: This answer does not explicitly answer the asked question. the other answers do it. Since the question is specific to a scenario and the raised exception is general, This answer points to the general case.

Hash values are just integers which are used to compare dictionary keys during a dictionary lookup quickly.

Internally, hash() method calls __hash__() method of an object which are set by default for any object.

Converting a nested list to a set

>>> a = [1,2,3,4,[5,6,7],8,9]
>>> set(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

This happens because of the list inside a list which is a list which cannot be hashed. Which can be solved by converting the internal nested lists to a tuple,

>>> set([1, 2, 3, 4, (5, 6, 7), 8, 9])
set([1, 2, 3, 4, 8, 9, (5, 6, 7)])

Explicitly hashing a nested list

>>> hash([1, 2, 3, [4, 5,], 6, 7])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'


>>> hash(tuple([1, 2, 3, [4, 5,], 6, 7]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

>>> hash(tuple([1, 2, 3, tuple([4, 5,]), 6, 7]))
-7943504827826258506

The solution to avoid this error is to restructure the list to have nested tuples instead of lists.

Use and meaning of "in" in an if statement?

You are used to using the javascript if, and I assume you know how it works.

in is a Pythonic way of implementing iteration. It's supposed to be easier for non-programmatic thinkers to adopt, but that can sometimes make it harder for programmatic thinkers, ironically.

When you say if x in y, you are literally saying:

"if x is in y", which assumes that y has an index. In that if statement then, each object at each index in y is checked against the condition.

Similarly,

for x in y

iterates through x's in y, where y is that indexable set of items.

Think of the if situation this way (pseudo-code):

for i in next:
    if i == "0" || i == "1":
        how_much = int(next)

It takes care of the iteration over next for you.

Happy coding!

Calculate the date yesterday in JavaScript

Try this

var d = new Date();
d.setDate(d.getDate() - 1);

How to set up fixed width for <td>?

In bootstarp 4 you can use row and col-* in table, I use it as below

<table class="table">
    <thead>
        <tr class="row">
            <th class="col-sm-3">3 row</th>
            <th class="col-sm-4">4 row</th>
            <th class="col-sm-5">5 row</th>
        </tr>
    </thead>
    <tbody>
        <tr class="row">
            <td class="col-sm-3">some text</td>
            <td class="col-sm-4">some text</td>
            <td class="col-sm-5">some text</td>
        </tr>
    </tbody>
</table>

Android: Force EditText to remove focus?

you have to remove <requestFocus/>

if you don't use it and still the same problem

user LinearLayout as a parent and set

android:focusable="true"
android:focusableInTouchMode="true"

Hope it's help you.

Extract matrix column values by matrix column name

> myMatrix <- matrix(1:10, nrow=2)
> rownames(myMatrix) <- c("A", "B")
> colnames(myMatrix) <- c("A", "B", "C", "D", "E")

> myMatrix
  A B C D  E
A 1 3 5 7  9
B 2 4 6 8 10

> myMatrix["A", "A"]
[1] 1

> myMatrix["A", ]
A B C D E 
1 3 5 7 9 

> myMatrix[, "A"]
A B 
1 2 

Hide horizontal scrollbar on an iframe?

If you are allowed to change the code of the document inside your iframe and that content is visible only using its parent window, simply add the following CSS in your iframe:

body {
    overflow:hidden;
}

Here a very simple example:

http://jsfiddle.net/u5gLoav9/

This solution allow you to:

  • Keep you HTML5 valid as it does not need scrolling="no" attribute on the iframe (this attribute in HTML5 has been deprecated).

  • Works on the majority of browsers using CSS overflow:hidden

  • No JS or jQuery necessary.

Notes:

To disallow scroll-bars horizontally, use this CSS instead:

overflow-x: hidden;

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

Javascript use variable as object name

You can set an objects property this way:

_x000D_
_x000D_
var obj = {};_x000D_
obj.whateverVarName = 'yourVal';_x000D_
console.log(obj);
_x000D_
_x000D_
_x000D_

Unioning two tables with different number of columns

Normally you need to have the same number of columns when you're using set based operators so Kangkan's answer is correct.

SAS SQL has specific operator to handle that scenario:

SAS(R) 9.3 SQL Procedure User's Guide

CORRESPONDING (CORR) Keyword

The CORRESPONDING keyword is used only when a set operator is specified. CORR causes PROC SQL to match the columns in table expressions by name and not by ordinal position. Columns that do not match by name are excluded from the result table, except for the OUTER UNION operator.

SELECT * FROM tabA
OUTER UNION CORR
SELECT * FROM tabB;

For:

+---+---+
| a | b |
+---+---+
| 1 | X |
| 2 | Y |
+---+---+

OUTER UNION CORR

+---+---+
| b | d |
+---+---+
| U | 1 |
+---+---+

<=>

+----+----+---+
| a  | b  | d |
+----+----+---+
|  1 | X  |   |
|  2 | Y  |   |
|    | U  | 1 |
+----+----+---+

U-SQL supports similar concept:

OUTER UNION BY NAME ON (*)

OUTER

requires the BY NAME clause and the ON list. As opposed to the other set expressions, the output schema of the OUTER UNION includes both the matching columns and the non-matching columns from both sides. This creates a situation where each row coming from one of the sides has "missing columns" that are present only on the other side. For such columns, default values are supplied for the "missing cells". The default values are null for nullable types and the .Net default value for the non-nullable types (e.g., 0 for int).

BY NAME

is required when used with OUTER. The clause indicates that the union is matching up values not based on position but by name of the columns. If the BY NAME clause is not specified, the matching is done positionally.

If the ON clause includes the “*” symbol (it may be specified as the last or the only member of the list), then extra name matches beyond those in the ON clause are allowed, and the result’s columns include all matching columns in the order they are present in the left argument.

And code:

@result =    
    SELECT * FROM @left
    OUTER UNION BY NAME ON (*) 
    SELECT * FROM @right;

EDIT:

The concept of outer union is supported by KQL:

kind:

inner - The result has the subset of columns that are common to all of the input tables.

outer - The result has all the columns that occur in any of the inputs. Cells that were not defined by an input row are set to null.

Example:

let t1 = datatable(col1:long, col2:string)  
[1, "a",  
2, "b",
3, "c"];
let t2 = datatable(col3:long)
[1,3];
t1 | union kind=outer t2;

Output:

+------+------+------+
| col1 | col2 | col3 |
+------+------+------+
|    1 | a    |      |
|    2 | b    |      |
|    3 | c    |      |
|      |      |    1 |
|      |      |    3 |
+------+------+------+

demo

Best Way to View Generated Source of Webpage?

In Firefox, just ctrl-a (select everything on the screen) then right click "View Selection Source". This captures any changes made by JavaScript to the DOM.

Java error: Implicit super constructor is undefined for default constructor

Sorry for necroposting but faced this problem just today. For everybody also facing with this problem - one of he possible reasons - you don't call super at the first line of method. Second, third and other lines fire this error. Call of super should be very first call in your method. In this case everything is well.