Programs & Examples On #Moq

Moq (pronounced "Mock-you" or just "Mock") is a mocking framework for .NET that makes heavy use of lambdas and LINQ expression trees.

Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

You'll get this error as well if you are verifying that an extension method of an interface is called.

For example if you are mocking:

var mockValidator = new Mock<IValidator<Foo>>();
mockValidator
  .Verify(validator => validator.ValidateAndThrow(foo, null));

You will get the same exception because .ValidateAndThrow() is an extension on the IValidator<T> interface.

public static void ValidateAndThrow<T>(this IValidator<T> validator, T instance, string ruleSet = null)...

Moq, SetupGet, Mocking a property

ColumnNames is a property of type List<String> so when you are setting up you need to pass a List<String> in the Returns call as an argument (or a func which return a List<String>)

But with this line you are trying to return just a string

input.SetupGet(x => x.ColumnNames).Returns(temp[0]);

which is causing the exception.

Change it to return whole list:

input.SetupGet(x => x.ColumnNames).Returns(temp);

Mocking HttpClient in unit tests

I did something very simple, as I was in a DI environment.

public class HttpHelper : IHttpHelper
{
    private ILogHelper _logHelper;

    public HttpHelper(ILogHelper logHelper)
    {
        _logHelper = logHelper;
    }

    public virtual async Task<HttpResponseMessage> GetAsync(string uri, Dictionary<string, string> headers = null)
    {
        HttpResponseMessage response;
        using (var client = new HttpClient())
        {
            if (headers != null)
            {
                foreach (var h in headers)
                {
                    client.DefaultRequestHeaders.Add(h.Key, h.Value);
                }
            }
            response = await client.GetAsync(uri);
        }

        return response;
    }

    public async Task<T> GetAsync<T>(string uri, Dictionary<string, string> headers = null)
    {
        ...

        rawResponse = await GetAsync(uri, headers);

        ...
    }

}

and the mock is:

    [TestInitialize]
    public void Initialize()
    {
       ...
        _httpHelper = new Mock<HttpHelper>(_logHelper.Object) { CallBase = true };
       ...
    }

    [TestMethod]
    public async Task SuccessStatusCode_WithAuthHeader()
    {
        ...

        _httpHelper.Setup(m => m.GetAsync(_uri, myHeaders)).Returns(
            Task<HttpResponseMessage>.Factory.StartNew(() =>
            {
                return new HttpResponseMessage(System.Net.HttpStatusCode.OK)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(_testData))
                };
            })
        );
        var result = await _httpHelper.Object.GetAsync<TestDTO>(...);

        Assert.AreEqual(...);
    }

Returning value that was passed into a method

You can use a lambda with an input parameter, like so:

.Returns((string myval) => { return myval; });

Or slightly more readable:

.Returns<string>(x => x);

Verifying a specific parameter with Moq

Had one of these as well, but the parameter of the action was an interface with no public properties. Ended up using It.Is() with a seperate method and within this method had to do some mocking of the interface

public interface IQuery
{
    IQuery SetSomeFields(string info);
}

void DoSomeQuerying(Action<IQuery> queryThing);

mockedObject.Setup(m => m.DoSomeQuerying(It.Is<Action<IQuery>>(q => MyCheckingMethod(q)));

private bool MyCheckingMethod(Action<IQuery> queryAction)
{
    var mockQuery = new Mock<IQuery>();
    mockQuery.Setup(m => m.SetSomeFields(It.Is<string>(s => s.MeetsSomeCondition())
    queryAction.Invoke(mockQuery.Object);
    mockQuery.Verify(m => m.SetSomeFields(It.Is<string>(s => s.MeetsSomeCondition(), Times.Once)
    return true
}

How can I tell Moq to return a Task?

Now you can also use Talentsoft.Moq.SetupAsync package https://github.com/TalentSoft/Moq.SetupAsync

Which on the base on the answers found here and ideas proposed to Moq but still not yet implemented here: https://github.com/moq/moq4/issues/384, greatly simplify setup of async methods

Few examples found in previous responses done with SetupAsync extension:

mock.SetupAsync(arg=>arg.DoSomethingAsync());
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Callback(() => { <my code here> });
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Throws(new InvalidOperationException());

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

Mocking Extension Methods with Moq

I found that I had to discover the inside of the extension method I was trying to mock the input for, and mock what was going on inside the extension.

I viewed using an extension as adding code directly to your method. This meant I needed to mock what happens inside the extension rather than the extension itself.

Assigning out/ref parameters in Moq

Building on Billy Jakes awnser, I made a fully dynamic mock method with an out parameter. I'm posting this here for anyone who finds it usefull.

// Define a delegate with the params of the method that returns void.
delegate void methodDelegate(int x, out string output);

// Define a variable to store the return value.
bool returnValue;

// Mock the method: 
// Do all logic in .Callback and store the return value.
// Then return the return value in the .Returns
mockHighlighter.Setup(h => h.SomeMethod(It.IsAny<int>(), out It.Ref<int>.IsAny))
  .Callback(new methodDelegate((int x, out int output) =>
  {
    // do some logic to set the output and return value.
    output = ...
    returnValue = ...
  }))
  .Returns(() => returnValue);

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

Here's how you can mock your FileConnection

Mock<IFileConnection> fileConnection = new Mock<IFileConnection>(
                                                           MockBehavior.Strict);
fileConnection.Setup(item => item.Get(It.IsAny<string>,It.IsAny<string>))
              .Throws(new IOException());

Then instantiate your Transfer class and use the mock in your method call

Transfer transfer = new Transfer();
transfer.GetFile(fileConnection.Object, someRemoteFilename, someLocalFileName);

Update:

First of all you have to mock your dependencies only, not the class you are testing(Transfer class in this case). Stating those dependencies in your constructor make it easy to see what services your class needs to work. It also makes it possible to replace them with fakes when you are writing your unit tests. At the moment it's impossible to replace those properties with fakes.

Since you are setting those properties using another dependency, I would write it like this:

public class Transfer
{
    public Transfer(IInternalConfig internalConfig)
    {
        source = internalConfig.GetFileConnection("source");
        destination = internalConfig.GetFileConnection("destination");
    }

    //you should consider making these private or protected fields
    public virtual IFileConnection source { get; set; }
    public virtual IFileConnection destination { get; set; }

    public virtual void GetFile(IFileConnection connection, 
        string remoteFilename, string localFilename)
    {
        connection.Get(remoteFilename, localFilename);
    }

    public virtual void PutFile(IFileConnection connection, 
        string localFilename, string remoteFilename)
    {
        connection.Get(remoteFilename, localFilename);
    }

    public virtual void TransferFiles(string sourceName, string destName)
    {
        var tempName = Path.GetTempFileName();
        GetFile(source, sourceName, tempName);
        PutFile(destination, tempName, destName);
    }
}

This way you can mock internalConfig and make it return IFileConnection mocks that does what you want.

How to mock static methods in c# using MOQ framework?

As mentioned in the other answers MOQ cannot mock static methods and, as a general rule, one should avoid statics where possible.

Sometimes it is not possible. One is working with legacy or 3rd party code or with even with the BCL methods that are static.

A possible solution is to wrap the static in a proxy with an interface which can be mocked

    public interface IFileProxy {
        void Delete(string path);
    }

    public class FileProxy : IFileProxy {
        public void Delete(string path) {
            System.IO.File.Delete(path);
        }
    }

    public class MyClass {

        private IFileProxy _fileProxy;

        public MyClass(IFileProxy fileProxy) {
            _fileProxy = fileProxy;
        }

        public void DoSomethingAndDeleteFile(string path) {
            // Do Something with file
            // ...
            // Delete
            System.IO.File.Delete(path);
        }

        public void DoSomethingAndDeleteFileUsingProxy(string path) {
            // Do Something with file
            // ...
            // Delete
            _fileProxy.Delete(path);

        }
    }

The downside is that the ctor can become very cluttered if there are a lot of proxies (though it could be argued that if there are a lot of proxies then the class may be trying to do too much and could be refactored)

Another possibility is to have a 'static proxy' with different implementations of the interface behind it

   public static class FileServices {

        static FileServices() {
            Reset();
        }

        internal static IFileProxy FileProxy { private get; set; }

        public static void Reset(){
           FileProxy = new FileProxy();
        }

        public static void Delete(string path) {
            FileProxy.Delete(path);
        }

    }

Our method now becomes

    public void DoSomethingAndDeleteFileUsingStaticProxy(string path) {
            // Do Something with file
            // ...
            // Delete
            FileServices.Delete(path);

    }

For testing, we can set the FileProxy property to our mock. Using this style reduces the number of interfaces to be injected but makes dependencies a bit less obvious (though no more so than the original static calls I suppose).

Change font-weight of FontAwesome icons?

Webkit browsers support the ability to add "stroke" to fonts. This bit of style makes fonts look thinner (assuming a white background):

-webkit-text-stroke: 2px white;

Example on codepen here: http://codepen.io/mackdoyle/pen/yrgEH Some people are using SVG for a cross-platform "stroke" solution: http://codepen.io/CrocoDillon/pen/dGIsK

jQuery Validation using the class instead of the name value

Another way you can do it, is using addClassRules. It's specific for classes, while the option using selector and .rules is more a generic way.

Before calling

$(form).validate()

Use like this:

jQuery.validator.addClassRules('myClassName', {
        required: true /*,
        other rules */
    });

Ref: http://docs.jquery.com/Plugins/Validation/Validator/addClassRules#namerules

I prefer this syntax for a case like this.

Gather multiple sets of columns

This could be done using reshape. It is possible with dplyr though.

  colnames(df) <- gsub("\\.(.{2})$", "_\\1", colnames(df))
  colnames(df)[2] <- "Date"
  res <- reshape(df, idvar=c("id", "Date"), varying=3:8, direction="long", sep="_")
  row.names(res) <- 1:nrow(res)
  
   head(res)
  #  id       Date time       Q3.2       Q3.3
  #1  1 2009-01-01    1  1.3709584  0.4554501
  #2  2 2009-01-02    1 -0.5646982  0.7048373
  #3  3 2009-01-03    1  0.3631284  1.0351035
  #4  4 2009-01-04    1  0.6328626 -0.6089264
  #5  5 2009-01-05    1  0.4042683  0.5049551
  #6  6 2009-01-06    1 -0.1061245 -1.7170087

Or using dplyr

  library(tidyr)
  library(dplyr)
  colnames(df) <- gsub("\\.(.{2})$", "_\\1", colnames(df))

  df %>%
     gather(loop_number, "Q3", starts_with("Q3")) %>% 
     separate(loop_number,c("L1", "L2"), sep="_") %>% 
     spread(L1, Q3) %>%
     select(-L2) %>%
     head()
  #  id       time       Q3.2       Q3.3
  #1  1 2009-01-01  1.3709584  0.4554501
  #2  1 2009-01-01  1.3048697  0.2059986
  #3  1 2009-01-01 -0.3066386  0.3219253
  #4  2 2009-01-02 -0.5646982  0.7048373
  #5  2 2009-01-02  2.2866454 -0.3610573
  #6  2 2009-01-02 -1.7813084 -0.7838389

Update

With new version of tidyr, we can use pivot_longer to reshape multiple columns. (Using the changed column names from gsub above)

library(dplyr)
library(tidyr)
df %>% 
    pivot_longer(cols = starts_with("Q3"), 
          names_to = c(".value", "Q3"), names_sep = "_") %>% 
    select(-Q3)
# A tibble: 30 x 4
#      id time         Q3.2    Q3.3
#   <int> <date>      <dbl>   <dbl>
# 1     1 2009-01-01  0.974  1.47  
# 2     1 2009-01-01 -0.849 -0.513 
# 3     1 2009-01-01  0.894  0.0442
# 4     2 2009-01-02  2.04  -0.553 
# 5     2 2009-01-02  0.694  0.0972
# 6     2 2009-01-02 -1.11   1.85  
# 7     3 2009-01-03  0.413  0.733 
# 8     3 2009-01-03 -0.896 -0.271 
#9     3 2009-01-03  0.509 -0.0512
#10     4 2009-01-04  1.81   0.668 
# … with 20 more rows

NOTE: Values are different because there was no set seed in creating the input dataset

Apache POI error loading XSSFWorkbook class

Add commons-collections4-x.x.jar file in your build path and try it again. It will work.

You can download it from https://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.0

Basic example for sharing text or image with UIActivityViewController in Swift

UIActivityViewController Example Project

Set up your storyboard with two buttons and hook them up to your view controller (see code below).

enter image description here

Add an image to your Assets.xcassets. I called mine "lion".

enter image description here

Code

import UIKit
class ViewController: UIViewController {

    // share text
    @IBAction func shareTextButton(_ sender: UIButton) {

        // text to share
        let text = "This is some text that I want to share."

        // set up activity view controller
        let textToShare = [ text ]
        let activityViewController = UIActivityViewController(activityItems: textToShare, applicationActivities: nil)
        activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash

        // exclude some activity types from the list (optional)
        activityViewController.excludedActivityTypes = [ UIActivityType.airDrop, UIActivityType.postToFacebook ]

        // present the view controller
        self.present(activityViewController, animated: true, completion: nil)

    }

    // share image
    @IBAction func shareImageButton(_ sender: UIButton) {

        // image to share
        let image = UIImage(named: "Image")

        // set up activity view controller
        let imageToShare = [ image! ]
        let activityViewController = UIActivityViewController(activityItems: imageToShare, applicationActivities: nil)
        activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash

        // exclude some activity types from the list (optional)
        activityViewController.excludedActivityTypes = [ UIActivityType.airDrop, UIActivityType.postToFacebook ]

        // present the view controller
        self.present(activityViewController, animated: true, completion: nil)
    }

}

Result

Clicking "Share some text" gives result on the left and clicking "Share an image" gives the result on the right.

enter image description here

Notes

  • I retested this with iOS 11 and Swift 4. I had to run it a couple times in the simulator before it worked because it was timing out. This may be because my computer is slow.
  • If you wish to hide some of these choices, you can do that with excludedActivityTypes as shown in the code above.
  • Not including the popoverPresentationController?.sourceView line will cause your app to crash when run on an iPad.
  • This does not allow you to share text or images to other apps. You probably want UIDocumentInteractionController for that.

See also

TypeScript typed array usage

You have an error in your syntax here:

this._possessions = new Thing[100]();

This doesn't create an "array of things". To create an array of things, you can simply use the array literal expression:

this._possessions = [];

Of the array constructor if you want to set the length:

this._possessions = new Array(100);

I have created a brief working example you can try in the playground.

module Entities {  

    class Thing {

    }        

    export class Person {
        private _name: string;
        private _possessions: Thing[];
        private _mostPrecious: Thing;

        constructor (name: string) {
            this._name = name;
            this._possessions = [];
            this._possessions.push(new Thing())
            this._possessions[100] = new Thing();
        }
    }
}

A generic list of anonymous class

I guess

List<T> CreateEmptyGenericList<T>(T example) {
    return new List<T>();
}

void something() {
    var o = new { Id = 1, Name = "foo" };
    var emptyListOfAnonymousType = CreateEmptyGenericList(o);
}

will work.

You might also consider writing it like this:

void something() {
    var String = string.Emtpy;
    var Integer = int.MinValue;
    var emptyListOfAnonymousType = CreateEmptyGenericList(new { Id = Integer, Name = String });
}

Check if string contains only whitespace

You want to use the isspace() method

str.isspace()

Return true if there are only whitespace characters in the string and there is at least one character, false otherwise.

That's defined on every string object. Here it is an usage example for your specific use case:

if aStr and (not aStr.isspace()):
    print aStr

python requests file upload

(2018) the new python requests library has simplified this process, we can use the 'files' variable to signal that we want to upload a multipart-encoded file

url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}

r = requests.post(url, files=files)
r.text

How do I run Redis on Windows?

I am using Memurai which is Redis-compatible cache and datastore for Windows. It is also recommended by Microsoft open tech as it written on their former project here.

This project is no longer being actively maintained. If you are looking for a Windows version of Redis, you may want to check out Memurai. Please note that Microsoft is not officially endorsing this product in any way.

How to stretch a fixed number of horizontal navigation items evenly and fully across a specified container

<!DOCTYPE html>
<html lang="en">
<head>
<style>
#container { width: 100%; border: 1px solid black; display: block; text-align: justify; }
object, span { display: inline-block; }
span { width: 100%; }
</style>
</head>

  <div id="container">
    <object>
      <div>
      alpha
      </div>
    </object>
    <object>
      <div>
      beta
      </div>
    </object>
    <object>
      <div>
      charlie
      </div>
    </object>
    <object>
      <div>
      delta
      </div>
    </object>
    <object>
      <div>
      epsilon
      </div>
    </object>
    <object>
      <div>
      foxtrot
      </div>
    </object>
    <span></span>
  </div>
</html>

Convert RGB to Black & White in OpenCV

A simple way of "binarize" an image is to compare to a threshold: For example you can compare all elements in a matrix against a value with opencv in c++

cv::Mat img = cv::imread("image.jpg", CV_LOAD_IMAGE_GRAYSCALE); 
cv::Mat bw = img > 128;

In this way, all pixels in the matrix greater than 128 now are white, and these less than 128 or equals will be black

Optionally, and for me gave good results is to apply blur

cv::blur( bw, bw, cv::Size(3,3) );

Later you can save it as said before with:

cv::imwrite("image_bw.jpg", bw);

The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM'

I had the same problem, to solve it set specific user from domain in iis -> action sidebar->Basic Settings -> Connect as... -> specific user

enter image description here

How to get the string size in bytes?

If you use sizeof()then a char *str and char str[] will return different answers. char str[] will return the length of the string(including the string terminator) while char *str will return the size of the pointer(differs as per compiler).

jQuery - selecting elements from inside a element

Why not just use:

$("#foo span")

or

$("#foo > span")

$('span', $('#foo')); works fine on my machine ;)

How to convert int[] to Integer[] in Java?

This worked like a charm!

int[] mInt = new int[10];
Integer[] mInteger = new Integer[mInt.length];

List<Integer> wrapper = new AbstractList<Integer>() {
    @Override
    public int size() {
        return mInt.length;
    }

    @Override
    public Integer get(int i) {
        return mInt[i];
    }
};

wrapper.toArray(mInteger);

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

I was running into a similar error in pywikipediabot. The .decode method is a step in the right direction but for me it didn't work without adding 'ignore':

ignore_encoding = lambda s: s.decode('utf8', 'ignore')

Ignoring encoding errors can lead to data loss or produce incorrect output. But if you just want to get it done and the details aren't very important this can be a good way to move faster.

Sort objects in ArrayList by date?

Future viewers, I think this is the simplest solution, if your model contains a string type date ("2020-01-01 10:00:00" for example), then just write the following line to sort the data by date descending from newest to the oldest:

Collections.sort(messages, (o1, o2) -> o2.getMessageDate().compareTo(o1.getMessageDate()));

What is HEAD in Git?

HEAD actually is just a file for storing current branch info

and if you use HEAD in your git commands you are pointing to your current branch

you can see the data of this file by cat .git/HEAD

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

if you want to upgrade only a single column of a table row then you can use as following:

$this->db->set('column_header', $value); //value that used to update column  
$this->db->where('column_id', $column_id_value); //which row want to upgrade  
$this->db->update('table_name');  //table name

What size do you use for varchar(MAX) in your parameter declaration?

The maximum SqlDbType.VarChar size is 2147483647.

If you would use a generic oledb connection instead of sql, I found here there is also a LongVarChar datatype. Its max size is 2147483647.

cmd.Parameters.Add("@blah", OleDbType.LongVarChar, -1).Value = "very big string";

Work with a time span in Javascript

/**
 * ??????????????,???????? 
 * English: Calculating the difference between the given time and the current time and then showing the results.
 */
function date2Text(date) {
    var milliseconds = new Date() - date;
    var timespan = new TimeSpan(milliseconds);
    if (milliseconds < 0) {
        return timespan.toString() + "??";
    }else{
        return timespan.toString() + "?";
    }
}

/**
 * ???????????
 * English: Using a function to calculate the time interval
 * @param milliseconds ???
 */
var TimeSpan = function (milliseconds) {
    milliseconds = Math.abs(milliseconds);
    var days = Math.floor(milliseconds / (1000 * 60 * 60 * 24));
    milliseconds -= days * (1000 * 60 * 60 * 24);

    var hours = Math.floor(milliseconds / (1000 * 60 * 60));
    milliseconds -= hours * (1000 * 60 * 60);

    var mins = Math.floor(milliseconds / (1000 * 60));
    milliseconds -= mins * (1000 * 60);

    var seconds = Math.floor(milliseconds / (1000));
    milliseconds -= seconds * (1000);
    return {
        getDays: function () {
            return days;
        },
        getHours: function () {
            return hours;
        },
        getMinuts: function () {
            return mins;
        },
        getSeconds: function () {
            return seconds;
        },
        toString: function () {
            var str = "";
            if (days > 0 || str.length > 0) {
                str += days + "?";
            }
            if (hours > 0 || str.length > 0) {
                str += hours + "??";
            }
            if (mins > 0 || str.length > 0) {
                str += mins + "??";
            }
            if (days == 0 && (seconds > 0 || str.length > 0)) {
                str += seconds + "?";
            }
            return str;
        }
    }
}

android get all contacts

public class MyActivity extends Activity 
                        implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final int CONTACTS_LOADER_ID = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Prepare the loader.  Either re-connect with an existing one,
        // or start a new one.
        getLoaderManager().initLoader(CONTACTS_LOADER_ID,
                                      null,
                                      this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        // This is called when a new Loader needs to be created.

        if (id == CONTACTS_LOADER_ID) {
            return contactsLoader();
        }
        return null;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        //The framework will take care of closing the
        // old cursor once we return.
        List<String> contacts = contactsFromCursor(cursor);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        // This is called when the last Cursor provided to onLoadFinished()
        // above is about to be closed.  We need to make sure we are no
        // longer using it.
    }

    private  Loader<Cursor> contactsLoader() {
        Uri contactsUri = ContactsContract.Contacts.CONTENT_URI; // The content URI of the phone contacts

        String[] projection = {                                  // The columns to return for each row
                ContactsContract.Contacts.DISPLAY_NAME
        } ;

        String selection = null;                                 //Selection criteria
        String[] selectionArgs = {};                             //Selection criteria
        String sortOrder = null;                                 //The sort order for the returned rows

        return new CursorLoader(
                getApplicationContext(),
                contactsUri,
                projection,
                selection,
                selectionArgs,
                sortOrder);
    }

    private List<String> contactsFromCursor(Cursor cursor) {
        List<String> contacts = new ArrayList<String>();

        if (cursor.getCount() > 0) {
            cursor.moveToFirst();

            do {
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                contacts.add(name);
            } while (cursor.moveToNext());
        }

        return contacts;
    }

}

and do not forget

<uses-permission android:name="android.permission.READ_CONTACTS" />

Principal Component Analysis (PCA) in Python

In addition to all the other answers, here is some code to plot the biplot using sklearn and matplotlib.

import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.decomposition import PCA
import pandas as pd
from sklearn.preprocessing import StandardScaler

iris = datasets.load_iris()
X = iris.data
y = iris.target
#In general a good idea is to scale the data
scaler = StandardScaler()
scaler.fit(X)
X=scaler.transform(X)    

pca = PCA()
x_new = pca.fit_transform(X)

def myplot(score,coeff,labels=None):
    xs = score[:,0]
    ys = score[:,1]
    n = coeff.shape[0]
    scalex = 1.0/(xs.max() - xs.min())
    scaley = 1.0/(ys.max() - ys.min())
    plt.scatter(xs * scalex,ys * scaley, c = y)
    for i in range(n):
        plt.arrow(0, 0, coeff[i,0], coeff[i,1],color = 'r',alpha = 0.5)
        if labels is None:
            plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, "Var"+str(i+1), color = 'g', ha = 'center', va = 'center')
        else:
            plt.text(coeff[i,0]* 1.15, coeff[i,1] * 1.15, labels[i], color = 'g', ha = 'center', va = 'center')
plt.xlim(-1,1)
plt.ylim(-1,1)
plt.xlabel("PC{}".format(1))
plt.ylabel("PC{}".format(2))
plt.grid()

#Call the function. Use only the 2 PCs.
myplot(x_new[:,0:2],np.transpose(pca.components_[0:2, :]))
plt.show()

enter image description here

fatal: could not read Username for 'https://github.com': No such file or directory

I found my answer here:

edit ~/.gitconfig and add the following:

[url "[email protected]:"]
 insteadOf = https://github.com/

Although it solves a different problem, the error code is the same...

Is this very likely to create a memory leak in Tomcat?

This problem appears when we are using any third party solution, without using the handlers for the cleanup activitiy. For me this was happening for EhCache. We were using EhCache in our project for caching. And often we used to see following error in the logs

 SEVERE: The web application [/products] appears to have started a thread named [products_default_cache_configuration] but has failed to stop it. This is very likely to create a memory leak.
Aug 07, 2017 11:08:36 AM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
SEVERE: The web application [/products] appears to have started a thread named [Statistics Thread-products_default_cache_configuration-1] but has failed to stop it. This is very likely to create a memory leak.

And we often noticed tomcat failing for OutOfMemory error during development where we used to do backend changes and deploy the application multiple times for reflecting our changes.

This is the fix we did

<listener>
  <listener-class>
     net.sf.ehcache.constructs.web.ShutdownListener
  </listener-class>
</listener>

So point I am trying to make is check the documentation of the third party libraries which you are using. They should be providing some mechanisms to clean up the threads during shutdown. Which you need to use in your application. No need to re-invent the wheel unless its not provided by them. The worst case is to provide your own implementation.

Reference for EHCache Shutdown http://www.ehcache.org/documentation/2.8/operations/shutdown.html

Export data from R to Excel

I have been trying out the different packages including the function:

install.packages ("prettyR") 

library (prettyR)

delimit.table (Corrvar,"Name the csv.csv") ## Corrvar is a name of an object from an output I had on scaled variables to run a regression.

However I tried this same code for an output from another analysis (occupancy models model selection output) and it did not work. And after many attempts and exploration I:

  • copied the output from R (Ctrl+c)
  • in Excel sheet I pasted it (Ctrl+V)
  • Select the first column where the data is
  • In the "Data" vignette, click on "Text to column"

  • Select Delimited option, click next

  • Tick space box in "Separator", click next

  • Click Finalize (End)

Your output now should be in a form you can manipulate easy in excel. So perhaps not the fanciest option but it does the trick if you just want to explore your data in another way.

PS. If the labels in excel are not the exact one it is because Im translating the lables from my spanish excel.

How to compare dates in Java?

Update for Java 8 and later

These methods exists in LocalDate, LocalTime, and LocalDateTime classes.

Those classes are built into Java 8 and later. Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

How to apply two CSS classes to a single element

Separate 'em with a space.

<div class="c1 c2"></div>

POST JSON to API using Rails and HTTParty

I solved this by adding .to_json and some heading information

@result = HTTParty.post(@urlstring_to_post.to_str, 
    :body => { :subject => 'This is the screen name', 
               :issue_type => 'Application Problem', 
               :status => 'Open', 
               :priority => 'Normal', 
               :description => 'This is the description for the problem'
             }.to_json,
    :headers => { 'Content-Type' => 'application/json' } )

Finding height in Binary Search Tree

Here is a solution in C#

    private static int heightOfTree(Node root)
    {
        if (root == null)
        {
            return 0;
        }

        int left = 1 + heightOfTree(root.left);
        int right = 1 + heightOfTree(root.right);

        return Math.Max(left, right);
    }

How to check if a variable is empty in python?

See also this previous answer which recommends the not keyword

How to check if a list is empty in Python?

It generalizes to more than just lists:

>>> a = ""
>>> not a
True

>>> a = []
>>> not a
True

>>> a = 0
>>> not a
True

>>> a = 0.0
>>> not a
True

>>> a = numpy.array([])
>>> not a
True

Notably, it will not work for "0" as a string because the string does in fact contain something - a character containing "0". For that you have to convert it to an int:

>>> a = "0"
>>> not a
False

>>> a = '0'
>>> not int(a)
True

How to compile C programming in Windows 7?

You can get MinGW (as others have suggested) but I would recommend getting a simple IDE (not VS Express). You can try Dev C++ http://www.bloodshed.net/devcpp.html Its a simple IDE for C/C++ and uses MinGW internally. In this you can write and compile single C files without creating a full-blown "project".

Connect to Amazon EC2 file directory using Filezilla and SFTP

Just one minor note to the well explained accepted answer of Yasitha Chinthaka:

Note: FileZilla automatically figures out which key to use. You do not need to specify the key after importing it as described above.

In my case I already had other 5 ppks from other instances that I was using in the past (with the ppk of the new instance being at the bottom of that list). I added the new ppk of my new instance, and it wouldn't let me connect to it. The error message: too many tries / attempts.

After I deleted the unused ppks, I was finally able to login to the instance.

So no, Filezilla is not that smart ;-)

Pandas every nth row

There is an even simpler solution to the accepted answer that involves directly invoking df.__getitem__.

df = pd.DataFrame('x', index=range(5), columns=list('abc'))
df

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

For example, to get every 2 rows, you can do

df[::2]

   a  b  c
0  x  x  x
2  x  x  x
4  x  x  x

There's also GroupBy.first/GroupBy.head, you group on the index:

df.index // 2
# Int64Index([0, 0, 1, 1, 2], dtype='int64')

df.groupby(df.index // 2).first()
# Alternatively,
# df.groupby(df.index // 2).head(1)

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x

The index is floor-divved by the stride (2, in this case). If the index is non-numeric, instead do

# df.groupby(np.arange(len(df)) // 2).first()
df.groupby(pd.RangeIndex(len(df)) // 2).first()

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x

node.js Error: connect ECONNREFUSED; response from server

use a proxy property in your code it should work just fine

const https = require('https');
const request = require('request');

request({
    'url':'https://teamtreehouse.com/chalkers.json',
    'proxy':'http://xx.xxx.xxx.xx'
    },
    function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var data = body;
            console.log(data);
        }
    }
);

How do I exit a foreach loop in C#?

Just use the statement:

break;

Angular ng-repeat add bootstrap row every 3 or 4 cols

Born Solutions its best one, just need a bit tweek to feet the needs, i had different responsive solutions and changed a bit

<div ng-repeat="post in posts">
    <div class="vechicle-single col-lg-4 col-md-6 col-sm-12 col-xs-12">
    </div>
    <div class="clearfix visible-lg" ng-if="($index + 1) % 3 == 0"></div>
    <div class="clearfix visible-md" ng-if="($index + 1) % 2 == 0"></div>
    <div class="clearfix visible-sm" ng-if="($index + 1) % 1 == 0"></div>
    <div class="clearfix visible-xs" ng-if="($index + 1) % 1 == 0"></div>
</div>

How do I add a delay in a JavaScript loop?

_x000D_
_x000D_
function waitforme(ms)  {

return new Promise( resolve => {

    setTimeout(()=> {resolve('')} ,ms );


})


}



async function printy()  {




for (let i= 0; i < 10 ; ++i)    {


    await waitforme(1000);
    //wait for 500 milisecond

    console.log(i);


}


console.log("I Ran after the loop finished :)");
}


printy();
_x000D_
_x000D_
_x000D_

How to make a DIV always float on the screen in top right corner?

Use position: fixed, and anchor it to the top and right sides of the page:

#fixed-div {
    position: fixed;
    top: 1em;
    right: 1em;
}

IE6 does not support position: fixed, however. If you need this functionality in IE6, this purely-CSS solution seems to do the trick. You'll need a wrapper <div> to contain some of the styles for it to work, as seen in the stylesheet.

How to redirect to a 404 in Rails?

I wanted to throw a 'normal' 404 for any logged in user that isn't an admin, so I ended up writing something like this in Rails 5:

class AdminController < ApplicationController
  before_action :blackhole_admin

  private

  def blackhole_admin
    return if current_user.admin?

    raise ActionController::RoutingError, 'Not Found'
  rescue ActionController::RoutingError
    render file: "#{Rails.root}/public/404", layout: false, status: :not_found
  end
end

Move seaborn plot legend to a different position?

If you wish to customize your legend, just use the add_legend method. It takes the same parameters as matplotlib plt.legend.

import seaborn as sns
sns.set(style="whitegrid")

titanic = sns.load_dataset("titanic")

g = sns.factorplot("class", "survived", "sex",
                    data=titanic, kind="bar",
                    size=6, palette="muted",
                   legend_out=False)
g.despine(left=True)
g.set_ylabels("survival probability")
g.add_legend(bbox_to_anchor=(1.05, 0), loc=2, borderaxespad=0.)

Can you Run Xcode in Linux?

OSX is based on BSD, not Linux. You cannot run Xcode on a Linux machine.

How do I loop through children objects in javascript?

I’m surprised no-one answered with this code:

for(var child=elt.firstChild;
    child;
    child=child.nextSibling){
  do_thing(child);
}

Or, if you only want children which are elements, this code:

for(var child=elt.firstElementChild;
    child;
    child=child.nextElementSibling){
  do_thing(child);
}

Artisan migrate could not find driver

Go to .env file and change the following
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=shreemad
DB_USERNAME=root
DB_PASSWORD=

Change the DB_PASSWORD field to

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=shreemad
DB_USERNAME=root
DB_PASSWORD=" "

In my case it works

NOTE: If your password in mysql is null

Access-Control-Allow-Origin Multiple Origin Domains?

Here's an expanded option for apache that includes some of the latest and planned font definitions:

<FilesMatch "\.(ttf|otf|eot|woff|woff2|sfnt|svg)$">
    <IfModule mod_headers.c>
        SetEnvIf Origin "^http(s)?://(.+\.)?(domainname1|domainname2|domainname3)\.(?:com|net|org)$" AccessControlAllowOrigin=$0$1$2
        Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
        Header set Access-Control-Allow-Credentials true
    </IfModule>
</FilesMatch>

Ruby combining an array into one string

Use the Array#join method (the argument to join is what to insert between the strings - in this case a space):

@arr.join(" ")

How to disable text selection highlighting

UPDATE January, 2017:

According to Can I use, the user-select is currently supported in all browsers except Internet Explorer 9 and its earlier versions (but sadly still needs a vendor prefix).


These are all of the available correct CSS variations:

_x000D_
_x000D_
.noselect {
  -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Old versions of Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome, Edge, Opera and Firefox */
}
_x000D_
<p>
  Selectable text.
</p>
<p class="noselect">
  Unselectable text.
</p>
_x000D_
_x000D_
_x000D_


Note that user-select is in standardization process (currently in a W3C working draft). It is not guaranteed to work everywhere and there might be differences in implementation among browsers. Also browsers can drop support for it in the future.


More information can be found in Mozilla Developer Network documentation.

Can HTML checkboxes be set to readonly?

In old HTML you can use

<input type="checkbox" disabled checked>text

but actually is not recommended to use just simply old HTML, now you should use XHTML.

In well formed XHTML you have to use

<input type="checkbox" disabled="disabled" checked="checked" />text <!-- if yu have a checked box-->
<input type="checkbox" disabled="disabled" />text <!-- if you have a unchecked box -->

well formed XHTML requires a XML form, thats the reason to use disabled="disabled" instead of simply use disabled.

Getting multiple keys of specified value of a generic Dictionary?

As a twist of the accepted answer (https://stackoverflow.com/a/255638/986160) assuming that the keys will be associated with signle values in the dictionary. Similar to (https://stackoverflow.com/a/255630/986160) but a bit more elegant. The novelty is in that the consuming class can be used as an enumeration alternative (but for strings too) and that the dictionary implements IEnumerable.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace MyApp.Dictionaries
{

    class BiDictionary<TFirst, TSecond> : IEnumerable
    {
        IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();
        IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();

        public void Add(TFirst first, TSecond second)
        {
            firstToSecond.Add(first, second);
            secondToFirst.Add(second, first);
        }

        public TSecond this[TFirst first]
        {
            get { return GetByFirst(first); }
        }

        public TFirst this[TSecond second]
        {
            get { return GetBySecond(second); }
        }

        public TSecond GetByFirst(TFirst first)
        {
            return firstToSecond[first];
        }

        public TFirst GetBySecond(TSecond second)
        {
            return secondToFirst[second];
        }

        public IEnumerator GetEnumerator()
        {
            return GetFirstEnumerator();
        }

        public IEnumerator GetFirstEnumerator()
        {
            return firstToSecond.GetEnumerator();
        }

        public IEnumerator GetSecondEnumerator()
        {
            return secondToFirst.GetEnumerator();
        }
    }
}

And as a consuming class you could have

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MyApp.Dictionaries
{
    class Greek
    {

        public static readonly string Alpha = "Alpha";
        public static readonly string Beta = "Beta";
        public static readonly string Gamma = "Gamma";
        public static readonly string Delta = "Delta";


        private static readonly BiDictionary<int, string> Dictionary = new BiDictionary<int, string>();


        static Greek() {
            Dictionary.Add(1, Alpha);
            Dictionary.Add(2, Beta);
            Dictionary.Add(3, Gamma);
            Dictionary.Add(4, Delta);
        }

        public static string getById(int id){
            return Dictionary.GetByFirst(id);
        }

        public static int getByValue(string value)
        {
            return Dictionary.GetBySecond(value);
        }

    }
}

MVC4 Passing model from view to controller

I hope this complete example will help you.

This is the TaxiInfo class which holds information about a taxi ride:

namespace Taxi.Models
{
    public class TaxiInfo
    {
        public String Driver { get; set; }
        public Double Fare { get; set; }
        public Double Distance { get; set; }
        public String StartLocation { get; set; }
        public String EndLocation { get; set; }
    }
}

We also have a convenience model which holds a List of TaxiInfo(s):

namespace Taxi.Models
{
    public class TaxiInfoSet
    {
        public List<TaxiInfo> TaxiInfoList { get; set; }

        public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
        {
            TaxiInfoList = new List<TaxiInfo>();

            foreach(var TaxiInfo in TaxiInfos)
            {
                TaxiInfoList.Add(TaxiInfo);
            }
        }
    }
}

Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:

public ActionResult Index()
{
    var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
    var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };

    return View(new TaxiInfoSet(taxi1,taxi2));
}

The code for the view is as follows:

@model Taxi.Models.TaxiInfoSet
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@foreach(var TaxiInfo in Model.TaxiInfoList){
    <form>
        <h1>Cost: [email protected]</h1>
        <h2>Distance: @(TaxiInfo.Distance) km</h2>
        <p>
            Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
        </p>
        @Html.ActionLink("Home","Booking",TaxiInfo)
    </form>
}

The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:

    public ActionResult Booking(TaxiInfo Taxi)
    {
        return View(Taxi);
    }

This returns a the following view:

@model Taxi.Models.TaxiInfo

@{
    ViewBag.Title = "Booking";
}

<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>

A visual tour:

The Index view

The Booking view

Change placeholder text

For JavaScript use:

document.getElementsByClassName('select-holder')[0].placeholder = "This is my new text";

For jQuery use:

$('.select-holder')[0].placeholder = "This is my new text";

Add custom buttons on Slick Carousel

If you are using sass you can simply set below mentioned variables to use icons provided by other fonts,

$slick-font-family:FontAwesome;
$slick-prev-character: "\f053";
$slick-next-character: "\f054";

These will change the font family used by slick's theme css and also the unicode for prev and next button. This example will use FontAwesome's chevron-left and chevron-right icons.

Other sass variables which can be configured are given in Slick Github page

Pure CSS to make font-size responsive based on dynamic amount of characters

The only way would probably be to set different widths for different screen sizes, but this approach is pretty inacurate and you should use a js solution.

h1 {
    font-size: 20px;
}

@media all and (max-device-width: 720px){
    h1 {
        font-size: 18px;
    }
}

@media all and (max-device-width: 640px){
    h1 {
        font-size: 16px;
    }
}

@media all and (max-device-width: 320px){
    h1 {
        font-size: 12px;
    }
}

Specify system property to Maven project

properties-maven-plugin plugin may help:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>properties-maven-plugin</artifactId>
    <version>1.0.0</version>
    <executions>
        <execution>
            <goals>
                <goal>set-system-properties</goal>
            </goals>
            <configuration>
                <properties>
                    <property>
                        <name>my.property.name</name>
                        <value>my.property.value</value>
                    </property>
                </properties>
            </configuration>
        </execution>
    </executions>
</plugin>

SqlException: DB2 SQL error: SQLCODE: -302, SQLSTATE: 22001, SQLERRMC: null

As a general point when using a search engine to search for SQL codes make sure you put the sqlcode e.g. -302 in quote marks - like "-302" otherwise the search engine will exclude all search results including the text 302, since the - sign is used to exclude results.

How to make nginx to listen to server_name:port

The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

netstat tells you that nginx listens on 0.0.0.0:80 which means that it will accept connections from any IP.

If you want to change the IP nginx binds on, you have to change the listendocs rule.
So, if you want to set nginx to bind to localhost, you'd change that to:

listen 127.0.0.1:80;

In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

Get list of a class' instance methods

TestClass.instance_methods

or without all the inherited methods

TestClass.instance_methods - Object.methods

(Was 'TestClass.methods - Object.methods')

How to pretty print XML from the command line?

This simple(st) solution doesn't provide indentation, but it is nevertheless much easier on the human eye. Also it allows the xml to be handled more easily by simple tools like grep, head, awk, etc.

Use sed to replace '<' with itself preceeded with a newline.

And as mentioned by Gilles, it's probably not a good idea to use this in production.

# check you are getting more than one line out
sed 's/</\n</g' sample.xml | wc -l

# check the output looks generally ok
sed 's/</\n</g' sample.xml | head

# capture the pretty xml in a different file
sed 's/</\n</g' sample.xml > prettySample.xml

The term 'ng' is not recognized as the name of a cmdlet

Installing angular cli globally solved my problem.

npm install -g @angular/cli

Return number of rows affected by UPDATE statements

You might need to collect the stats as you go, but @@ROWCOUNT captures this:

declare @Fish table (
Name varchar(32)
)

insert into @Fish values ('Cod')
insert into @Fish values ('Salmon')
insert into @Fish values ('Butterfish')
update @Fish set Name = 'LurpackFish' where Name = 'Butterfish'
select @@ROWCOUNT  --gives 1

update @Fish set Name = 'Dinner'
select @@ROWCOUNT -- gives 3

How do you decrease navbar height in Bootstrap 3?

If you have only one nav and you want to change it, you should change your variables.less: @navbar-height (somewhere near line 265, I can't recall how many lines I added to mine).

This is referenced by the mixin .navbar-vertical-align, which is used for example to position the "toggle" element, anything with .navbar-form, .navbar-btn, and .navbar-text.

If you have two navbars and want them to be different heights, Minder Saini's answer may work well enough, when qualified further by an , e.g., #topnav.navbar but should be tested across multiple device widths.

How to install package from github repo in Yarn

This is described here: https://yarnpkg.com/en/docs/cli/add#toc-adding-dependencies

For example:

yarn add https://github.com/novnc/noVNC.git#0613d18

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

This error is usually observed when your machine is low on disk space. Steps to be followed to avoid this error message

  1. Resetting the read-only index block on the index:

    $ curl -X PUT -H "Content-Type: application/json" http://127.0.0.1:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'
    
    Response
    ${"acknowledged":true}
    
  2. Updating the low watermark to at least 50 gigabytes free, a high watermark of at least 20 gigabytes free, and a flood stage watermark of 10 gigabytes free, and updating the information about the cluster every minute

     Request
     $curl -X PUT "http://127.0.0.1:9200/_cluster/settings?pretty" -H 'Content-Type: application/json' -d' { "transient": { "cluster.routing.allocation.disk.watermark.low": "50gb", "cluster.routing.allocation.disk.watermark.high": "20gb", "cluster.routing.allocation.disk.watermark.flood_stage": "10gb", "cluster.info.update.interval": "1m"}}'
    
      Response
      ${
       "acknowledged" : true,
       "persistent" : { },
       "transient" : {
       "cluster" : {
       "routing" : {
       "allocation" : {
       "disk" : {
         "watermark" : {
           "low" : "50gb",
           "flood_stage" : "10gb",
           "high" : "20gb"
         }
       }
     }
    }, 
    "info" : {"update" : {"interval" : "1m"}}}}}
    

After running these two commands, you must run the first command again so that the index does not go again into read-only mode

AttributeError: Module Pip has no attribute 'main'

It appears that pip did a refactor and moved main to internal. There is a comprehensive discussion about it here: https://github.com/pypa/pip/issues/5240

A workaround for me was to change

import pip
pip.main(...)

to

from pip._internal import main
main(...)

I recommend reading through the discussion, I'm not sure this is the best approach, but it worked for my purposes.

C# Create New T()

Another way is to use reflection:

protected T GetObject<T>(Type[] signature, object[] args)
{
    return (T)typeof(T).GetConstructor(signature).Invoke(args);
}

How to replace url parameter with javascript/jquery?

How about something like this:

<script>
function changeQueryVariable(keyString, replaceString) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    var replaced = false;
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == keyString) {
            vars[i] = pair[0] + "="+ replaceString;
            replaced = true;
        }
    }
    if (!replaced) vars.push(keyString + "=" + replaceString);
    return vars.join("&");
}
</script>

Remove all child elements of a DOM node in JavaScript

i saw people doing:

while (el.firstNode) {
    el.removeChild(el.firstNode);
}

then someone said using el.lastNode is faster

however I would think that this is the fastest:

var children = el.childNodes;
for (var i=children.length - 1; i>-1; i--) {
    el.removeNode(children[i]);
}

what do you think?

ps: this topic was a life saver for me. my firefox addon got rejected cuz i used innerHTML. Its been a habit for a long time. then i foudn this. and i actually noticed a speed difference. on load the innerhtml took awhile to update, however going by addElement its instant!

How do I escape a single quote ( ' ) in JavaScript?

You should always consider what the browser will see by the end. In this case, it will see this:

<img src='something' onmouseover='change(' ex1')' />

In other words, the "onmouseover" attribute is just change(, and there's another "attribute" called ex1')' with no value.

The truth is, HTML does not use \ for an escape character. But it does recognise &quot; and &apos; as escaped quote and apostrophe, respectively.

Armed with this knowledge, use this:

document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(&quot;ex1&quot;)' />";

... That being said, you could just use JavaScript quotes:

document.getElementById("something").innerHTML = "<img src='something' onmouseover='change(\"ex1\")' />";

Get GPS location via a service in Android

Here is my solution

Step1 Register Serice in manifest

<receiver
    android:name=".MySMSBroadcastReceiver"
    android:exported="true">
    <intent-filter>
        <action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED" />
    </intent-filter>
</receiver>

Step2 Code Of Service

public class FusedLocationService extends Service {

    private String mLastUpdateTime = null;

    // bunch of location related apis
    private FusedLocationProviderClient mFusedLocationClient;
    private SettingsClient mSettingsClient;
    private LocationRequest mLocationRequest;
    private LocationSettingsRequest mLocationSettingsRequest;
    private LocationCallback mLocationCallback;
    private Location lastLocation;

    // location updates interval - 10sec
    private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 5000;

    // fastest updates interval - 5 sec
    // location updates will be received if another app is requesting the locations
    // than your app can handle
    private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 500;
    private DatabaseReference locationRef;
    private int notificationBuilder = 0;
    private boolean isInitRef;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.log("LOCATION GET DURATION", "start in service");
        init();
        return START_STICKY;
    }

    /**
     * Initilize Location Apis
     * Create Builder if Share location true
     */
    private void init() {
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        mSettingsClient = LocationServices.getSettingsClient(this);
        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                receiveLocation(locationResult);
            }
        };

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);
        mLocationSettingsRequest = builder.build();
        startLocationUpdates();
    }

    /**
     * Request Location Update
     */
    @SuppressLint("MissingPermission")
    private void startLocationUpdates() {
        mSettingsClient
                .checkLocationSettings(mLocationSettingsRequest)
                .addOnSuccessListener(locationSettingsResponse -> {
                    Log.log(TAG, "All location settings are satisfied. No MissingPermission");

                    //noinspection MissingPermission
                    mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
                })
                .addOnFailureListener(e -> {
                    int statusCode = ((ApiException) e).getStatusCode();
                    switch (statusCode) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            Log.loge("Location settings are not satisfied. Attempting to upgrade " + "location settings ");
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            Log.loge("Location settings are inadequate, and cannot be " + "fixed here. Fix in Settings.");
                    }
                });
    }

    /**
     * onLocationResult
     * on Receive Location  share to other activity and save if save true
     *
     * @param locationResult
     */
    private void receiveLocation(LocationResult locationResult) {
        lastLocation = locationResult.getLastLocation();

        LocationInstance.getInstance().changeState(lastLocation);

        saveLocation();
    }

    private void saveLocation() {
        String saveLocation = getsaveLocationStatus(this);

        if (saveLocation.equalsIgnoreCase("true") && notificationBuilder == 0) {
            notificationBuilder();
            notificationBuilder = 1;
        } else if (saveLocation.equalsIgnoreCase("false") && notificationBuilder == 1) {
            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancel(1);
            notificationBuilder = 0;
        }

        Log.logd("receiveLocation : Share :- " + saveLocation + ", [Lat " + lastLocation.getLatitude() + ", Lng" + lastLocation.getLongitude() + "], Time :- " + mLastUpdateTime);

        if (saveLocation.equalsIgnoreCase("true") || getPreviousMin() < getCurrentMin()) {
            setLatLng(this, lastLocation);

            mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());

            if (isOnline(this) && !getUserId(this).equalsIgnoreCase("")) {
                if (!isInitRef) {
                    locationRef = getFirebaseInstance().child(getUserId(this)).child("location");
                    isInitRef = true;
                }
                if (isInitRef) {
                    locationRef.setValue(new LocationModel(lastLocation.getLatitude(), lastLocation.getLongitude(), mLastUpdateTime));
                }
            }
        }
    }

    private int getPreviousMin() {
        int previous_min = 0;
        if (mLastUpdateTime != null) {
            String[] pretime = mLastUpdateTime.split(":");
            previous_min = Integer.parseInt(pretime[1].trim()) + 1;

            if (previous_min > 59) {
                previous_min = 0;
            }
        }
        return previous_min;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopLocationUpdates();
    }

    /**
     * Remove Location Update
     */
    public void stopLocationUpdates() {
        mFusedLocationClient
                .removeLocationUpdates(mLocationCallback)
                .addOnCompleteListener(task -> Log.logd("stopLocationUpdates : "));
    }

    private void notificationBuilder() {
        if (Build.VERSION.SDK_INT >= 26) {
            String CHANNEL_ID = "my_channel_01";
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);

            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);

            Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle("")
                    .setContentText("").build();

            startForeground(1, notification);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

Step 3

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

Step 4

implementation 'com.google.android.gms:play-services-location:16.0.0'

Getting the parameters of a running JVM

I am adding this new answer because as per JDK8 documentation jcmd is suggested approach now.

It is suggested to use the latest utility, jcmd instead of the previous jstack, jinfo, and jmap utilities for enhanced diagnostics and reduced performance overhead.

Below are commands to get your properties/flags you want.

jcmd pid VM.system_properties
jcmd pid VM.flags

We need pid, for this use jcmd -l, like below

username@users-Air:~/javacode$ jcmd -l 
11441 Test 
6294 Test 
29197 jdk.jcmd/sun.tools.jcmd.JCmd -l 

Now time to use these pids to get properties/flags you want

Command: jcmd 11441 VM.system_properties

11441:
#Tue Oct 17 12:44:50 IST 2017
gopherProxySet=false
awt.toolkit=sun.lwawt.macosx.LWCToolkit
file.encoding.pkg=sun.io
java.specification.version=9
sun.cpu.isalist=
sun.jnu.encoding=UTF-8
java.class.path=.
java.vm.vendor=Oracle Corporation
sun.arch.data.model=64
java.vendor.url=http\://java.oracle.com/
user.timezone=Asia/Kolkata
java.vm.specification.version=9
os.name=Mac OS X
sun.java.launcher=SUN_STANDARD
user.country=US
sun.boot.library.path=/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/lib
sun.java.command=Test
http.nonProxyHosts=local|*.local|169.254/16|*.169.254/16
jdk.debug=release
sun.cpu.endian=little
user.home=/Users/XXXX
user.language=en
java.specification.vendor=Oracle Corporation
java.home=/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home
file.separator=/
java.vm.compressedOopsMode=Zero based
line.separator=\n
java.specification.name=Java Platform API Specification
java.vm.specification.vendor=Oracle Corporation
java.awt.graphicsenv=sun.awt.CGraphicsEnvironment
sun.management.compiler=HotSpot 64-Bit Tiered Compilers
ftp.nonProxyHosts=local|*.local|169.254/16|*.169.254/16
java.runtime.version=9+181
user.name=XXXX
path.separator=\:
os.version=10.12.6
java.runtime.name=Java(TM) SE Runtime Environment
file.encoding=UTF-8
java.vm.name=Java HotSpot(TM) 64-Bit Server VM
java.vendor.url.bug=http\://bugreport.java.com/bugreport/
java.io.tmpdir=/var/folders/dm/gd6lc90d0hg220lzw_m7krr00000gn/T/
java.version=9
user.dir=/Users/XXXX/javacode
os.arch=x86_64
java.vm.specification.name=Java Virtual Machine Specification
java.awt.printerjob=sun.lwawt.macosx.CPrinterJob
sun.os.patch.level=unknown
MyParam=2
java.library.path=/Users/XXXX/Library/Java/Extensions\:/Library/Java/Extensions\:/Network/Library/Java/Extensions\:/System/Library/Java/Extensions\:/usr/lib/java\:.
java.vm.info=mixed mode
java.vendor=Oracle Corporation
java.vm.version=9+181
sun.io.unicode.encoding=UnicodeBig
java.class.version=53.0
socksNonProxyHosts=local|*.local|169.254/16|*.169.254/16

Command : jcmd 11441 VM.flags output:

11441:
-XX:CICompilerCount=3 -XX:ConcGCThreads=1 -XX:G1ConcRefinementThreads=4 -XX:G1HeapRegionSize=1048576 -XX:InitialHeapSize=67108864 -XX:MarkStackSize=4194304 -XX:MaxHeapSize=1073741824 -XX:MaxNewSize=643825664 -XX:MinHeapDeltaBytes=1048576 -XX:NonNMethodCodeHeapSize=5830092 -XX:NonProfiledCodeHeapSize=122914074 -XX:ProfiledCodeHeapSize=122914074 -XX:ReservedCodeCacheSize=251658240 -XX:+SegmentedCodeCache -XX:-UseAOT -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseFastUnorderedTimeStamps -XX:+UseG1GC 

For more instructions of usages of jcmd, see my blog post

$watch an object

Try this:

function MyController($scope) {
    $scope.form = {
        name: 'my name',
        surname: 'surname'
    }

    function track(newValue, oldValue, scope) {
        console.log('changed');
    };

    $scope.$watch('form.name', track);
}

How do I configure Notepad++ to use spaces instead of tabs?

Go to the Preferences menu command under menu Settings, and select Language Menu/Tab Settings, depending on your version. Earlier versions use Tab Settings. Later versions use Language. Click the Replace with space check box. Set the size to 4.

Enter image description here

See documentation: http://docs.notepad-plus-plus.org/index.php/Built-in_Languages#Tab_settings

Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

This means that you must declare strict mode by writing "use strict" at the beginning of the file or the function to use block-scope declarations.

EX:

function test(){
    "use strict";
    let a = 1;
} 

How to get element by classname or id

getElementsByClassName is a function on the DOM Document. It is neither a jQuery nor a jqLite function.

Don't add the period before the class name when using it:

var result = document.getElementsByClassName("multi-files");

Wrap it in jqLite (or jQuery if jQuery is loaded before Angular):

var wrappedResult = angular.element(result);

If you want to select from the element in a directive's link function you need to access the DOM reference instead of the the jqLite reference - element[0] instead of element:

link: function (scope, element, attrs) {

  var elementResult = element[0].getElementsByClassName('multi-files');
}

Alternatively you can use the document.querySelector function (need the period here if selecting by class):

var queryResult = element[0].querySelector('.multi-files');
var wrappedQueryResult = angular.element(queryResult);

Demo: http://plnkr.co/edit/AOvO47ebEvrtpXeIzYOH?p=preview

Making interface implementations async

An abstract class can be used instead of an interface (in C# 7.3).

// Like interface
abstract class IIO
{
    public virtual async Task<string> DoOperation(string Name)
    {
        throw new NotImplementedException(); // throwing exception
        // return await Task.Run(() => { return ""; }); // or empty do
    }
}

// Implementation
class IOImplementation : IIO
{
    public override async Task<string> DoOperation(string Name)
    {
        return await await Task.Run(() =>
        {
            if(Name == "Spiderman")
                return "ok";
            return "cancel";
        }); 
    }
}

How to manually deploy artifacts in Nexus Repository Manager OSS 3

To use mvn deploy:deploy-file, must add ~./m2/settings.xml

<settings>
  <servers>
    <server>
      <id>nexus-repo</id>
      <username>admin</username>
      <password>admin123</password>
    </server>
  </servers>
</settings>

command:

mvn deploy:deploy-file -DgroupId=com.example \
                                       -DartifactId=my-app \
                                       -Dversion=2.0.0 \
                                       -Dpackaging=jar \
                                       -Dfile=my-app.jar \
                                       -DgeneratePom=true \
                                       -DrepositoryId=nexus-repo \
                                       -Durl=http://localhost:8081/repository/maven-releases/

How to make git mark a deleted and a new file as a file move?

Do the move and the modify in separate commits.

React.js create loop through Array

In CurrentGame component you need to change initial state because you are trying use loop for participants but this property is undefined that's why you get error.,

getInitialState: function(){
    return {
       data: {
          participants: [] 
       }
    };
},

also, as player in .map is Object you should get properties from it

this.props.data.participants.map(function(player) {
   return <li key={player.championId}>{player.summonerName}</li>
   // -------------------^^^^^^^^^^^---------^^^^^^^^^^^^^^
})

Example

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

Solution to this is:

  1. use dataType: json
  2. add &callback=? to your url

this worked on calling Facebook API and with Firefox. Firebug is using GET instead of OPTIONS with the above conditions (both of them).

Removing "bullets" from unordered list <ul>

In my case

li {
  list-style-type : none;
}

It doesn't show the bullet but leaved some space for the bullet.

I use

li {
  list-style-type : '';
}

It works perfectly.

How to create an integer-for-loop in Ruby?

If you're doing this in your erb view (for Rails), be mindful of the <% and <%= differences. What you'd want is:

<% (1..x).each do |i| %>
  Code to display using <%= stuff %> that you want to display    
<% end %>

For plain Ruby, you can refer to: http://www.tutorialspoint.com/ruby/ruby_loops.htm

How to join multiple lines of file names into one with custom delimiter?

Adding on top of majkinetor's answer, here is the way of removing trailing delimiter(since I cannot just comment under his answer yet):

ls -1 | awk 'ORS=","' | head -c -1

Just remove as many trailing bytes as your delimiter counts for.

I like this approach because I can use multi character delimiters + other benefits of awk:

ls -1 | awk 'ORS=", "' | head -c -2

EDIT

As Peter has noticed, negative byte count is not supported in native MacOS version of head. This however can be easily fixed.

First, install coreutils. "The GNU Core Utilities are the basic file, shell and text manipulation utilities of the GNU operating system."

brew install coreutils

Commands also provided by MacOS are installed with the prefix "g". For example gls.

Once you have done this you can use ghead which has negative byte count, or better, make alias:

alias head="ghead"

"Could not load type [Namespace].Global" causing me grief

Change the GUID of the assembly. This fixes many MANY problems, I have found.

Generate a random point within a circle (uniformly)

Such a fun problem.
The rationale of the probability of a point being chosen lowering as distance from the axis origin increases is explained multiple times above. We account for that by taking the root of U[0,1]. Here's a general solution for a positive r in Python 3.

import numpy
import math
import matplotlib.pyplot as plt

def sq_point_in_circle(r):
    """
    Generate a random point in an r radius circle 
    centered around the start of the axis
    """

    t = 2*math.pi*numpy.random.uniform()
    R = (numpy.random.uniform(0,1) ** 0.5) * r

    return(R*math.cos(t), R*math.sin(t))

R = 200 # Radius
N = 1000 # Samples

points = numpy.array([sq_point_in_circle(R) for i in range(N)])
plt.scatter(points[:, 0], points[:,1])

enter image description here

No notification sound when sending notification from firebase in android

adavaced options select advanced options when Write a message, and choose sound activated choose activated

this is My solution

What is the maximum characters for the NVARCHAR(MAX)?

I think actually nvarchar(MAX) can store approximately 1070000000 chars.

What is memoization and how can I use it in Python?

Memoization is the conversion of functions into data structures. Usually one wants the conversion to occur incrementally and lazily (on demand of a given domain element--or "key"). In lazy functional languages, this lazy conversion can happen automatically, and thus memoization can be implemented without (explicit) side-effects.

How do I create a local database inside of Microsoft SQL Server 2014?

install Local DB from following link https://www.microsoft.com/en-us/download/details.aspx?id=42299 then connect to the local db using windows authentication. (localdb)\MSSQLLocalDB

How to set radio button selected value using jquery

Try

function RadionButtonSelectedValueSet(name, SelectdValue) {
    $('input[name="' + name+ '"][value="' + SelectdValue + '"]').prop('checked', true);
}

also call the method on dom ready

<script type="text/javascript">
jQuery(function(){
    RadionButtonSelectedValueSet('RBLExperienceApplicable', '1');
})
</script>

JQuery show and hide div on mouse click (animate)

Use slideToggle(500) function with a duration in milliseconds for getting a better effect.

Sample Html

<body>
    <div class="growth-step js--growth-step">
        <div class="step-title">
            <div class="num">2.</div>
            <h3>How Can Aria Help Your Business</h3>
        </div>
        <div class="step-details ">
            <p>At Aria solutions, we’ve taken the consultancy concept one step further by offering a full service
                management organization with expertise. </p>
        </div>
    </div>
    <div class="growth-step js--growth-step">
        <div class="step-title">
            <div class="num">3.</div>
            <h3>How Can Aria Help Your Business</h3>
        </div>
        <div class="step-details">
            <p>At Aria solutions, we’ve taken the consultancy concept one step further by offering a full service
                management organization with expertise. </p>
        </div>
    </div>
</body>

In your js file, if you need child propagation for the animation then remove the second click event function and its codes.

$(document).ready(function(){
    $(".js--growth-step").click(function(event){
       $(this).children(".step-details").slideToggle(500);
         return false;
    });
//for stoping child to manipulate the animation
    $(".js--growth-step .step-details").click(function(event) {
        event.stopPropagation();
   });
});

How to set time to midnight for current day?

I believe you are looking for DateTime.Today. The documentation states:

An object that is set to today's date, with the time component set to 00:00:00.

http://msdn.microsoft.com/en-us/library/system.datetime.today.aspx

Your code would be

DateTime _Begin = DateTime.Today;

Which version of MVC am I using?

Navigate to "C:\Program Files (x86)\Microsoft ASP.NET" folder. You will see "ASP.NET MVC 4" or something like that. To know detail navigate to "C:\Program Files (x86)\Microsoft ASP.NET{your MVC version}\Assemblies\System.Web.Mvc.dll" Right click and see the version.

Finding current executable's path without /proc/self/exe

An alternative on Linux to using either /proc/self/exe or argv[0] is using the information passed by the ELF interpreter, made available by glibc as such:

#include <stdio.h>
#include <sys/auxv.h>

int main(int argc, char **argv)
{
    printf("%s\n", (char *)getauxval(AT_EXECFN));
    return(0);
}

Note that getauxval is a glibc extension, and to be robust you should check so that it doesn't return NULL (indicating that the ELF interpreter hasn't provided the AT_EXECFN parameter), but I don't think this is ever actually a problem on Linux.

ES6 Class Multiple inheritance

My answer seems like less code and it works for me:

_x000D_
_x000D_
    class Nose {
      constructor() {
        this.booger = 'ready'; 
      }
      
      pick() {
        console.log('pick your nose')
      } 
    }
    
    class Ear {
      constructor() {
        this.wax = 'ready'; 
      }
      
      dig() {
        console.log('dig in your ear')
      } 
    }
    
    class Gross extends Classes([Nose,Ear]) {
      constructor() {
        super();
        this.gross = true;
      }
    }
    
    function Classes(bases) {
      class Bases {
        constructor() {
          bases.forEach(base => Object.assign(this, new base()));
        }
      }
      bases.forEach(base => {
        Object.getOwnPropertyNames(base.prototype)
        .filter(prop => prop != 'constructor')
        .forEach(prop => Bases.prototype[prop] = base.prototype[prop])
      })
      return Bases;
    }

    
    // test it
    
    var grossMan = new Gross();
    grossMan.pick(); // eww
    grossMan.dig();  // yuck!
_x000D_
_x000D_
_x000D_

How do I redirect a user when a button is clicked?

If, like me, you don't like to rely on JavaScript for links on buttons. You can also use a anchor and style it like your buttons using CSS.

<a href="/Controller/View" class="Button">Text</a>

How to replace (or strip) an extension from a filename in Python?

Try os.path.splitext it should do what you want.

import os
print os.path.splitext('/home/user/somefile.txt')[0]+'.jpg'

How to show current user name in a cell?

The simplest way is to create a VBA macro that wraps that function, like so:

Function UserNameWindows() As String
    UserName = Environ("USERNAME")
End Function

Then call it from the cell:

=UserNameWindows()

See this article for more details, and other ways.

How to search and replace text in a file?

(pip install python-util)

from pyutil import filereplace

filereplace("somefile.txt","abcd","ram")

Will replace all occurences of "abcd" with "ram".
The function also supports regex by specifying regex=True

from pyutil import filereplace

filereplace("somefile.txt","\\w+","ram",regex=True)

Disclaimer: I'm the author (https://github.com/MisterL2/python-util)

Get current date in milliseconds

There are several ways of doing this, although my personal favorite is:

CFAbsoluteTime timeInSeconds = CFAbsoluteTimeGetCurrent();

You can read more about this method here. You can also create a NSDate object and get time by calling timeIntervalSince1970 which returns the seconds since 1/1/1970:

NSTimeInterval timeInSeconds = [[NSDate date] timeIntervalSince1970];

And in Swift:

let timeInSeconds: TimeInterval = Date().timeIntervalSince1970

What are the time complexities of various data structures?

Arrays

  • Set, Check element at a particular index: O(1)
  • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
  • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
  • Similarly, Insert for arrays is basically Set as mentioned in the beginning

ArrayList:

  • Add: Amortized O(1)
  • Remove: O(n)
  • Contains: O(n)
  • Size: O(1)

Linked List:

  • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Doubly-Linked List:

  • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Stack:

  • Push: O(1)
  • Pop: O(1)
  • Top: O(1)
  • Search (Something like lookup, as a special operation): O(n) (I guess so)

Queue/Deque/Circular Queue:

  • Insert: O(1)
  • Remove: O(1)
  • Size: O(1)

Binary Search Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

Red-Black Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

Heap/PriorityQueue (min/max):

  • Find Min/Find Max: O(1)
  • Insert: O(log n)
  • Delete Min/Delete Max: O(log n)
  • Extract Min/Extract Max: O(log n)
  • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST

HashMap/Hashtable/HashSet:

  • Insert/Delete: O(1) amortized
  • Re-size/hash: O(n)
  • Contains: O(1)

Limit String Length

To truncate a string provided by the maximum limit without breaking a word use this:

/**
 * truncate a string provided by the maximum limit without breaking a word
 * @param string $str
 * @param integer $maxlen
 * @return string
 */
public static function truncateStringWords($str, $maxlen): string
{
    if (strlen($str) <= $maxlen) return $str;

    $newstr = substr($str, 0, $maxlen);
    if (substr($newstr, -1, 1) != ' ') $newstr = substr($newstr, 0, strrpos($newstr, " "));

    return $newstr;
}

How to echo out table rows from the db (php)

$sql = "SELECT * FROM MY_TABLE";
$result = mysqli_query($conn, $sql); // First parameter is just return of "mysqli_connect()" function
echo "<br>";
echo "<table border='1'>";
while ($row = mysqli_fetch_assoc($result)) { // Important line !!! Check summary get row on array ..
    echo "<tr>";
    foreach ($row as $field => $value) { // I you want you can right this line like this: foreach($row as $value) {
        echo "<td>" . $value . "</td>"; // I just did not use "htmlspecialchars()" function. 
    }
    echo "</tr>";
}
echo "</table>";

Select something that has more/less than x character

If your experiencing the same problem while querying a DB2 database, you'll need to use the below query.

SELECT * 
FROM OPENQUERY(LINK_DB,'SELECT
CITY,
cast(STATE as varchar(40)) 
FROM DATABASE')

angular 2 sort and filter

It is not supported by design. The sortBy pipe can cause real performance issues for a production scale app. This was an issue with angular version 1.

You should not create a custom sort function. Instead, you should sort your array first in the typescript file and then display it. If the order needs to be updated when for example a dropdown is selected then have this dropdown selection trigger a function and call your sort function called from that. This sort function can be extracted to a service so that it can be re-used. This way, the sorting will only be applied when it is required and your app performance will be much better.

PHP AES encrypt / decrypt

If you are using MCRYPT_RIJNDAEL_128, try rtrim($output, "\0\3"). If the length of the string is less than 16, the decrypt function will return a string with length of 16 characters, adding 03 at the end.

You can easily check this, e.g. by trying:

$string = "TheString";
$decrypted_string = decrypt_function($stirng, $key);

echo bin2hex($decrypted_string)."=".bin2hex("TheString");

Import Libraries in Eclipse?

For the Android library projects, I do it as in the attached screenshot:

Right click the project, select Properties->Android and in the library section click Add. From here you can select the available libraries.

If you are importing a jar file, then importing them as jar or external jar, as other posters posted would work. I prefer to copy/paste jar file in the libs folder (create one if it doesn't exist) and then import as jar.

Adding a library

Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

Uncaught ReferenceError: google is not defined error will be gone when removed the async defer from the map API script tag.

Android: Background Image Size (in Pixel) which Support All Devices

Android Devices Matrices

                            ldpi     mdpi     hdpi    xhdpi    xxhdpi      xxxhdpi
Launcher And Home           36*36    48*48   72*72    96*96    144*144     192*192
Toolbar And Tab             24*24    32*32   48*48    64*64    96*96       128*128
Notification                18*18    24*24   36*36    48*48    72*72       96*96 
Background                 240*320  320*480 480*800  768*1280  1080 *1920  1440*2560 

(For good approach minus Toolbar Size From total height of Background Screen and then Design Graphics of Screens )

For More Help (This link includes tablets also):

https://design.google.com/devices/

Android Native Icons (Recommended) You can change color of these icons programmatically. https://design.google.com/icons/

Switch case with fallthrough?

If the values are integer then you can use [2-3] or you can use [5,7,8] for non continuous values.

#!/bin/bash
while [ $# -gt 0 ];
do
    case $1 in
    1)
        echo "one"
        ;;
    [2-3])
        echo "two or three"
        ;;
    [4-6])
        echo "four to six"
        ;;
    [7,9])
        echo "seven or nine"
        ;;
    *)
        echo "others"
        ;;
    esac
    shift
done

If the values are string then you can use |.

#!/bin/bash
while [ $# -gt 0 ];
do
    case $1 in
    "one")
        echo "one"
        ;;
    "two" | "three")
        echo "two or three"
        ;;
    *)
        echo "others"
        ;;
    esac
    shift
done

init-param and context-param

Consider the below definition in web.xml

<servlet>
    <servlet-name>HelloWorld</servlet-name>
    <servlet-class>TestServlet</servlet-class>
    <init-param>
        <param-name>myprop</param-name>
        <param-value>value</param-value>
    </init-param>
</servlet>

You can see that init-param is defined inside a servlet element. This means it is only available to the servlet under declaration and not to other parts of the web application. If you want this parameter to be available to other parts of the application say a JSP this needs to be explicitly passed to the JSP. For instance passed as request.setAttribute(). This is highly inefficient and difficult to code.

So if you want to get access to global values from anywhere within the application without explicitly passing those values, you need to use Context Init parameters.

Consider the following definition in web.xml

 <web-app>
      <context-param>
           <param-name>myprop</param-name>
           <param-value>value</param-value>
      </context-param>
 </web-app>

This context param is available to all parts of the web application and it can be retrieved from the Context object. For instance, getServletContext().getInitParameter(“dbname”);

From a JSP you can access the context parameter using the application implicit object. For example, application.getAttribute(“dbname”);

How to make an inline-block element fill the remainder of the line?

A modern solution using flexbox:

_x000D_
_x000D_
.container {_x000D_
    display: flex;_x000D_
}_x000D_
.container > div {_x000D_
    border: 1px solid black;_x000D_
    height: 10px;_x000D_
}_x000D_
_x000D_
.left {_x000D_
   width: 100px;_x000D_
}_x000D_
_x000D_
.right {_x000D_
    width: 100%;_x000D_
    background-color:#ddd;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="left"></div>_x000D_
  <div class="right"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/m5Xz2/100/

403 - Forbidden: Access is denied. ASP.Net MVC

I just had this issue, it was because the IIS site was pointing at the wrong Application Pool.

WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400

In my case, I have just install express-status-monitor to get rid of this error

here are the settings

install express-status-monitor
npm i express-status-monitor --save
const expressStatusMonitor = require('express-status-monitor');
app.use(expressStatusMonitor({
    websocket: io,
    port: app.get('port')
}));

Java Reflection: How to get the name of a variable?

(Edit: two previous answers removed, one for answering the question as it stood before edits and one for being, if not absolutely wrong, at least close to it.)

If you compile with debug information on (javac -g), the names of local variables are kept in the .class file. For example, take this simple class:

class TestLocalVarNames {
    public String aMethod(int arg) {
        String local1 = "a string";
        StringBuilder local2 = new StringBuilder();
        return local2.append(local1).append(arg).toString();
    }
}

After compiling with javac -g:vars TestLocalVarNames.java, the names of local variables are now in the .class file. javap's -l flag ("Print line number and local variable tables") can show them.

javap -l -c TestLocalVarNames shows:

class TestLocalVarNames extends java.lang.Object{
TestLocalVarNames();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

  LocalVariableTable:
   Start  Length  Slot  Name   Signature
   0      5      0    this       LTestLocalVarNames;

public java.lang.String aMethod(int);
  Code:
   0:   ldc     #2; //String a string
   2:   astore_2
   3:   new     #3; //class java/lang/StringBuilder
   6:   dup
   7:   invokespecial   #4; //Method java/lang/StringBuilder."<init>":()V
   10:  astore_3
   11:  aload_3
   12:  aload_2
   13:  invokevirtual   #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   16:  iload_1
   17:  invokevirtual   #6; //Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
   20:  invokevirtual   #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
   23:  areturn

  LocalVariableTable:
   Start  Length  Slot  Name   Signature
   0      24      0    this       LTestLocalVarNames;
   0      24      1    arg       I
   3      21      2    local1       Ljava/lang/String;
   11      13      3    local2       Ljava/lang/StringBuilder;
}

The VM spec explains what we're seeing here:

§4.7.9 The LocalVariableTable Attribute:

The LocalVariableTable attribute is an optional variable-length attribute of a Code (§4.7.3) attribute. It may be used by debuggers to determine the value of a given local variable during the execution of a method.

The LocalVariableTable stores the names and types of the variables in each slot, so it is possible to match them up with the bytecode. This is how debuggers can do "Evaluate expression".

As erickson said, though, there's no way to access this table through normal reflection. If you're still determined to do this, I believe the Java Platform Debugger Architecture (JPDA) will help (but I've never used it myself).

Clip/Crop background-image with CSS

may be you can write like this:

#graphic { 
 background-image: url(image.jpg); 
 background-position: 0 -50px; 
 width: 200px; 
 height: 100px;
}

js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check

Just default the variable to the expected type:

(number=1) => ...
(number=1.0) => ...
(string='str') ...

Two-dimensional array in Swift

This can be done in one simple line.

Swift 5

var my2DArray = (0..<4).map { _ in Array(0..<) }

You could also map it to instances of any class or struct of your choice

struct MyStructCouldBeAClass {
    var x: Int
    var y: Int
}

var my2DArray: [[MyStructCouldBeAClass]] = (0..<2).map { x in
    Array(0..<2).map { MyStructCouldBeAClass(x: x, y: $0)}
}

Insert data into table with result from another select query

If table_2 is empty, then try the following insert statement:

insert into table_2 (itemid,location1) 
select itemid,quantity from table_1 where locationid=1

If table_2 already contains the itemid values, then try this update statement:

update table_2 set location1=
(select quantity from table_1 where locationid=1 and table_1.itemid = table_2.itemid)

How do I get the Date & Time (VBS)

nowreturns the current date and time

How to cancel a local git commit

Just use git reset without the --hard flag:

git reset HEAD~1

PS: On Unix based systems you can use HEAD^ which is equal to HEAD~1. On Windows HEAD^ will not work because ^ signals a line continuation. So your command prompt will just ask you More?.

What's the difference between xsd:include and xsd:import?

The fundamental difference between include and import is that you must use import to refer to declarations or definitions that are in a different target namespace and you must use include to refer to declarations or definitions that are (or will be) in the same target namespace.

Source: https://web.archive.org/web/20070804031046/http://xsd.stylusstudio.com/2002Jun/post08016.htm

How to return a result (startActivityForResult) from a TabHost Activity?

Intent.FLAG_ACTIVITY_FORWARD_RESULT?

If set and this intent is being used to launch a new activity from an existing one, then the reply target of the existing activity will be transfered to the new activity.

Do copyright dates need to be updated?

Your OCD is to blame :)

You do not have to put anything about copyright on your page - copyright automatically applies until you explicitly license it otherwise. Copyright also applies for a preset number of years as determined by international treaties. I do not know what the exact number of years is, but it is a lot, so there is absolutely no point in updating the year in your copyright notice.

JavaFX Application Icon

stage.getIcons().add(new Image(ClassLoader.getSystemResourceAsStream("images/icon.png")));

images folder need to be in Resource folder.

HTML5 Canvas: Zooming

IIRC Canvas is a raster style bitmap. it wont be zoomable because there's no stored information to zoom to.

Your best bet is to keep two copies in memory (zoomed and non) and swap them on mouse click.

':app:lintVitalRelease' error when generating signed apk

I wouldn't recommend turning off the lint checks, they're there for a reason. Instead, check what the error is and fix it.

The error report is saved to [app module]/build/reports/lint-results-yourBuildName-fatal.html. You can open this file in a browser to read about the errors.

It would be nice if Gradle could make it a little more clear where the error report is generated.

memcpy() vs memmove()

compiler could optimize memcpy, for example:

int x;
memcpy(&x, some_pointer, sizeof(int));

This memcpy may be optimized as: x = *(int*)some_pointer;

Array vs ArrayList in performance

When deciding to use Array or ArrayList, your first instinct really shouldn't be worrying about performance, though they do perform differently. You first concern should be whether or not you know the size of the Array before hand. If you don't, naturally you would go with an array list, just for functionality.

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

What is a Memory Heap?

A memory heap is a location in memory where memory may be allocated at random access.
Unlike the stack where memory is allocated and released in a very defined order, individual data elements allocated on the heap are typically released in ways which is asynchronous from one another. Any such data element is freed when the program explicitly releases the corresponding pointer, and this may result in a fragmented heap. In opposition only data at the top (or the bottom, depending on the way the stack works) may be released, resulting in data element being freed in the reverse order they were allocated.

phpMyAdmin - config.inc.php configuration?

Run This Query:


*> -- --------------------------------------------------------
> -- SQL Commands to set up the pmadb as described in the documentation.
> --
> -- This file is meant for use with MySQL 5 and above!
> --
> -- This script expects the user pma to already be existing. If we would put a
> -- line here to create him too many users might just use this script and end
> -- up with having the same password for the controluser.
> --
> -- This user "pma" must be defined in config.inc.php (controluser/controlpass)
> --
> -- Please don't forget to set up the tablenames in config.inc.php
> --
> 
> -- --------------------------------------------------------
> 
> --
> -- Database : `phpmyadmin`
> -- CREATE DATABASE IF NOT EXISTS `phpmyadmin`   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin; USE phpmyadmin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Privileges
> --
> -- (activate this statement if necessary)
> -- GRANT SELECT, INSERT, DELETE, UPDATE, ALTER ON `phpmyadmin`.* TO
> --    'pma'@localhost;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__bookmark`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__bookmark` (   `id` int(10) unsigned
> NOT NULL auto_increment,   `dbase` varchar(255) NOT NULL default '',  
> `user` varchar(255) NOT NULL default '',   `label` varchar(255)
> COLLATE utf8_general_ci NOT NULL default '',   `query` text NOT NULL, 
> PRIMARY KEY  (`id`) )   COMMENT='Bookmarks'   DEFAULT CHARACTER SET
> utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__column_info`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__column_info` (   `id` int(5) unsigned
> NOT NULL auto_increment,   `db_name` varchar(64) NOT NULL default '', 
> `table_name` varchar(64) NOT NULL default '',   `column_name`
> varchar(64) NOT NULL default '',   `comment` varchar(255) COLLATE
> utf8_general_ci NOT NULL default '',   `mimetype` varchar(255) COLLATE
> utf8_general_ci NOT NULL default '',   `transformation` varchar(255)
> NOT NULL default '',   `transformation_options` varchar(255) NOT NULL
> default '',   `input_transformation` varchar(255) NOT NULL default '',
> `input_transformation_options` varchar(255) NOT NULL default '',  
> PRIMARY KEY  (`id`),   UNIQUE KEY `db_name`
> (`db_name`,`table_name`,`column_name`) )   COMMENT='Column information
> for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__history`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__history` (   `id` bigint(20) unsigned
> NOT NULL auto_increment,   `username` varchar(64) NOT NULL default '',
> `db` varchar(64) NOT NULL default '',   `table` varchar(64) NOT NULL
> default '',   `timevalue` timestamp NOT NULL default
> CURRENT_TIMESTAMP,   `sqlquery` text NOT NULL,   PRIMARY KEY  (`id`), 
> KEY `username` (`username`,`db`,`table`,`timevalue`) )   COMMENT='SQL
> history for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__pdf_pages`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__pdf_pages` (   `db_name` varchar(64)
> NOT NULL default '',   `page_nr` int(10) unsigned NOT NULL
> auto_increment,   `page_descr` varchar(50) COLLATE utf8_general_ci NOT
> NULL default '',   PRIMARY KEY  (`page_nr`),   KEY `db_name`
> (`db_name`) )   COMMENT='PDF relation pages for phpMyAdmin'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__recent`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__recent` (   `username` varchar(64)
> NOT NULL,   `tables` text NOT NULL,   PRIMARY KEY (`username`) )  
> COMMENT='Recently accessed tables'   DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__favorite`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__favorite` (   `username` varchar(64)
> NOT NULL,   `tables` text NOT NULL,   PRIMARY KEY (`username`) )  
> COMMENT='Favorite tables'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__table_uiprefs`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__table_uiprefs` (   `username`
> varchar(64) NOT NULL,   `db_name` varchar(64) NOT NULL,   `table_name`
> varchar(64) NOT NULL,   `prefs` text NOT NULL,   `last_update`
> timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
> CURRENT_TIMESTAMP,   PRIMARY KEY (`username`,`db_name`,`table_name`) )
> COMMENT='Tables'' UI preferences'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__relation`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__relation` (   `master_db` varchar(64)
> NOT NULL default '',   `master_table` varchar(64) NOT NULL default '',
> `master_field` varchar(64) NOT NULL default '',   `foreign_db`
> varchar(64) NOT NULL default '',   `foreign_table` varchar(64) NOT
> NULL default '',   `foreign_field` varchar(64) NOT NULL default '',  
> PRIMARY KEY  (`master_db`,`master_table`,`master_field`),   KEY
> `foreign_field` (`foreign_db`,`foreign_table`) )   COMMENT='Relation
> table'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__table_coords`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__table_coords` (   `db_name`
> varchar(64) NOT NULL default '',   `table_name` varchar(64) NOT NULL
> default '',   `pdf_page_number` int(11) NOT NULL default '0',   `x`
> float unsigned NOT NULL default '0',   `y` float unsigned NOT NULL
> default '0',   PRIMARY KEY  (`db_name`,`table_name`,`pdf_page_number`)
> )   COMMENT='Table coordinates for phpMyAdmin PDF output'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__table_info`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__table_info` (   `db_name` varchar(64)
> NOT NULL default '',   `table_name` varchar(64) NOT NULL default '',  
> `display_field` varchar(64) NOT NULL default '',   PRIMARY KEY 
> (`db_name`,`table_name`) )   COMMENT='Table information for
> phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__tracking`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__tracking` (   `db_name` varchar(64)
> NOT NULL,   `table_name` varchar(64) NOT NULL,   `version` int(10)
> unsigned NOT NULL,   `date_created` datetime NOT NULL,  
> `date_updated` datetime NOT NULL,   `schema_snapshot` text NOT NULL,  
> `schema_sql` text,   `data_sql` longtext,   `tracking`
> set('UPDATE','REPLACE','INSERT','DELETE','TRUNCATE','CREATE
> DATABASE','ALTER DATABASE','DROP DATABASE','CREATE TABLE','ALTER
> TABLE','RENAME TABLE','DROP TABLE','CREATE INDEX','DROP INDEX','CREATE
> VIEW','ALTER VIEW','DROP VIEW') default NULL,   `tracking_active`
> int(1) unsigned NOT NULL default '1',   PRIMARY KEY 
> (`db_name`,`table_name`,`version`) )   COMMENT='Database changes
> tracking for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__userconfig`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__userconfig` (   `username`
> varchar(64) NOT NULL,   `timevalue` timestamp NOT NULL default
> CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,   `config_data` text
> NOT NULL,   PRIMARY KEY  (`username`) )   COMMENT='User preferences
> storage for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__users`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__users` (   `username` varchar(64) NOT
> NULL,   `usergroup` varchar(64) NOT NULL,   PRIMARY KEY
> (`username`,`usergroup`) )   COMMENT='Users and their assignments to
> user groups'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__usergroups`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__usergroups` (   `usergroup`
> varchar(64) NOT NULL,   `tab` varchar(64) NOT NULL,   `allowed`
> enum('Y','N') NOT NULL DEFAULT 'N',   PRIMARY KEY
> (`usergroup`,`tab`,`allowed`) )   COMMENT='User groups with configured
> menu items'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__navigationhiding`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__navigationhiding` (   `username`
> varchar(64) NOT NULL,   `item_name` varchar(64) NOT NULL,  
> `item_type` varchar(64) NOT NULL,   `db_name` varchar(64) NOT NULL,  
> `table_name` varchar(64) NOT NULL,   PRIMARY KEY
> (`username`,`item_name`,`item_type`,`db_name`,`table_name`) )  
> COMMENT='Hidden items of navigation tree'   DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__savedsearches`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__savedsearches` (   `id` int(5)
> unsigned NOT NULL auto_increment,   `username` varchar(64) NOT NULL
> default '',   `db_name` varchar(64) NOT NULL default '',  
> `search_name` varchar(64) NOT NULL default '',   `search_data` text
> NOT NULL,   PRIMARY KEY  (`id`),   UNIQUE KEY
> `u_savedsearches_username_dbname` (`username`,`db_name`,`search_name`)
> )   COMMENT='Saved searches'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__central_columns`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__central_columns` (   `db_name`
> varchar(64) NOT NULL,   `col_name` varchar(64) NOT NULL,   `col_type`
> varchar(64) NOT NULL,   `col_length` text,   `col_collation`
> varchar(64) NOT NULL,   `col_isNull` boolean NOT NULL,   `col_extra`
> varchar(255) default '',   `col_default` text,   PRIMARY KEY
> (`db_name`,`col_name`) )   COMMENT='Central list of columns'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__designer_settings`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__designer_settings` (   `username`
> varchar(64) NOT NULL,   `settings_data` text NOT NULL,   PRIMARY KEY
> (`username`) )   COMMENT='Settings related to Designer'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__export_templates`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__export_templates` (   `id` int(5)
> unsigned NOT NULL AUTO_INCREMENT,   `username` varchar(64) NOT NULL,  
> `export_type` varchar(10) NOT NULL,   `template_name` varchar(64) NOT
> NULL,   `template_data` text NOT NULL,   PRIMARY KEY (`id`),   UNIQUE
> KEY `u_user_type_template` (`username`,`export_type`,`template_name`)
> )   COMMENT='Saved export templates'   DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;*

Open This File :

C:\xampp\phpMyAdmin\config.inc.php

Clear and Past this Code :

> --------------------------------------------------------- <?php /**  * Debian local configuration file  *  * This file overrides the settings
> made by phpMyAdmin interactive setup  * utility.  *  * For example
> configuration see
> /usr/share/doc/phpmyadmin/examples/config.default.php.gz  *  * NOTE:
> do not add security sensitive data to this file (like passwords)  *
> unless you really know what you're doing. If you do, any user that can
> * run PHP or CGI on your webserver will be able to read them. If you still  * want to do this, make sure to properly secure the access to
> this file  * (also on the filesystem level).  */ /**  * Server(s)
> configuration  */ $i = 0; // The $cfg['Servers'] array starts with
> $cfg['Servers'][1].  Do not use $cfg['Servers'][0]. // You can disable
> a server config entry by setting host to ''. $i++; /* Read
> configuration from dbconfig-common */
> require('/etc/phpmyadmin/config-db.php'); /* Configure according to
> dbconfig-common if enabled */ if (!empty($dbname)) {
>     /* Authentication type */
>     $cfg['Servers'][$i]['auth_type'] = 'cookie';
>     /* Server parameters */
>     if (empty($dbserver)) $dbserver = 'localhost';
>     $cfg['Servers'][$i]['host'] = $dbserver;
>     if (!empty($dbport)) {
>         $cfg['Servers'][$i]['connect_type'] = 'tcp';
>         $cfg['Servers'][$i]['port'] = $dbport;
>     }
>     //$cfg['Servers'][$i]['compress'] = false;
>     /* Select mysqli if your server has it */
>     $cfg['Servers'][$i]['extension'] = 'mysqli';
>     /* Optional: User for advanced features */
>     $cfg['Servers'][$i]['controluser'] = $dbuser;
>     $cfg['Servers'][$i]['controlpass'] = $dbpass;
>     /* Optional: Advanced phpMyAdmin features */
>     $cfg['Servers'][$i]['pmadb'] = $dbname;
>     $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
>     $cfg['Servers'][$i]['relation'] = 'pma_relation';
>     $cfg['Servers'][$i]['table_info'] = 'pma_table_info';
>     $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
>     $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
>     $cfg['Servers'][$i]['column_info'] = 'pma_column_info';
>     $cfg['Servers'][$i]['history'] = 'pma_history';
>     $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';
>     /* Uncomment the following to enable logging in to passwordless accounts,
>      * after taking note of the associated security risks. */
>     // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
>     /* Advance to next server for rest of config */
>     $i++; } /* Authentication type */ //$cfg['Servers'][$i]['auth_type'] = 'cookie'; /* Server parameters */
> $cfg['Servers'][$i]['host'] = 'localhost';  
> $cfg['Servers'][$i]['connect_type'] = 'tcp';
> //$cfg['Servers'][$i]['compress'] = false; /* Select mysqli if your
> server has it */ //$cfg['Servers'][$i]['extension'] = 'mysql'; /*
> Optional: User for advanced features */ //
> $cfg['Servers'][$i]['controluser'] = 'pma'; //
> $cfg['Servers'][$i]['controlpass'] = 'pmapass'; /* Optional: Advanced
> phpMyAdmin features */ // $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
> // $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; //
> $cfg['Servers'][$i]['relation'] = 'pma_relation'; //
> $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; //
> $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; //
> $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; //
> $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; //
> $cfg['Servers'][$i]['history'] = 'pma_history'; //
> $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords'; /*
> Uncomment the following to enable logging in to passwordless accounts,
> * after taking note of the associated security risks. */ // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; /*  * End of servers
> configuration  */ /*  * Directories for saving/loading files from
> server  */ $cfg['UploadDir'] = ''; $cfg['SaveDir'] = '';

------------------------------------------

i Solve My Problem Through this Method

Why do I keep getting Delete 'cr' [prettier/prettier]?

I know this is old but I just encountered the issue in my team (some mac, some linux, some windows , all vscode).

solution was to set the line ending in vscode's settings:

.vscode/settings.json

{
    "files.eol": "\n",
}

https://qvault.io/2020/06/18/how-to-get-consistent-line-breaks-in-vs-code-lf-vs-crlf/

Bootstrap 4, how to make a col have a height of 100%?

Use bootstrap class vh-100 for exp:

<div class="vh-100">

CSS3 transform: rotate; in IE9

Try this

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
body {
    margin-left: 50px;
    margin-top: 50px;
    margin-right: 50px;
    margin-bottom: 50px;
}
.rotate {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 16px;
    -webkit-transform: rotate(-10deg);
    -moz-transform: rotate(-10deg);
    -o-transform: rotate(-10deg);
    -ms-transform: rotate(-10deg);
    -sand-transform: rotate(10deg);
    display: block;
    position: fixed;
}
</style>
</head>

<body>
<div class="rotate">Alpesh</div>
</body>
</html>

How to update column with null value

if you follow

UPDATE table SET name = NULL

then name is "" not NULL IN MYSQL means your query

SELECT * FROM table WHERE name = NULL not work or disappoint yourself

Check if table exists

I don't actually find any of the presented solutions here to be fully complete so I'll add my own. Nothing new here. You can stitch this together from the other presented solutions plus various comments.

There are at least two things you'll have to make sure:

  1. Make sure you pass the table name to the getTables() method, rather than passing a null value. In the first case you let the database server filter the result for you, in the second you request a list of all tables from the server and then filter the list locally. The former is much faster if you are only searching for a single table.

  2. Make sure to check the table name from the resultset with an equals match. The reason is that the getTables() does pattern matching on the query for the table and the _ character is a wildcard in SQL. Suppose you are checking for the existence of a table named EMPLOYEE_SALARY. You'll then get a match on EMPLOYEESSALARY too which is not what you want.

Ohh, and do remember to close those resultsets. Since Java 7 you would want to use a try-with-resources statement for that.

Here's a complete solution:

public static boolean tableExist(Connection conn, String tableName) throws SQLException {
    boolean tExists = false;
    try (ResultSet rs = conn.getMetaData().getTables(null, null, tableName, null)) {
        while (rs.next()) { 
            String tName = rs.getString("TABLE_NAME");
            if (tName != null && tName.equals(tableName)) {
                tExists = true;
                break;
            }
        }
    }
    return tExists;
}

You may want to consider what you pass as the types parameter (4th parameter) on your getTables() call. Normally I would just leave at null because you don't want to restrict yourself. A VIEW is as good as a TABLE, right? These days many databases allow you to update through a VIEW so restricting yourself to only TABLE type is in most cases not the way to go. YMMV.

"Use the new keyword if hiding was intended" warning

In the code below, Class A implements the interface IShow and implements its method ShowData. Class B inherits Class A. In order to use ShowData method in Class B, we have to use keyword new in the ShowData method in order to hide the base class Class A method and use override keyword in order to extend the method.

interface IShow
{
    protected void ShowData();
}

class A : IShow
{
    protected void ShowData()
    {
        Console.WriteLine("This is Class A");
    }
}

class B : A
{
    protected new void ShowData()
    {
        Console.WriteLine("This is Class B");
    }
}

Refused to load the script because it violates the following Content Security Policy directive

The probable reason why you get this error is likely because you've added the /build folder to your .gitignore file or generally haven't checked it into Git.

So when you Git push Heroku master, the build folder you're referencing don't get pushed to Heroku. And that's why it shows this error.

That's the reason it works properly locally, but not when you deployed to Heroku.

PowerShell: Comparing dates

Late but more complete answer in point of getting the most advanced date from $Output

## Q:\test\2011\02\SO_5097125.ps1
## simulate object input with a here string 
$Output = @"
"Date"
"Monday, April 08, 2013 12:00:00 AM"
"Friday, April 08, 2011 12:00:00 AM"
"@ -split '\r?\n' | ConvertFrom-Csv

## use Get-Date and calculated property in a pipeline
$Output | Select-Object @{n='Date';e={Get-Date $_.Date}} |
    Sort-Object Date | Select-Object -Last 1 -Expand Date

## use Get-Date in a ForEach-Object
$Output.Date | ForEach-Object{Get-Date $_} |
    Sort-Object | Select-Object -Last 1

## use [datetime]::ParseExact
## the following will only work if your locale is English for day, month day abbrev.
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',$Null)
} | Sort-Object | Select-Object -Last 1

## for non English locales
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',[cultureinfo]::InvariantCulture)
} | Sort-Object | Select-Object -Last 1

## in case the day month abbreviations are in other languages, here German
## simulate object input with a here string 
$Output = @"
"Date"
"Montag, April 08, 2013 00:00:00"
"Freidag, April 08, 2011 00:00:00"
"@ -split '\r?\n' | ConvertFrom-Csv
$CIDE = New-Object System.Globalization.CultureInfo("de-DE")
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy HH:mm:ss',$CIDE)
} | Sort-Object | Select-Object -Last 1

Loop through files in a folder using VBA?

Here's my interpretation as a Function Instead:

'#######################################################################
'# LoopThroughFiles
'# Function to Loop through files in current directory and return filenames
'# Usage: LoopThroughFiles ActiveWorkbook.Path, "txt" 'inputDirectoryToScanForFile
'# https://stackoverflow.com/questions/10380312/loop-through-files-in-a-folder-using-vba
'#######################################################################
Function LoopThroughFiles(inputDirectoryToScanForFile, filenameCriteria) As String

    Dim StrFile As String
    'Debug.Print "in LoopThroughFiles. inputDirectoryToScanForFile: ", inputDirectoryToScanForFile

    StrFile = Dir(inputDirectoryToScanForFile & "\*" & filenameCriteria)
    Do While Len(StrFile) > 0
        Debug.Print StrFile
        StrFile = Dir

    Loop

End Function

Cancel a UIView animation?

CALayer * pLayer = self.layer.presentationLayer;
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView animateWithDuration:0.001 animations:^{
    self.frame = pLayer.frame;
}];

How to validate a form with multiple checkboxes to have atleast one checked

if (
  document.forms["form"]["mon"].checked==false &&
  document.forms["form"]["tues"].checked==false &&
  document.forms["form"]["wed"].checked==false &&
  document.forms["form"]["thrs"].checked==false &&
  document.forms["form"]["fri"].checked==false
) {
  alert("Select at least One Day into Five Days");
  return false; 
}

What is the size of a boolean variable in Java?

On a side note...

If you are thinking about using an array of Boolean objects, don't. Use a BitSet instead - it has some performance optimisations (and some nice extra methods, allowing you to get the next set/unset bit).

How to align matching values in two columns in Excel, and bring along associated values in other columns

assuming the item numbers are unique, a VLOOKUP should get you the information you need.

first value would be =VLOOKUP(E1,A:B,2,FALSE), and the same type of formula to retrieve the second value would be =VLOOKUP(E1,C:D,2,FALSE). Wrap them in an IFERROR if you want to return anything other than #N/A if there is no corresponding value in the item column(s)

How do you configure HttpOnly cookies in tomcat / java webapps?

For cookies that I am explicitly setting, I switched to use SimpleCookie provided by Apache Shiro. It does not inherit from javax.servlet.http.Cookie so it takes a bit more juggling to get everything to work correctly however it does provide a property set HttpOnly and it works with Servlet 2.5.

For setting a cookie on a response, rather than doing response.addCookie(cookie) you need to do cookie.saveTo(request, response).

how to convert string into time format and add two hours

You can use SimpleDateFormat to convert the String to Date. And after that you have two options,

  • Make a Calendar object and and then use that to add two hours, or
  • get the time in millisecond from that date object, and add two hours like, (2 * 60 * 60 * 1000)

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    // replace with your start date string
    Date d = df.parse("2008-04-16 00:05:05"); 
    Calendar gc = new GregorianCalendar();
    gc.setTime(d);
    gc.add(Calendar.HOUR, 2);
    Date d2 = gc.getTime();
    

    Or,

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    // replace with your start date string
    Date d = df.parse("2008-04-16 00:05:05");
    Long time = d.getTime();
    time +=(2*60*60*1000);
    Date d2 = new Date(time);
    

Have a look to these tutorials.

How to declare an array of objects in C#

The issue here is that you've initialized your array, but not its elements; they are all null. So if you try to reference houses[0], it will be null.

Here's a great little helper method you could write for yourself:

T[] InitializeArray<T>(int length) where T : new()
{
    T[] array = new T[length];
    for (int i = 0; i < length; ++i)
    {
        array[i] = new T();
    }

    return array;
}

Then you could initialize your houses array as:

GameObject[] houses = InitializeArray<GameObject>(200);

How to check if a file exists in a folder?

Use FileInfo.Exists Property:

DirectoryInfo di = new DirectoryInfo(ProcessingDirectory);
FileInfo[] TXTFiles = di.GetFiles("*.xml");
if (TXTFiles.Length == 0)
{
    log.Info("no files present")
}
foreach (var fi in TXTFiles)
    log.Info(fi.Exists);

or File.Exists Method:

string curFile = @"c:\temp\test.txt";
Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");

Get Wordpress Category from Single Post

For the lazy and the learning, to put it into your theme, Rfvgyhn's full code

<?php $category = get_the_category();
$firstCategory = $category[0]->cat_name; echo $firstCategory;?>

Command CompileSwift failed with a nonzero exit code in Xcode 10

in my case the problem was due to watchkit extension being set to swift 3 while the main project's target was set to swift 4.2

Using multiprocessing.Process with a maximum number of simultaneous processes

more generally, this could also look like this:

import multiprocessing
def chunks(l, n):
    for i in range(0, len(l), n):
        yield l[i:i + n]

numberOfThreads = 4


if __name__ == '__main__':
    jobs = []
    for i, param in enumerate(params):
        p = multiprocessing.Process(target=f, args=(i,param))
        jobs.append(p)
    for i in chunks(jobs,numberOfThreads):
        for j in i:
            j.start()
        for j in i:
            j.join()

Of course, that way is quite cruel (since it waits for every process in a junk until it continues with the next chunk). Still it works well for approx equal run times of the function calls.

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

Apparently the error I got when trying to import pandas for the first time was ValueError: unknown locale: UTF-8

Trying to import again afterwards, gave another error as described in my question above.

I found the solution to solve the ValueError on IPython Notebook locale error

After updating my bash profile, the error AttributeError: module 'pandas' has no attribute 'core' did not appear anymore.

Multi-dimensional associative arrays in JavaScript

Javascript is flexible:

var arr = {
  "fred": {"apple": 2, "orange": 4},
  "mary": {}
  //etc, etc
};

alert(arr.fred.orange);
alert(arr["fred"]["orange"]);
for (key in arr.fred)
    alert(key + ": " + arr.fred[key]);

Visual c++ can't open include file 'iostream'

I had this exact same problem in VS 2015. It looks like as of VS 2010 and later you need to include #include "stdafx.h" in all your projects.

#include "stdafx.h"
#include <iostream>
using namespace std;

The above worked for me. The below did not:

#include <iostream>
using namespace std;

This also failed:

#include <iostream>
using namespace std;
#include "stdafx.h"

Python: How to create a unique file name?

To create a unique file path if its exist, use random package to generate a new string name for file. You may refer below code for same.

import os
import random
import string

def getUniquePath(folder, filename):    
    path = os.path.join(folder, filename)
    while os.path.exists(path):
         path = path.split('.')[0] + ''.join(random.choice(string.ascii_lowercase) for i in range(10)) + '.' + path.split('.')[1]
    return path

Now you can use this path to create file accordingly.

How to read file from res/raw by name

With the help of the given links I was able to solve the problem myself. The correct way is to get the resource ID with

getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
                             "raw", getPackageName());

To get it as a InputStream

InputStream ins = getResources().openRawResource(
            getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
            "raw", getPackageName()));

TSQL How do you output PRINT in a user defined function?

No, you can not.

You can call a function from a stored procedure and debug a stored procedure (this will step into the function)

XCOPY: Overwrite all without prompt in BATCH

The solution is the /Y switch:

xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y

socket programming multiple client to one server

Here is code for Multiple Client to one Server Working Fine .. Give it a try :)

Server.java:

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

class Multi extends Thread{
private Socket s=null;
DataInputStream infromClient;
Multi() throws IOException{


}
Multi(Socket s) throws IOException{
    this.s=s;
    infromClient = new DataInputStream(s.getInputStream());
}
public void run(){  

    String SQL=new String();
    try {
        SQL = infromClient.readUTF();
    } catch (IOException ex) {
        Logger.getLogger(Multi.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println("Query: " + SQL); 
    try {
        System.out.println("Socket Closing");
        s.close();
    } catch (IOException ex) {
        Logger.getLogger(Multi.class.getName()).log(Level.SEVERE, null, ex);
       }
   }  
}
public class Server {

public static void main(String args[]) throws IOException, 
InterruptedException{   

    while(true){
        ServerSocket ss=new ServerSocket(11111);
        System.out.println("Server is Awaiting"); 
        Socket s=ss.accept();
        Multi t=new Multi(s);
        t.start();

        Thread.sleep(2000);
        ss.close();
    }    




    }   
}

Client1.java:

 import java.io.DataOutputStream;
 import java.io.ObjectInputStream;
 import java.net.Socket;


public class client1 {
   public static void main(String[] arg) {
  try {

     Socket socketConnection = new Socket("127.0.0.1", 11111);


     //QUERY PASSING
     DataOutputStream outToServer = new DataOutputStream(socketConnection.getOutputStream());

     String SQL="I  am  client 1";
     outToServer.writeUTF(SQL);


  } catch (Exception e) {System.out.println(e); }
   }
}

Client2.java

import java.io.DataOutputStream; 
import java.net.Socket;


public class client2 {
    public static void main(String[] arg) {
  try {

     Socket socketConnection = new Socket("127.0.0.1", 11111);


     //QUERY PASSING
     DataOutputStream outToServer = new DataOutputStream(socketConnection.getOutputStream());

     String SQL="I am  Client 2";
     outToServer.writeUTF(SQL);


  } catch (Exception e) {System.out.println(e); }
   }
 }

WCF ServiceHost access rights

Another solution is to use the address

http://localhost:8732/Design_Time_Addresses/YOUR_ADDRESS .

.NET Framework (3.5) automatically register this address (http://*:8732/Design_Time_Addresses) for debugging scope. This is useful when you need to host services inside visual studio for debugging or testing. Don't use this on production...

Git mergetool generates unwanted .orig files

The option to save the .orig file can be disabled by configuring KDiff3

KDiff3 Backup file .orig option

Skip the headers when editing a csv file using Python

Doing row=1 won't change anything, because you'll just overwrite that with the results of the loop.

You want to do next(reader) to skip one row.

What is the correct JSON content type?

For JSON text:

application/json

The MIME media type for JSON text is application/json. The default encoding is UTF-8. (Source: RFC 4627).

For JSONP (runnable JavaScript) with callback:

application/javascript

Here are some blog posts that were mentioned in the relevant comments:

Math.random() versus Random.nextInt(int)

According to https://forums.oracle.com/forums/thread.jspa?messageID=6594485&#6594485 Random.nextInt(n) is both more efficient and less biased than Math.random() * n

SSRS Query execution failed for dataset

I had the similar issue showing the error

For more information about this error navigate to the report server on the local server machine, or enable remote errors Query execution failed for dataset 'PrintInvoice'.

Solution: 1) The error may be with the dataset in some cases, you can always check if the dataset is populating the exact data you are expecting by going to the dataset properties and choosing 'Query Designer' and try 'Run', If you can successfully able to pull the fields you are expecting, then you can be sure that there isn't any problem with the dataset, which takes us to next solution.

2) Even though the error message says "Query Failed Execution for the dataset", another probable chances are with the datasource connection, make sure you have connected to the correct datasource that has the tables you need and you have permissions to access that datasource.

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

CONNECTION_REFUSED is standard when the port is closed, but it could be rejected because SSL is failing authentication (one of a billion reasons). Did you configure SSL with Ratchet? (Apache is bypassed) Did you try without SSL in JavaScript?

I don't think Ratchet has built-in support for SSL. But even if it does you'll want to try the ws:// protocol first; it's a lot simpler, easier to debug, and closer to telnet. Chrome or the socket service may also be generating the REFUSED error if the service doesn't support SSL (because you explicitly requested SSL).

However the refused message is likely a server side problem, (usually port closed).

How to post data using HttpClient?

Use UploadStringAsync method:

WebClient webClient = new WebClient();
webClient.UploadStringCompleted += (s, e) =>
{
    if (e.Error != null)
    {
        //handle your error here
    }
    else
    {
        //post was successful, so do what you need to do here
    }
};

webClient.UploadStringAsync(new Uri(yourUri), UriKind.Absolute), "POST", yourParameters);     

How to search in an array with preg_match?

$items = array();
foreach ($haystacks as $haystack) {
    if (preg_match($pattern, $haystack, $matches)
        $items[] = $matches[1];
}

How to add an Android Studio project to GitHub

First of all, create a Github account and project in Github. Go to the root folder and follow steps.

The most important thing we forgot here is ignoring the file. Every time we run Gradle or build it creates new files that are changeable from build to build and pc to pc. We do not want all the files from Android Studio to be added to Git. Files like generated code, binary files (executables) should not be added to Git (version control). So please use .gitignore file while uploading projects to Github. It also reduces the size of the project uploaded to the server.

  1. Go to root folder.
  2. git init
  3. Create .gitignore txt file in root folder. Place these content in the file. (this step not required if the file is auto-generated)

    *.iml .gradle /local.properties /.idea/workspace.xml /.idea/libraries .idea .DS_Store /build /captures .externalNativeBuild

  4. git add .
  5. git remote add origin https://github.com/username/project.git
  6. git commit - m "My First Commit"
  7. git push -u origin master

Note : As per suggestion from different developers, they always suggest to use git from the command line. It is up to you.

Updating property value in properties file without deleting other values

You can use Apache Commons Configuration library. The best part of this is, it won't even mess up the properties file and keeps it intact (even comments).

Javadoc

PropertiesConfiguration conf = new PropertiesConfiguration("propFile.properties");
conf.setProperty("key", "value");
conf.save();    

What is the difference between DSA and RSA?

And in addition to the above nice answers.

  • DSA uses Discrete logarithm.
  • RSA uses Integer Factorization.

RSA stands for Ron Rivest, Adi Shamir and Leonard Adleman.

How to count items in JSON object using command line?

A simple solution is to install jshon library :

jshon -l < /tmp/test.json
2

How to parse XML to R data frame

You can try the code below:

# Load the packages required to read XML files.
library("XML")
library("methods")

# Convert the input xml file to a data frame.
xmldataframe <- xmlToDataFrame("input.xml")
print(xmldataframe)

The requested resource does not support HTTP method 'GET'

Please use the attributes from the System.Web.Http namespace on your WebAPI actions:

    [System.Web.Http.AcceptVerbs("GET", "POST")]
    [System.Web.Http.HttpGet]
    public string Auth(string username, string password)
    {...}

The reason why it doesn't work is because you were using the attributes that are from the MVC namespace System.Web.Mvc. The classes in the System.Web.Http namespace are for WebAPI.

add Shadow on UIView using swift 3

If you need rounded shadow. Works for swift 4.2

extension UIView {

        func dropShadow() {

            var shadowLayer: CAShapeLayer!
            let cornerRadius: CGFloat = 16.0
            let fillColor: UIColor = .white

            if shadowLayer == nil {
                shadowLayer = CAShapeLayer()

                shadowLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath
                shadowLayer.fillColor = fillColor.cgColor

                shadowLayer.shadowColor = UIColor.black.cgColor
                shadowLayer.shadowPath = shadowLayer.path
                shadowLayer.shadowOffset = CGSize(width: -2.0, height: 2.0)
                shadowLayer.shadowOpacity = 0.8
                shadowLayer.shadowRadius = 2

                layer.insertSublayer(shadowLayer, at: 0)
            }
        }
    }

Swift 4 rounded UIView with shadow

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

Setting this attribute to ObjectMapper instance works,

objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

iOS (iPhone, iPad, iPodTouch) view real-time console log terminal

Two options:

libimobiledevice is installable via homebrew and works great. Its idevicesyslog tool works similarly to deviceconsole (below), and it supports wirelessly viewing your device's syslog (!)

I've written more about that on Tumblr tl;dr:

brew install libimobiledevice
idevice_id --list // list available device UDIDs
idevicesyslog -u <device udid>

with the device connected via USB or available on the local wireless network.


(Keeping for the historical record, from 2013:) deviceconsole from rpetrich is a much less wacked-out solution than ideviceconsole above. My fork of it builds and runs in Xcode 5 out of the box, and the Build action will install the binary to /usr/local/bin for ease of use.

As an additional helpful bit of info, I use it in the following style which makes it easy to find the device I want in my shell history and removes unnecessary > lines that deviceconsole prints out.

deviceconsole -d -u <device UDID> | uniq -u && echo "<device name>"

Delete all duplicate rows Excel vba

The duplicate values in any column can be deleted with a simple for loop.

Sub remove()
Dim a As Long
For a = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
If WorksheetFunction.CountIf(Range("A1:A" & a), Cells(a, 1)) > 1 Then Rows(a).Delete
Next
End Sub

Alter a MySQL column to be AUTO_INCREMENT

Roman is right, but note that the auto_increment column must be part of the PRIMARY KEY or a UNIQUE KEY (and in almost 100% of the cases, it should be the only column that makes up the PRIMARY KEY):

ALTER TABLE document MODIFY document_id INT AUTO_INCREMENT PRIMARY KEY

How to make a radio button unchecked by clicking it?

Most of the modern day browsers consider checked="anything" as checked="true".

You might have to remove the checked attribute if that makes sense in your case, one of which might be related to when you load the page.

$(this).removeAttr('checked')

This might help you in cases when you want your radio button to be checked adhering to some condition. You can simply remove the attribute to achieve that.

PS: Not helpful in all the cases.

How to clear out session on log out

<script runat="server">  
    protected void Page_Load(object sender, System.EventArgs e) {  
        Session["FavoriteSoftware"] = "Adobe ColdFusion";  
        Label1.Text = "Session read...<br />";  
        Label1.Text += "Favorite Software : " + Session["FavoriteSoftware"];  
        Label1.Text += "<br />SessionID : " + Session.SessionID;  
        Label1.Text += "<br> Now clear the current session data.";  
        Session.Clear();  
        Label1.Text += "<br /><br />SessionID : " + Session.SessionID;  
        Label1.Text += "<br />Favorite Software[after clear]: " + Session["FavoriteSoftware"];  
    }  
</script>  



<html xmlns="http://www.w3.org/1999/xhtml">  
<head id="Head1" runat="server">  
    <title>asp.net session Clear example: how to clear the current session data (remove all the session items)</title>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <div>  
        <h2 style="color:Teal">asp.net session example: Session Clear</h2>  
        <asp:Label   
            ID="Label1"   
            runat="server"   
            Font-Size="Large"  
            ForeColor="DarkMagenta"  
            >  
        </asp:Label>  
    </div>  
    </form>  
</body>  
</html>  

How to display a list using ViewBag

To put it all together, this is what it should look like:

In the controller:

List<Fund> fundList = db.Funds.ToList();
ViewBag.Funds = fundList;

Then in the view:

@foreach (var item in ViewBag.Funds)
{
    <span> @item.FundName </span>
}

How do I set the size of an HTML text box?

If you don't want to use the class method you can use parent-child method to make changes in the text box.

For eg. I've made a form in my form div.

HTML Code:

<div class="form">
    <textarea name="message" rows="10" cols="30" >Describe your project in detail.</textarea>
</div>

Now CSS code will be like:

.form textarea {
    height: 220px;
    width: 342px;
}

Problem solved.

org.hibernate.MappingException: Unknown entity

In hibernate.cfg.xml , please put following code

<mapping class="class/bo name"/>

Compare dates in MySQL

That is SQL Server syntax for converting a date to a string. In MySQL you can use the DATE function to extract the date from a datetime:

SELECT *
FROM players
WHERE DATE(us_reg_date) BETWEEN '2000-07-05' AND '2011-11-10'

But if you want to take advantage of an index on the column us_reg_date you might want to try this instead:

SELECT *
FROM players
WHERE us_reg_date >= '2000-07-05'
  AND us_reg_date < '2011-11-10' + interval 1 day

node.js execute system command synchronously

I actually had a situation where I needed to run multiple commands one after another from a package.json preinstall script in a way that would work on both Windows and Linux/OSX, so I couldn't rely on a non-core module.

So this is what I came up with:

#cmds.coffee
childproc = require 'child_process'

exports.exec = (cmds) ->
  next = ->
    if cmds.length > 0
      cmd = cmds.shift()
      console.log "Running command: #{cmd}"
      childproc.exec cmd, (err, stdout, stderr) ->
        if err? then console.log err
        if stdout? then console.log stdout
        if stderr? then console.log stderr
        next()
    else
      console.log "Done executing commands."

  console.log "Running the follows commands:"
  console.log cmds
  next()

You can use it like this:

require('./cmds').exec ['grunt coffee', 'nodeunit test/tls-config.js']

EDIT: as pointed out, this doesn't actually return the output or allow you to use the result of the commands in a Node program. One other idea for that is to use LiveScript backcalls. http://livescript.net/

Detect page change on DataTable

Paging events are handled in this way,

 $(document).ready(function() {

    $('#example')
        .on( 'order.dt',  function () { console.log('Order' ); } )
        .on( 'search.dt', function () {console.log('Search' ); } )
        .on( 'page.dt',   function () { console.log('Page' ); } )
        .dataTable();
} );

documented in the official website, here http://www.datatables.net/examples/advanced_init/dt_events.html

The length.dt event is fired whenever the table's page length is changed

$('#example').dataTable();

$('#example').on( 'length.dt', function ( e, settings, len ) {
    console.log( 'New page length: '+len );
} );

http://datatables.net/reference/event/length

More events here

datatables.net/reference/event/

What does map(&:name) mean in Ruby?

tags.map(&:name)

is The same as

tags.map{|tag| tag.name}

&:name just uses the symbol as the method name to be called.

How do I kill all the processes in Mysql "show processlist"?

Here is a solution that you can execute without relying on the operating system:

STEP 1: Create a stored procedure.

DROP PROCEDURE IF EXISTS  kill_user_processes$$ 

CREATE PROCEDURE `kill_user_processes`(
  IN user_to_kill VARCHAR(255)
)
READS SQL DATA
BEGIN

  DECLARE name_val VARCHAR(255);
  DECLARE no_more_rows BOOLEAN;
  DECLARE loop_cntr INT DEFAULT 0;
  DECLARE num_rows INT DEFAULT 0;

  DECLARE friends_cur CURSOR FOR
    SELECT CONCAT('KILL ',id,';') FROM information_schema.processlist WHERE USER=user_to_kill;

  DECLARE CONTINUE HANDLER FOR NOT FOUND
    SET no_more_rows = TRUE;

  OPEN friends_cur;
  SELECT FOUND_ROWS() INTO num_rows;

  the_loop: LOOP

    FETCH  friends_cur
    INTO   name_val;

    IF no_more_rows THEN
        CLOSE friends_cur;
        LEAVE the_loop;
    END IF;


 SET @s = name_val;
    PREPARE stmt FROM @s;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

    SELECT name_val;

    SET loop_cntr = loop_cntr + 1;

  END LOOP the_loop;

  SELECT num_rows, loop_cntr;

END $$
DELIMITER ;

STEP 2: Call the stored procedure giving it the name of a database user whose processes you want to kill. You could rewrite the stored procedure to filter on some other criteria if you like.

CALL kill_user_processes('devdba');

ExecuteReader: Connection property has not been initialized

You can also write this:

SqlCommand cmd=new SqlCommand ("insert into time(project,iteration) values (@project, @iteration)", conn);
cmd.Parameters.AddWithValue("@project",name1.SelectedValue);
cmd.Parameters.AddWithValue("@iteration",iteration.SelectedValue);

Linking a qtDesigner .ui file to python/pyqt?

You can also use uic in PyQt5 with the following code.

from PyQt5 import uic, QtWidgets
import sys

class Ui(QtWidgets.QDialog):
    def __init__(self):
        super(Ui, self).__init__()
        uic.loadUi('SomeUi.ui', self)
        self.show()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = Ui()
    sys.exit(app.exec_())

Import Maven dependencies in IntelliJ IDEA

Deleting the .idea folder from the project directory, and then re-importing the project as a Maven project is what worked for me.

Loop through each cell in a range of cells when given a Range object

You could use Range.Rows, Range.Columns or Range.Cells. Each of these collections contain Range objects.

Here's how you could modify Dick's example so as to work with Rows:

Sub LoopRange()

    Dim rCell As Range
    Dim rRng As Range

    Set rRng = Sheet1.Range("A1:A6")

    For Each rCell In rRng.Rows
        Debug.Print rCell.Address, rCell.Value
    Next rCell

End Sub

And Columns:

Sub LoopRange()

    Dim rCell As Range
    Dim rRng As Range

    Set rRng = Sheet1.Range("A1:A6")

    For Each rCol In rRng.Columns
        For Each rCell In rCol.Rows
            Debug.Print rCell.Address, rCell.Value
        Next rCell
    Next rCol

End Sub

Service Reference Error: Failed to generate code for the service reference

Restarting Visual Studio did the trick for me. I am using VS 2015.

How do I sort a VARCHAR column in SQL server that contains numbers?

SELECT FIELD FROM TABLE
ORDER BY 
  isnumeric(FIELD) desc, 
  CASE ISNUMERIC(test) 
    WHEN 1 THEN CAST(CAST(test AS MONEY) AS INT)
    ELSE NULL 
  END,
  FIELD

As per this link you need to cast to MONEY then INT to avoid ordering '$' as a number.