Programs & Examples On #Python ldap

python-ldap provides an object-oriented API to access LDAP directory servers from Python programs

I can't install python-ldap

On CentOS/RHEL 6, you need to install:

sudo yum install python-devel
sudo yum install openldap-devel

and yum will also install cyrus-sasl-devel as a dependency. Then you can run:

pip-2.7 install python-ldap

Closing Twitter Bootstrap Modal From Angular Controller

Here's a reusable Angular directive that will hide and show a Bootstrap modal.

app.directive("modalShow", function () {
    return {
        restrict: "A",
        scope: {
            modalVisible: "="
        },
        link: function (scope, element, attrs) {

            //Hide or show the modal
            scope.showModal = function (visible) {
                if (visible)
                {
                    element.modal("show");
                }
                else
                {
                    element.modal("hide");
                }
            }

            //Check to see if the modal-visible attribute exists
            if (!attrs.modalVisible)
            {

                //The attribute isn't defined, show the modal by default
                scope.showModal(true);

            }
            else
            {

                //Watch for changes to the modal-visible attribute
                scope.$watch("modalVisible", function (newValue, oldValue) {
                    scope.showModal(newValue);
                });

                //Update the visible value when the dialog is closed through UI actions (Ok, cancel, etc.)
                element.bind("hide.bs.modal", function () {
                    scope.modalVisible = false;
                    if (!scope.$$phase && !scope.$root.$$phase)
                        scope.$apply();
                });

            }

        }
    };

});

Usage Example #1 - this assumes you want to show the modal - you could add ng-if as a condition

<div modal-show class="modal fade"> ...bootstrap modal... </div>

Usage Example #2 - this uses an Angular expression in the modal-visible attribute

<div modal-show modal-visible="showDialog" class="modal fade"> ...bootstrap modal... </div>

Another Example - to demo the controller interaction, you could add something like this to your controller and it will show the modal after 2 seconds and then hide it after 5 seconds.

$scope.showDialog = false;
$timeout(function () { $scope.showDialog = true; }, 2000)
$timeout(function () { $scope.showDialog = false; }, 5000)

I'm late to contribute to this question - created this directive for another question here. Simple Angular Directive for Bootstrap Modal

Hope this helps.

New to unit testing, how to write great tests?

It's worth noting that retro-fitting unit tests into existing code is far more difficult than driving the creation of that code with tests in the first place. That's one of the big questions in dealing with legacy applications... how to unit test? This has been asked many times before (so you may be closed as a dupe question), and people usually end up here:

Moving existing code to Test Driven Development

I second the accepted answer's book recommendation, but beyond that there's more information linked in the answers there.

How to get element by class name?

The name of the DOM function is actually getElementsByClassName, not getElementByClassName, simply because more than one element on the page can have the same class, hence: Elements.

The return value of this will be a NodeList instance, or a superset of the NodeList (FF, for instance returns an instance of HTMLCollection). At any rate: the return value is an array-like object:

var y = document.getElementsByClassName('foo');
var aNode = y[0];

If, for some reason you need the return object as an array, you can do that easily, because of its magic length property:

var arrFromList = Array.prototype.slice.call(y);
//or as per AntonB's comment:
var arrFromList = [].slice.call(y);

As yckart suggested querySelector('.foo') and querySelectorAll('.foo') would be preferable, though, as they are, indeed, better supported (93.99% vs 87.24%), according to caniuse.com:

“Origin null is not allowed by Access-Control-Allow-Origin” error for request made by application running from a file:// URL

In my case, same code worked fine on Firefox, but not on Google Chrome. Google Chrome's JavaScript console said:

XMLHttpRequest cannot load http://www.xyz.com/getZipInfo.php?zip=11234. 
Origin http://xyz.com is not allowed by Access-Control-Allow-Origin.
Refused to get unsafe header "X-JSON"

I had to drop the www part of the Ajax URL for it to match correctly with the origin URL and it worked fine then.

How to create an array of object literals in a loop?

var arr = [];
var len = oFullResponse.results.length;
for (var i = 0; i < len; i++) {
    arr.push({
        key: oFullResponse.results[i].label,
        sortable: true,
        resizeable: true
    });
}

How to update single value inside specific array item in redux

I believe when you need this kinds of operations on your Redux state the spread operator is your friend and this principal applies for all children.

Let's pretend this is your state:

const state = {
    houses: {
        gryffindor: {
          points: 15
        },
        ravenclaw: {
          points: 18
        },
        hufflepuff: {
          points: 7
        },
        slytherin: {
          points: 5
        }
    }
}

And you want to add 3 points to Ravenclaw

const key = "ravenclaw";
  return {
    ...state, // copy state
    houses: {
      ...state.houses, // copy houses
      [key]: {  // update one specific house (using Computed Property syntax)
        ...state.houses[key],  // copy that specific house's properties
        points: state.houses[key].points + 3   // update its `points` property
      }
    }
  }

By using the spread operator you can update only the new state leaving everything else intact.

Example taken from this amazing article, you can find almost every possible option with great examples.

Print a list in reverse order with range()?

No sense to use reverse because the range method can return reversed list.

When you have iteration over n items and want to replace order of list returned by range(start, stop, step) you have to use third parameter of range which identifies step and set it to -1, other parameters shall be adjusted accordingly:

  1. Provide stop parameter as -1(it's previous value of stop - 1, stop was equal to 0).
  2. As start parameter use n-1.

So equivalent of range(n) in reverse order would be:

n = 10
print range(n-1,-1,-1) 
#[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Python & Matplotlib: Make 3D plot interactive in Jupyter Notebook

try:

%matplotlib notebook

see jakevdp reply here

EDIT for JupyterLab users:

Follow the instructions to install jupyter-matplotlib

Then the magic command above is no longer needed, as in the example:

# Enabling the `widget` backend.
# This requires jupyter-matplotlib a.k.a. ipympl.
# ipympl can be install via pip or conda.
%matplotlib widget
# aka import ipympl

import matplotlib.pyplot as plt

plt.plot([0, 1, 2, 2])
plt.show()

Finally, note Maarten Breddels' reply; IMHO ipyvolume is indeed very impressive (and useful!).

URL.Action() including route values

You also can use in this form:

<a href="@Url.Action("Information", "Admin", null)"> Admin</a>

Git pull after forced update

To receive the new commits

git fetch

Reset

You can reset the commit for a local branch using git reset.

To change the commit of a local branch:

git reset origin/master --hard

Be careful though, as the documentation puts it:

Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded.

If you want to actually keep whatever changes you've got locally - do a --soft reset instead. Which will update the commit history for the branch, but not change any files in the working directory (and you can then commit them).

Rebase

You can replay your local commits on top of any other commit/branch using git rebase:

git rebase -i origin/master

This will invoke rebase in interactive mode where you can choose how to apply each individual commit that isn't in the history you are rebasing on top of.

If the commits you removed (with git push -f) have already been pulled into the local history, they will be listed as commits that will be reapplied - they would need to be deleted as part of the rebase or they will simply be re-included into the history for the branch - and reappear in the remote history on the next push.

Use the help git command --help for more details and examples on any of the above (or other) commands.

Passing vector by reference

If you define your function to take argument of std::vector<int>& arr and integer value, then you can use push_back inside that function:

void do_something(int el, std::vector<int>& arr)
{
    arr.push_back(el);
    //....
}

usage:

std::vector<int> arr;
do_something(1, arr); 

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

How can I select all rows with sqlalchemy?

You can easily import your model and run this:

from models import User

# User is the name of table that has a column name
users = User.query.all()

for user in users:
    print user.name

C# Example of AES256 encryption using System.Security.Cryptography.Aes

Maybe this example listed here can help you out. Statement from the author

about 24 lines of code to encrypt, 23 to decrypt

Due to the fact that the link in the original posting is dead - here the needed code parts (c&p without any change to the original source)

  /*
  Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
  
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.*/
   
  #region Usings
  using System;
  using System.IO;
  using System.Security.Cryptography;
  using System.Text;
  #endregion
   
  namespace Utilities.Encryption
  {
      /// <summary>
      /// Utility class that handles encryption
      /// </summary>
      public static class AESEncryption
      {
          #region Static Functions
   
          /// <summary>
          /// Encrypts a string
          /// </summary>
          /// <param name="PlainText">Text to be encrypted</param>
          /// <param name="Password">Password to encrypt with</param>
          /// <param name="Salt">Salt to encrypt with</param>
          /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
          /// <param name="PasswordIterations">Number of iterations to do</param>
          /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
          /// <param name="KeySize">Can be 128, 192, or 256</param>
          /// <returns>An encrypted string</returns>
          public static string Encrypt(string PlainText, string Password,
              string Salt = "Kosher", string HashAlgorithm = "SHA1",
              int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
              int KeySize = 256)
          {
              if (string.IsNullOrEmpty(PlainText))
                  return "";
              byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
              byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
              byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
              PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
              byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
              RijndaelManaged SymmetricKey = new RijndaelManaged();
              SymmetricKey.Mode = CipherMode.CBC;
              byte[] CipherTextBytes = null;
              using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
              {
                  using (MemoryStream MemStream = new MemoryStream())
                  {
                      using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                      {
                          CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                          CryptoStream.FlushFinalBlock();
                          CipherTextBytes = MemStream.ToArray();
                          MemStream.Close();
                          CryptoStream.Close();
                      }
                  }
              }
              SymmetricKey.Clear();
              return Convert.ToBase64String(CipherTextBytes);
          }
   
          /// <summary>
          /// Decrypts a string
          /// </summary>
          /// <param name="CipherText">Text to be decrypted</param>
          /// <param name="Password">Password to decrypt with</param>
          /// <param name="Salt">Salt to decrypt with</param>
          /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
          /// <param name="PasswordIterations">Number of iterations to do</param>
          /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
          /// <param name="KeySize">Can be 128, 192, or 256</param>
          /// <returns>A decrypted string</returns>
          public static string Decrypt(string CipherText, string Password,
              string Salt = "Kosher", string HashAlgorithm = "SHA1",
              int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
              int KeySize = 256)
          {
              if (string.IsNullOrEmpty(CipherText))
                  return "";
              byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
              byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
              byte[] CipherTextBytes = Convert.FromBase64String(CipherText);
              PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
              byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
              RijndaelManaged SymmetricKey = new RijndaelManaged();
              SymmetricKey.Mode = CipherMode.CBC;
              byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
              int ByteCount = 0;
              using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
              {
                  using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
                  {
                      using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                      {
   
                          ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                          MemStream.Close();
                          CryptoStream.Close();
                      }
                  }
              }
              SymmetricKey.Clear();
              return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
          }
   
          #endregion
      }
  }

Create a tag in a GitHub repository

Using Sourcetree

Here are the simple steps to create a GitHub Tag, when you release build from master.

  1. Open source_tree tab

    step 1

  2. Right click on Tag sections from Tag which appear on left navigation section

    step 2

  3. Click on New Tag()

  4. A dialog appears to Add Tag and Remove Tag
  5. Click on Add Tag from give name to tag (preferred version name of the code)

    step 3

  6. If you want to push the TAG on remote, while creating the TAG ref: step 5 which gives checkbox push TAG to origin check it and pushed tag appears on remote repository

  7. In case while creating the TAG if you have forgotten to check the box Push to origin, you can do it later by right-clicking on the created TAG, click on Push to origin. enter image description here

How to remove all ListBox items?

while (listBox1.Items.Count > 0){ 
    listBox1.Items.Remove(0);
}

How many bytes in a JavaScript string?

These are 3 ways I use:

  1. TextEncoder
new TextEncoder().encode("myString").length
  1. Blob
new Blob(["myString"]).size
  1. Buffer
Buffer.byteLength("myString", 'utf8')

Automatically capture output of last command into a variable using Bash?

I don't know of any variable that does this automatically. To do something aside from just copy-pasting the result, you can re-run whatever you just did, eg

vim $(!!)

Where !! is history expansion meaning 'the previous command'.

If you expect there to be a single filename with spaces or other characters in it that might prevent proper argument parsing, quote the result (vim "$(!!)"). Leaving it unquoted will allow multiple files to be opened at once as long as they don't include spaces or other shell parsing tokens.

.gitignore and "The following untracked working tree files would be overwritten by checkout"

Warning: This will delete the local files that are not indexed

Just force it : git checkout -f another-branch

using if else with eval in aspx page

<%# (string)Eval("gender") =="M" ? "Male" :"Female"%>

How to add a local repo and treat it as a remote repo

If your goal is to keep a local copy of the repository for easy backup or for sticking onto an external drive or sharing via cloud storage (Dropbox, etc) you may want to use a bare repository. This allows you to create a copy of the repository without a working directory, optimized for sharing.

For example:

$ git init --bare ~/repos/myproject.git
$ cd /path/to/existing/repo
$ git remote add origin ~/repos/myproject.git
$ git push origin master

Similarly you can clone as if this were a remote repo:

$ git clone ~/repos/myproject.git

How to convert between bytes and strings in Python 3?

In python3, there is a bytes() method that is in the same format as encode().

str1 = b'hello world'
str2 = bytes("hello world", encoding="UTF-8")
print(str1 == str2) # Returns True

I didn't read anything about this in the docs, but perhaps I wasn't looking in the right place. This way you can explicitly turn strings into byte streams and have it more readable than using encode and decode, and without having to prefex b in front of quotes.

jQuery's .on() method combined with the submit event

The problem here is that the "on" is applied to all elements that exists AT THE TIME. When you create an element dynamically, you need to run the on again:

$('form').on('submit',doFormStuff);

createNewForm();

// re-attach to all forms
$('form').off('submit').on('submit',doFormStuff);

Since forms usually have names or IDs, you can just attach to the new form as well. If I'm creating a lot of dynamic stuff, I'll include a setup or bind function:

function bindItems(){
    $('form').off('submit').on('submit',doFormStuff); 
    $('button').off('click').on('click',doButtonStuff);
}   

So then whenever you create something (buttons usually in my case), I just call bindItems to update everything on the page.

createNewButton();
bindItems();

I don't like using 'body' or document elements because with tabs and modals they tend to hang around and do things you don't expect. I always try to be as specific as possible unless its a simple 1 page project.

Possible to change where Android Virtual Devices are saved?

Please take note of the following : modifying android.bat in the Android tools directory, as suggested in a previous answer, may lead to problems.

If you do so, in order to legitimately have your .android directory located to a non-default location then there may be an inconsistency between the AVDs listed by Android Studio (using "Tools > Android > AVD Manager") and the AVDs listed by sdk command line tool "android avd".

I suppose that Android Studio, with its internal AVD Manager, does not use the android.bat modified path ; it relies on the ANDROID_SDK_HOME variable to locate AVDs.

My own tests have shown that Android tools correctly use the ANDROID_SDK_HOME variable.

Therefore, there is no point, as far as I know, in modifying android.bat, and using the environment variable should be preferred.

How to find a hash key containing a matching value

Another approach I would try is by using #map

clients.map{ |key, _| key if clients[key] == {"client_id"=>"2180"} }.compact 
#=> ["orange"]

This will return all occurences of given value. The underscore means that we don't need key's value to be carried around so that way it's not being assigned to a variable. The array will contain nils if the values doesn't match - that's why I put #compact at the end.

Convert String with Dot or Comma as decimal separator to number in JavaScript

Here's a self-sufficient JS function that solves this (and other) problems for most European/US locales (primarily between US/German/Swedish number chunking and formatting ... as in the OP). I think it's an improvement on (and inspired by) Slawa's solution, and has no dependencies.

function realParseFloat(s)
{
    s = s.replace(/[^\d,.-]/g, ''); // strip everything except numbers, dots, commas and negative sign
    if (navigator.language.substring(0, 2) !== "de" && /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(s)) // if not in German locale and matches #,###.######
    {
        s = s.replace(/,/g, ''); // strip out commas
        return parseFloat(s); // convert to number
    }
    else if (/^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(s)) // either in German locale or not match #,###.###### and now matches #.###,########
    {
        s = s.replace(/\./g, ''); // strip out dots
        s = s.replace(/,/g, '.'); // replace comma with dot
        return parseFloat(s);
    }
    else // try #,###.###### anyway
    {
        s = s.replace(/,/g, ''); // strip out commas
        return parseFloat(s); // convert to number
    }
}

Difference between SelectedItem, SelectedValue and SelectedValuePath

inspired by this question I have written a blog along with the code snippet here. Below are some of the excerpts from the blog

SelectedItem – Selected Item helps to bind the actual value from the DataSource which will be displayed. This is of type object and we can bind any type derived from object type with this property. Since we will be using the MVVM binding for our combo boxes in that case this is the property which we can use to notify VM that item has been selected.

SelectedValue and SelectedValuePath – These are the two most confusing and misinterpreted properties for combobox. But these properties come to rescue when we want to bind our combobox with the value from already created object. Please check my last scenario in the following list to get a brief idea about the properties.

Serializing and submitting a form with jQuery and PHP

 $("#contactForm").submit(function() {

    $.post(url, $.param($(this).serializeArray()), function(data) {

    });
 });

Create a global variable in TypeScript

I needed to make lodash global to use an existing .js file that I could not change, only require.

I found that this worked:

import * as lodash from 'lodash';

(global as any)._ = lodash;

How to set DataGrid's row Background, based on a property value using data bindings

In XAML, add and define a RowStyle Property for the DataGrid with a goal to set the Background of the Row, to the Color defined in my Employee Object.

<DataGrid AutoGenerateColumns="False" ItemsSource="EmployeeList">
   <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
             <Setter Property="Background" Value="{Binding ColorSet}"/>
        </Style>
   </DataGrid.RowStyle>

And in my Employee Class

public class Employee {

    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

    public string ColorSet { get; set; }

    public Employee() { }

    public Employee(int id, string name, int age)
    {
        Id = id;
        Name = name;
        Age = age;
        if (Age > 50)
        {
            ColorSet = "Green";
        }
        else if (Age > 100)
        {
            ColorSet = "Red";
        }
        else
        {
            ColorSet = "White";
        }
    }
}

This way every Row of the DataGrid has the BackGround Color of the ColorSet Property of my Object.

How to copy files from host to Docker container?

The best way for copying files to the container I found is mounting a directory on host using -v option of docker run command.

Convert Mongoose docs to json

You may also try mongoosejs's lean() :

UserModel.find().lean().exec(function (err, users) {
    return res.end(JSON.stringify(users));
}

Bulk Record Update with SQL

Or you can simply update without using join like this:

Update t1 set  t1.Description = t2.Description from @tbl2 t2,tbl1 t1
where t1.ID= t2.ID

Bootstrap table without stripe / borders

Use the border- class from Boostrap 4

<td class="border-0"></td>

or

<table class='table border-0'></table>

Be sure to end the class input with the last change you want to do.

How can I set the default timezone in node.js?

You could enforce the Node.js process timezone by setting the environment variable TZ to UTC

So all time will be measured in UTC+00:00

Full list: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

Example package.json:

{
  "scripts": {
    "start": "TZ='UTC' node index.js"
  }
}

TypeError: '<=' not supported between instances of 'str' and 'int'

Change

vote = input('Enter the name of the player you wish to vote for')

to

vote = int(input('Enter the name of the player you wish to vote for'))

You are getting the input from the console as a string, so you must cast that input string to an int object in order to do numerical operations.

Delete keychain items when an app is uninstalled

For users looking for a Swift 3.0 version of @amro's answer:

let userDefaults = UserDefaults.standard

if !userDefaults.bool(forKey: "hasRunBefore") {
     // Remove Keychain items here

     // Update the flag indicator
     userDefaults.set(true, forKey: "hasRunBefore")
}

*note that synchronize() function is deprecated

Python: How to ignore an exception and proceed?

Try this:

try:
    blah()
except:
    pass

check all socket opened in linux OS

You can use netstat command

netstat --listen

To display open ports and established TCP connections,

netstat -vatn

To display only open UDP ports try the following command:

netstat -vaun

Convert a String to a byte array and then back to the original String

I would suggest using the members of string, but with an explicit encoding:

byte[] bytes = text.getBytes("UTF-8");
String text = new String(bytes, "UTF-8");

By using an explicit encoding (and one which supports all of Unicode) you avoid the problems of just calling text.getBytes() etc:

  • You're explicitly using a specific encoding, so you know which encoding to use later, rather than relying on the platform default.
  • You know it will support all of Unicode (as opposed to, say, ISO-Latin-1).

EDIT: Even though UTF-8 is the default encoding on Android, I'd definitely be explicit about this. For example, this question only says "in Java or Android" - so it's entirely possible that the code will end up being used on other platforms.

Basically given that the normal Java platform can have different default encodings, I think it's best to be absolutely explicit. I've seen way too many people using the default encoding and losing data to take that risk.

EDIT: In my haste I forgot to mention that you don't have to use the encoding's name - you can use a Charset instead. Using Guava I'd really use:

byte[] bytes = text.getBytes(Charsets.UTF_8);
String text = new String(bytes, Charsets.UTF_8);

Build error: "The process cannot access the file because it is being used by another process"

Deleting Obj, retail and debug folder of the .NET project and re-building again worked for me.

Efficiently getting all divisors of a given number

Here's my code:

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>

using namespace std;

#define pii pair<int, int>

#define MAX 46656
#define LMT 216
#define LEN 4830
#define RNG 100032

unsigned base[MAX / 64], segment[RNG / 64], primes[LEN];

#define sq(x) ((x)*(x))
#define mset(x,v) memset(x,v,sizeof(x))
#define chkC(x,n) (x[n>>6]&(1<<((n>>1)&31)))
#define setC(x,n) (x[n>>6]|=(1<<((n>>1)&31)))

// http://zobayer.blogspot.com/2009/09/segmented-sieve.html
void sieve()
{
    unsigned i, j, k;
    for (i = 3; i<LMT; i += 2)
        if (!chkC(base, i))
            for (j = i*i, k = i << 1; j<MAX; j += k)
                setC(base, j);
    primes[0] = 2;
    for (i = 3, j = 1; i<MAX; i += 2)
        if (!chkC(base, i))
            primes[j++] = i;
}


//http://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/
vector <pii> factors;
void primeFactors(int num)
{
    int expo = 0;   
    for (int i = 0; primes[i] <= sqrt(num); i++)
    {
        expo = 0;
        int prime = primes[i];
        while (num % prime == 0){
            expo++;
            num = num / prime;
        }
        if (expo>0)
            factors.push_back(make_pair(prime, expo));
    }

    if ( num >= 2)
        factors.push_back(make_pair(num, 1));

}

vector <int> divisors;
void setDivisors(int n, int i) {
    int j, x, k;
    for (j = i; j<factors.size(); j++) {
        x = factors[j].first * n;
        for (k = 0; k<factors[j].second; k++) {
            divisors.push_back(x);
            setDivisors(x, j + 1);
            x *= factors[j].first;
        }
    }
}

int main() {

    sieve();
    int n, x, i; 
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> x;
        primeFactors(x);
        setDivisors(1, 0);
        divisors.push_back(1);
        sort(divisors.begin(), divisors.end());
        cout << divisors.size() << "\n";
        for (int j = 0; j < divisors.size(); j++) {
            cout << divisors[j] << " "; 
        }
        cout << "\n";
        divisors.clear();
        factors.clear();
    }
}

The first part, sieve() is used to find the prime numbers and put them in primes[] array. Follow the link to find more about that code (bitwise sieve).

The second part primeFactors(x) takes an integer (x) as input and finds out its prime factors and corresponding exponent, and puts them in vector factors[]. For example, primeFactors(12) will populate factors[] in this way:

factors[0].first=2, factors[0].second=2
factors[1].first=3, factors[1].second=1

as 12 = 2^2 * 3^1

The third part setDivisors() recursively calls itself to calculate all the divisors of x, using the vector factors[] and puts them in vector divisors[].

It can calculate divisors of any number which fits in int. Also it is quite fast.

Can anyone recommend a simple Java web-app framework?

I would think to stick with JSP, servlets and JSTL After more than 12 years dealing with web frameworks in several companies I worked with, I always find my self go back to good old JSP. Yes there are some things you need to write yourself that some frameworks do automatically. But if you approach it correctly, and build some basic utils on top of your servlets, it gives the best flexibility and you can do what ever you want easily. I did not find real advantages to write in any of the frameworks. And I keep looking.

Looking at all the answers above also means that there is no real one framework that is good and rules.

How to set IE11 Document mode to edge as default?

I ran into this problem with a particular webpage I was maintaining. No matter what settings I changed, it kept going back to IE8 compatibility mode.

It turned out X-UA-Compatible was set in the metadata in the head:

<meta http-equiv="X-UA-Compatible" content="IE=8" >

As I later discovered, and at least in Internet Explorer 11, you can see where it gets its "document mode" from, by going into developer tools (F12), then selecting the tab "Emulation", and checking the text below the drop down "Document mode".

Since we only support IE11 and higher, and Microsoft says document modes are deprecated, I just threw the whole thing out. That solved it.

Set up Python simpleHTTPserver on Windows

From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":

The following works for me:

python -m http.server [<portNo>]

Because I am using Python 3 the module SimpleHTTPServer has been replaced by http.server, at least in Windows.

How can I group data with an Angular filter?

In addition to the accepted answers above I created a generic 'groupBy' filter using the underscore.js library.

JSFiddle (updated): http://jsfiddle.net/TD7t3/

The filter

app.filter('groupBy', function() {
    return _.memoize(function(items, field) {
            return _.groupBy(items, field);
        }
    );
});

Note the 'memoize' call. This underscore method caches the result of the function and stops angular from evaluating the filter expression every time, thus preventing angular from reaching the digest iterations limit.

The html

<ul>
    <li ng-repeat="(team, players) in teamPlayers | groupBy:'team'">
        {{team}}
        <ul>
            <li ng-repeat="player in players">
                {{player.name}}
            </li>
        </ul>
    </li>
</ul>

We apply our 'groupBy' filter on the teamPlayers scope variable, on the 'team' property. Our ng-repeat receives a combination of (key, values[]) that we can use in our following iterations.

Update June 11th 2014 I expanded the group by filter to account for the use of expressions as the key (eg nested variables). The angular parse service comes in quite handy for this:

The filter (with expression support)

app.filter('groupBy', function($parse) {
    return _.memoize(function(items, field) {
        var getter = $parse(field);
        return _.groupBy(items, function(item) {
            return getter(item);
        });
    });
});

The controller (with nested objects)

app.controller('homeCtrl', function($scope) {
    var teamAlpha = {name: 'team alpha'};
    var teamBeta = {name: 'team beta'};
    var teamGamma = {name: 'team gamma'};

    $scope.teamPlayers = [{name: 'Gene', team: teamAlpha},
                      {name: 'George', team: teamBeta},
                      {name: 'Steve', team: teamGamma},
                      {name: 'Paula', team: teamBeta},
                      {name: 'Scruath of the 5th sector', team: teamGamma}];
});

The html (with sortBy expression)

<li ng-repeat="(team, players) in teamPlayers | groupBy:'team.name'">
    {{team}}
    <ul>
        <li ng-repeat="player in players">
            {{player.name}}
        </li>
    </ul>
</li>

JSFiddle: http://jsfiddle.net/k7fgB/2/

How to set initial value and auto increment in MySQL?

MySQL Workbench

If you want to avoid writing sql, you can also do it in MySQL Workbench by right clicking on the table, choose "Alter Table ..." in the menu.

When the table structure view opens, go to tab "Options" (on the lower bottom of the view), and set "Auto Increment" field to the value of the next autoincrement number.

Don't forget to hit "Apply" when you are done with all changes.

PhpMyAdmin:

If you are using phpMyAdmin, you can click on the table in the lefthand navigation, go to the tab "Operations" and under Table Options change the AUTO_INCREMENT value and click OK.

Groovy String to Date

JChronic is your best choice. Here's an example that adds a .fromString() method to the Date class that parses just about anything you can throw at it:

Date.metaClass.'static'.fromString = { str ->
    com.mdimension.jchronic.Chronic.parse(str).beginCalendar.time
}

You can call it like this:

println Date.fromString("Tue Aug 10 16:02:43 PST 2010")
println Date.fromString("july 1, 2012")
println Date.fromString("next tuesday")

What data type to use in MySQL to store images?

What you need, according to your comments, is a 'BLOB' (Binary Large OBject) for both image and resume.

Matching an optional substring in a regex

(\d+)\s+(\(.*?\))?\s?Z

Note the escaped parentheses, and the ? (zero or once) quantifiers. Any of the groups you don't want to capture can be (?: non-capture groups).

I agree about the spaces. \s is a better option there. I also changed the quantifier to insure there are digits at the beginning. As far as newlines, that would depend on context: if the file is parsed line by line it won't be a problem. Another option is to anchor the start and end of the line (add a ^ at the front and a $ at the end).

Bootstrap 4 - Responsive cards in card-columns

Update 2019 - Bootstrap 4

You can simply use the SASS mixin to change the number of cards across in each breakpoint / grid tier.

.card-columns {
  @include media-breakpoint-only(xl) {
    column-count: 5;
  }
  @include media-breakpoint-only(lg) {
    column-count: 4;
  }
  @include media-breakpoint-only(md) {
    column-count: 3;
  }
  @include media-breakpoint-only(sm) {
    column-count: 2;
  }
}

SASS Demo: http://www.codeply.com/go/FPBCQ7sOjX

Or, CSS only like this...

@media (min-width: 576px) {
    .card-columns {
        column-count: 2;
    }
}

@media (min-width: 768px) {
    .card-columns {
        column-count: 3;
    }
}

@media (min-width: 992px) {
    .card-columns {
        column-count: 4;
    }
}

@media (min-width: 1200px) {
    .card-columns {
        column-count: 5;
    }
}

CSS-only Demo: https://www.codeply.com/go/FIqYTyyWWZ

Create a list from two object lists with linq

There are a few pieces to doing this, assuming each list does not contain duplicates, Name is a unique identifier, and neither list is ordered.

First create an append extension method to get a single list:

static class Ext {
  public static IEnumerable<T> Append(this IEnumerable<T> source,
                                      IEnumerable<T> second) {
    foreach (T t in source) { yield return t; }
    foreach (T t in second) { yield return t; }
  }
}

Thus can get a single list:

var oneList = list1.Append(list2);

Then group on name

var grouped = oneList.Group(p => p.Name);

Then can process each group with a helper to process one group at a time

public Person MergePersonGroup(IGrouping<string, Person> pGroup) {
  var l = pGroup.ToList(); // Avoid multiple enumeration.
  var first = l.First();
  var result = new Person {
    Name = first.Name,
    Value = first.Value
  };
  if (l.Count() == 1) {
    return result;
  } else if (l.Count() == 2) {
    result.Change = first.Value - l.Last().Value;
    return result;
  } else {
    throw new ApplicationException("Too many " + result.Name);
  }
}

Which can be applied to each element of grouped:

var finalResult = grouped.Select(g => MergePersonGroup(g));

(Warning: untested.)

Git Diff with Beyond Compare

Update for BC4 64bit: This works for Git for Windows v.2.16.2 and Beyond Compare 4 - v.4.2.4 (64bit Edition)

I manually edited the .gitconfig file located in my user root "C:\Users\MyUserName" and replaced the diff/difftool and merge/mergetool tags with

[diff]
  tool = bc
[difftool "bc"]
  path = 'C:/Program Files/Beyond Compare 4/BComp.exe'
[difftool "bc"]
  cmd = \"C:/Program Files/Beyond Compare 4/BComp.exe\" \"$LOCAL\" \"$REMOTE\"
[difftool]
  prompt = false
[merge]
  tool = bc
[mergetool "bc"]
  path = 'C:/Program Files/Beyond Compare 4/BComp.exe'
[mergetool "bc"]
  cmd = \"C:/Program Files/Beyond Compare 4/BComp.exe\" \"$REMOTE\" \"$LOCAL\" \"$BASE\" \"$MERGED\"

How to find out if you're using HTTPS without $_SERVER['HTTPS']

The only reliable method is the one described by Igor M.

$pv_URIprotocol = isset($_SERVER["HTTPS"]) ? (($_SERVER["HTTPS"]==="on" || $_SERVER["HTTPS"]===1 || $_SERVER["SERVER_PORT"]===$pv_sslport) ? "https://" : "http://") :  (($_SERVER["SERVER_PORT"]===$pv_sslport) ? "https://" : "http://");

Consider following: You are using nginx with fastcgi, by default(debian, ubuntu) fastgi_params contain directive:

fastcgi_param HTTPS $https;

if you are NOT using SSL, it gets translated as empty value, not 'off', not 0 and you are doomed.

http://unpec.blogspot.cz/2013/01/nette-nginx-php-fpm-redirect.html

echo key and value of an array without and with loop

function displayArrayValue($array,$key) {
   if (array_key_exists($key,$array)) echo "$key is at ".$array[$key];
}

displayArrayValue($page, "Service"); 

How to get IntPtr from byte[] in C#

You could use Marshal.UnsafeAddrOfPinnedArrayElement to get a memory pointer to the array (or to a specific element in the array). Keep in mind that the array must be pinned first as per the API documentation:

The array must be pinned using a GCHandle before it is passed to this method. For maximum performance, this method does not validate the array passed to it; this can result in unexpected behavior.

Python - Convert a bytes array into JSON format

Your bytes object is almost JSON, but it's using single quotes instead of double quotes, and it needs to be a string. So one way to fix it is to decode the bytes to str and replace the quotes. Another option is to use ast.literal_eval; see below for details. If you want to print the result or save it to a file as valid JSON you can load the JSON to a Python list and then dump it out. Eg,

import json

my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'

# Decode UTF-8 bytes to Unicode, and convert single quotes 
# to double quotes to make it valid JSON
my_json = my_bytes_value.decode('utf8').replace("'", '"')
print(my_json)
print('- ' * 20)

# Load the JSON to a Python list & dump it back out as formatted JSON
data = json.loads(my_json)
s = json.dumps(data, indent=4, sort_keys=True)
print(s)

output

[{"Date": "2016-05-21T21:35:40Z", "CreationDate": "2012-05-05", "LogoType": "png", "Ref": 164611595, "Classe": ["Email addresses", "Passwords"],"Link":"http://some_link.com"}]
- - - - - - - - - - - - - - - - - - - - 
[
    {
        "Classe": [
            "Email addresses",
            "Passwords"
        ],
        "CreationDate": "2012-05-05",
        "Date": "2016-05-21T21:35:40Z",
        "Link": "http://some_link.com",
        "LogoType": "png",
        "Ref": 164611595
    }
]

As Antti Haapala mentions in the comments, we can use ast.literal_eval to convert my_bytes_value to a Python list, once we've decoded it to a string.

from ast import literal_eval
import json

my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'

data = literal_eval(my_bytes_value.decode('utf8'))
print(data)
print('- ' * 20)

s = json.dumps(data, indent=4, sort_keys=True)
print(s)

Generally, this problem arises because someone has saved data by printing its Python repr instead of using the json module to create proper JSON data. If it's possible, it's better to fix that problem so that proper JSON data is created in the first place.

What is path of JDK on Mac ?

The location has changed from Java 6 (provided by Apple) to Java 7 and onwards (provided by Oracle). The best generic way to find this out is to run

/usr/libexec/java_home

This is the natively supported way to find out both the path to the default Java installation as well as all alternative ones present.

If you check out its help text (java_home -h), you'll see that you can use this command to reliably start a Java program on OS X (java_home --exec ...), with the ability to explicitly specify the desired Java version and architecture, or even request the user to install it if missing.

A more pedestrian approach, but one which will help you trace specifically which Java installation the command java resolves into, goes like this:

  1. run

    which java
    
  2. if that gives you something like /usr/bin/java, which is a symbolic link to the real location, run

    ls -l `which java`
    

    On my system, this outputs

    /usr/bin/java -> /Library/Java/JavaVirtualMachines/jdk1.7.0_25.jdk/Contents/Home/bin/java
    

    and therefrom you can read the Java home directory;

  3. if usr/bin/java points to another symbolic link, recursively apply the same approach with

    ls -l <whatever the /usr/bin/java symlink points to>
    

An important variation is the setup you get if you start by installing Apple's Java and later install Oracle's. In that case Step 2 above will give you

/usr/bin/java -> /System/Library/Frameworks/JavaVM.framework/Commands/java

and that particular java binary is a stub which will resolve the actual java command to call by consulting the JAVA_HOME environment variable and, if it's not set or doesn't point to a Java home directory, will fall back to calling java_home. It is important to have this in mind when debugging your setup.

Call method when home button pressed

I also struggled with HOME button for awhile. I wanted to stop/skip a background service (which polls location) when user clicks HOME button.

here is what I implemented as "hack-like" solution;

keep the state of the app on SharedPreferences using boolean value

on each activity

onResume() -> set appactive=true

onPause() -> set appactive=false

and the background service checks the appstate in each loop, skips the action

IF appactive=false

it works well for me, at least not draining the battery anymore, hope this helps....

Error: Cannot find module 'gulp-sass'

Make sure python is installed on your machine, Python is required for node-sass.

Why doesn't "System.out.println" work in Android?

I dont having fancy IDE to use LogCat as I use a mobile IDE.

I had to use various other methods and I have the classes and utilties for you to use if you need.

  1. class jav.android.Msg. Has a collection of static methods. A: methods for printing android TOASTS. B: methods for popping up a dialog box. Each method requires a valid Context. You can set the default context.

  2. A more ambitious way, An Android Console. You instantiate a handle to the console in your app, which fires up the console(if it is installed), and you can write to the console. I recently updated the console to implement reading input from the console. Which doesnt return until the input is recieved, like a regular console. A: Download and install Android Console( get it from me) B: A java file is shipped with it(jav.android.console.IConsole). Place it at the appropriate directory. It contains the methods to operate Android Console. C: Call the constructor which completes the initialization. D: read<*> and write the console. There is still work to do. Namely, since OnServiceConnected is not called immediately, You cannot use IConsole in the same function you instantiated it.

  3. Before creating Android Console, I created Console Dialog, which was a dialog operating in the same app to resemble a console. Pro: no need to wait on OnServiceConnected to use it. Con: When app crashes, you dont get the message that crashed the app.

Since Android Console is a seperate app in a seperate process, if your app crashes, you definately get to see the error. Furthermore IConsole sets an uncaught exception handler in your app incase you are not keen in exception handling. It pretty much prints the stack traces and exception messages to Android Console. Finally, if Android Console crashes, it sends its stacktrace and exceptions to you and you can choose an app to read it. Actually, AndroidConsole is not required to crash.

Edit Extras I noticed that my while APK Builder has no LogCat; AIDE does. Then I realized a pro of using my Android Console anyhow.

  1. Android Console is design to take up only a portion of the screen, so you can see both your app, and data emitted from your app to the console. This is not possible with AIDE. So I I want to touch the screen and see coordinates, Android Console makes this easy.

  2. Android Console is designed to pop up when you write to it.

  3. Android Console will hide when you backpress.

Date minus 1 year?

On my website, to check if registering people is 18 years old, I simply used the following :

$legalAge = date('Y-m-d', strtotime('-18 year'));

After, only compare the the two dates.

Hope it could help someone.

Rails: How can I rename a database column in a Ruby on Rails migration?

Let's KISS. All it takes is three simple steps. The following works for Rails 5.2.

1 . Create a Migration

  • rails g migration RenameNameToFullNameInStudents

  • rails g RenameOldFieldToNewFieldInTableName - that way it is perfectly clear to maintainers of the code base later on. (use a plural for the table name).

2. Edit the migration

# I prefer to explicitly write theupanddownmethods.

# ./db/migrate/20190114045137_rename_name_to_full_name_in_students.rb

class RenameNameToFullNameInStudents < ActiveRecord::Migration[5.2]
  def up
    # rename_column :table_name, :old_column, :new_column
    rename_column :students, :name, :full_name
  end

  def down
            # Note that the columns are reversed
    rename_column :students, :full_name, :name
  end
end

3. Run your migrations

rake db:migrate

And you are off to the races!

How to Debug Variables in Smarty like in PHP var_dump()

Try out with the Smarty Session:

{$smarty.session|@debug_print_var}

or

{$smarty.session|@print_r}

To beautify your output, use it between <pre> </pre> tags

How to include libraries in Visual Studio 2012?

In code level also, you could add your lib to the project using the compiler directives #pragma.

example:

#pragma comment( lib, "yourLibrary.lib" )

check if a file is open in Python

None of the other provided examples would work for me when dealing with this specific issue with excel on windows 10. The only other option I could think of was to try and rename the file or directory containing the file temporarily, then rename it back.

import os

try: 
    os.rename('file.xls', 'tempfile.xls')
    os.rename('tempfile.xls', 'file.xls')
except OSError:
    print('File is still open.')

how to use Spring Boot profiles

If you are using the Spring Boot Maven Plugin, run:

mvn spring-boot:run -Dspring-boot.run.profiles=foo,bar

(https://docs.spring.io/spring-boot/docs/current/maven-plugin/examples/run-profiles.html)

How can I send an HTTP POST request to a server from Excel using VBA?

In addition to the anwser of Bill the Lizard:

Most of the backends parse the raw post data. In PHP for example, you will have an array $_POST in which individual variables within the post data will be stored. In this case you have to use an additional header "Content-type: application/x-www-form-urlencoded":

Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
URL = "http://www.somedomain.com"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
objHTTP.send ("var1=value1&var2=value2&var3=value3")

Otherwise you have to read the raw post data on the variable "$HTTP_RAW_POST_DATA".

stringstream, string, and char* conversion confusion

stringstream.str() returns a temporary string object that's destroyed at the end of the full expression. If you get a pointer to a C string from that (stringstream.str().c_str()), it will point to a string which is deleted where the statement ends. That's why your code prints garbage.

You could copy that temporary string object to some other string object and take the C string from that one:

const std::string tmp = stringstream.str();
const char* cstr = tmp.c_str();

Note that I made the temporary string const, because any changes to it might cause it to re-allocate and thus render cstr invalid. It is therefor safer to not to store the result of the call to str() at all and use cstr only until the end of the full expression:

use_c_str( stringstream.str().c_str() );

Of course, the latter might not be easy and copying might be too expensive. What you can do instead is to bind the temporary to a const reference. This will extend its lifetime to the lifetime of the reference:

{
  const std::string& tmp = stringstream.str();   
  const char* cstr = tmp.c_str();
}

IMO that's the best solution. Unfortunately it's not very well known.

Center icon in a div - horizontally and vertically

Since they are already inline-block child elements, you can set text-align:center on the parent without having to set a width or margin:0px auto on the child. Meaning it will work for dynamically generated content with varying widths.

.img_container, .img_container2 {
    text-align: center;
}

This will center the child within both div containers.

UPDATE:

For vertical centering, you can use the calc() function assuming the height of the icon is known.

.img_container > i, .img_container2 > i {
    position:relative;
    top: calc(50% - 10px); /* 50% - 3/4 of icon height */
}

jsFiddle demo - it works.

For what it's worth - you can also use vertical-align:middle assuming display:table-cell is set on the parent.

Set width of dropdown element in HTML select dropdown options

Small And Better One

var i = 0;
$("#container > option").each(function(){ 
    if($(this).val().length > i) {
        i = $(this).val().length;

        console.log(i);
        console.log($(this).val());
    }
});

How can I convert a dictionary into a list of tuples?

By keys() and values() methods of dictionary and zip.

zip will return a list of tuples which acts like an ordered dictionary.

Demo:

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> zip(d.keys(), d.values())
[('a', 1), ('c', 3), ('b', 2)]
>>> zip(d.values(), d.keys())
[(1, 'a'), (3, 'c'), (2, 'b')]

How do I remove duplicate items from an array in Perl?

That last one was pretty good. I'd just tweak it a bit:

my @arr;
my @uniqarr;

foreach my $var ( @arr ){
  if ( ! grep( /$var/, @uniqarr ) ){
     push( @uniqarr, $var );
  }
}

I think this is probably the most readable way to do it.

javascript window.location in new tab

You can even use

window.open('https://support.wwf.org.uk', "_blank") || window.location.replace('https://support.wwf.org.uk');

This will open it on the same tab if the pop-up is blocked.

JFrame.dispose() vs System.exit()

JFrame.dispose()

public void dispose()

Releases all of the native screen resources used by this Window, its subcomponents, and all of its owned children. That is, the resources for these Components will be destroyed, any memory they consume will be returned to the OS, and they will be marked as undisplayable. The Window and its subcomponents can be made displayable again by rebuilding the native resources with a subsequent call to pack or show. The states of the recreated Window and its subcomponents will be identical to the states of these objects at the point where the Window was disposed (not accounting for additional modifications between those actions).

Note: When the last displayable window within the Java virtual machine (VM) is disposed of, the VM may terminate. See AWT Threading Issues for more information.

System.exit()

public static void exit(int status)

Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination. This method calls the exit method in class Runtime. This method never returns normally.

The call System.exit(n) is effectively equivalent to the call:

Runtime.getRuntime().exit(n)

Troubleshooting misplaced .git directory (nothing to commit)

try removing the origin first before adding it again

git remote rm origin
git remote add origin https://github.com/abc/xyz.git

Completely cancel a rebase

In the case of a past rebase that you did not properly aborted, you now (Git 2.12, Q1 2017) have git rebase --quit

See commit 9512177 (12 Nov 2016) by Nguy?n Thái Ng?c Duy (pclouds). (Merged by Junio C Hamano -- gitster -- in commit 06cd5a1, 19 Dec 2016)

rebase: add --quit to cleanup rebase, leave everything else untouched

There are occasions when you decide to abort an in-progress rebase and move on to do something else but you forget to do "git rebase --abort" first. Or the rebase has been in progress for so long you forgot about it. By the time you realize that (e.g. by starting another rebase) it's already too late to retrace your steps. The solution is normally

rm -r .git/<some rebase dir>

and continue with your life.
But there could be two different directories for <some rebase dir> (and it obviously requires some knowledge of how rebase works), and the ".git" part could be much longer if you are not at top-dir, or in a linked worktree. And "rm -r" is very dangerous to do in .git, a mistake in there could destroy object database or other important data.

Provide "git rebase --quit" for this use case, mimicking a precedent that is "git cherry-pick --quit".


Before Git 2.27 (Q2 2020), The stash entry created by "git merge --autostash" to keep the initial dirty state were discarded by mistake upon "git rebase --quit", which has been corrected.

See commit 9b2df3e (28 Apr 2020) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 3afdeef, 29 Apr 2020)

rebase: save autostash entry into stash reflog on --quit

Signed-off-by: Denton Liu

In a03b55530a ("merge: teach --autostash option", 2020-04-07, Git v2.27.0 -- merge listed in batch #5), the --autostash option was introduced for git merge.

(See "Can “git pull” automatically stash and pop pending changes?")

Notably, when git merge --quit is run with an autostash entry present, it is saved into the stash reflog.

This is contrasted with the current behaviour of git rebase --quit where the autostash entry is simply just dropped out of existence.

Adopt the behaviour of git merge --quit in git rebase --quit and save the autostash entry into the stash reflog instead of just deleting it.

How to store image in SQL Server database tables column

give this a try,

insert into tableName (ImageColumn) 
SELECT BulkColumn 
FROM Openrowset( Bulk 'image..Path..here', Single_Blob) as img

INSERTING

enter image description here

REFRESHING THE TABLE

enter image description here

Twitter bootstrap modal-backdrop doesn't disappear

for me, the best answer is this.

<body>
<!-- All other HTML -->
<div>
    ...
</div>

<!-- Modal -->
<div class="modal fade" id="myModal">
    ...
</div>

Modal Markup Placement Always try to place a modal's HTML code in a top-level position in your document to avoid other components affecting the modal's appearance and/or functionality.

from this SO answer

Mockito: Mock private field initialization

Using @Jarda's guide you can define this if you need to set the variable the same value for all tests:

@Before
public void setClientMapper() throws NoSuchFieldException, SecurityException{
    FieldSetter.setField(client, client.getClass().getDeclaredField("mapper"), new Mapper());
}

But beware that setting private values to be different should be handled with care. If they are private are for some reason.

Example, I use it, for example, to change the wait time of a sleep in the unit tests. In real examples I want to sleep for 10 seconds but in unit-test I'm satisfied if it's immediate. In integration tests you should test the real value.

How can I format a decimal to always show 2 decimal places?

The String Formatting Operations section of the Python documentation contains the answer you're looking for. In short:

"%0.2f" % (num,)

Some examples:

>>> "%0.2f" % 10
'10.00'
>>> "%0.2f" % 1000
'1000.00'
>>> "%0.2f" % 10.1
'10.10'
>>> "%0.2f" % 10.120
'10.12'
>>> "%0.2f" % 10.126
'10.13'

PHP Change Array Keys

You could create a new array containing that array, so:

<?php
$array = array();
$array['name'] = $oldArray;
?>

How to open a local disk file with JavaScript?

You can't. New browsers like Firefox, Safari etc. block the 'file' protocol. It will only work on old browsers.

You'll have to upload the files you want.

Python slice first and last element in list

first, last = some_list[0], some_list[-1]

iOS: UIButton resize according to text length

To accomplish this using autolayout, try setting a variable width constraint:

Width Constraint

You may also need to adjust your Content Hugging Priority and Content Compression Resistance Priority to get the results you need.


UILabel is completely automatically self-sizing:

This UILabel is simply set to be centered on the screen (two constraints only, horizontal/vertical):

It changes widths totally automatically:

You do not need to set any width or height - it's totally automatic.

enter image description here

enter image description here

Notice the small yellow squares are simply attached ("spacing" of zero). They automatically move as the UILabel resizes.

Adding a ">=" constraint sets a minimum width for the UILabel:

enter image description here

Getting full URL of action in ASP.NET MVC

This question is specific to ASP .NET however I am sure some of you will benefit of system agnostic javascript which is beneficial in many situations.

UPDATE: The way to get url formed outside of the page itself is well described in answers above.

Or you could do a oneliner like following:

new UrlHelper(actionExecutingContext.RequestContext).Action(
    "SessionTimeout", "Home", 
    new {area = string.Empty}, 
    actionExecutingContext.Request.Url!= null? 
    actionExecutingContext.Request.Url.Scheme : "http"
);

from filter or:

new UrlHelper(this.Request.RequestContext).Action(
    "Details", 
    "Journey", 
    new { area = productType }, 
    this.Request.Url!= null? this.Request.Url.Scheme : "http"
);

However quite often one needs to get the url of current page, for those cases using Html.Action and putting he name and controller of page you are in to me feels awkward. My preference in such cases is to use JavaScript instead. This is especially good in systems that are half re-written MVT half web-forms half vb-script half God knows what - and to get URL of current page one needs to use different method every time.

One way is to use JavaScript to get URL is window.location.href another - document.URL

PHP regular expressions: No ending delimiter '^' found in

You can use T-Regx library, that doesn't need delimiters

pattern('^([0-9]+)$')->match($input);

What are the differences between 'call-template' and 'apply-templates' in XSL?

The functionality is indeed similar (apart from the calling semantics, where call-template requires a name attribute and a corresponding names template).

However, the parser will not execute the same way.

From MSDN:

Unlike <xsl:apply-templates>, <xsl:call-template> does not change the current node or the current node-list.

Using headers with the Python requests library's get method

Seems pretty straightforward, according to the docs on the page you linked (emphasis mine).

requests.get(url, params=None, headers=None, cookies=None, auth=None, timeout=None)

Sends a GET request. Returns Response object.

Parameters:

  • url – URL for the new Request object.
  • params – (optional) Dictionary of GET Parameters to send with the Request.
  • headers – (optional) Dictionary of HTTP Headers to send with the Request.
  • cookies – (optional) CookieJar object to send with the Request.
  • auth – (optional) AuthObject to enable Basic HTTP Auth.
  • timeout – (optional) Float describing the timeout of the request.

open read and close a file in 1 line of code

I frequently do something like this when I need to get a few lines surrounding something I've grepped in a log file:

$ grep -n "xlrd" requirements.txt | awk -F ":" '{print $1}'
54

$ python -c "with open('requirements.txt') as file: print ''.join(file.readlines()[52:55])"
wsgiref==0.1.2
xlrd==0.9.2
xlwt==0.7.5

How do I give PHP write access to a directory?

Best way in giving write access to a directory..

$dst = "path/to/directory";
mkdir($dst); 
chown($dst, "ownername");
chgrp($dst, "groupname");
exec ("find ".$dst." -type d -exec chmod 0777 {} +");

Match multiline text using regular expression

This has nothing to do with the MULTILINE flag; what you're seeing is the difference between the find() and matches() methods. find() succeeds if a match can be found anywhere in the target string, while matches() expects the regex to match the entire string.

Pattern p = Pattern.compile("xyz");

Matcher m = p.matcher("123xyzabc");
System.out.println(m.find());    // true
System.out.println(m.matches()); // false

Matcher m = p.matcher("xyz");
System.out.println(m.matches()); // true

Furthermore, MULTILINE doesn't mean what you think it does. Many people seem to jump to the conclusion that you have to use that flag if your target string contains newlines--that is, if it contains multiple logical lines. I've seen several answers here on SO to that effect, but in fact, all that flag does is change the behavior of the anchors, ^ and $.

Normally ^ matches the very beginning of the target string, and $ matches the very end (or before a newline at the end, but we'll leave that aside for now). But if the string contains newlines, you can choose for ^ and $ to match at the start and end of any logical line, not just the start and end of the whole string, by setting the MULTILINE flag.

So forget about what MULTILINE means and just remember what it does: changes the behavior of the ^ and $ anchors. DOTALL mode was originally called "single-line" (and still is in some flavors, including Perl and .NET), and it has always caused similar confusion. We're fortunate that the Java devs went with the more descriptive name in that case, but there was no reasonable alternative for "multiline" mode.

In Perl, where all this madness started, they've admitted their mistake and gotten rid of both "multiline" and "single-line" modes in Perl 6 regexes. In another twenty years, maybe the rest of the world will have followed suit.

Find duplicate records in MongoDB

Use aggregation on name and get name with count > 1:

db.collection.aggregate([
    {"$group" : { "_id": "$name", "count": { "$sum": 1 } } },
    {"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } }, 
    {"$project": {"name" : "$_id", "_id" : 0} }
]);

To sort the results by most to least duplicates:

db.collection.aggregate([
    {"$group" : { "_id": "$name", "count": { "$sum": 1 } } },
    {"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } }, 
    {"$sort": {"count" : -1} },
    {"$project": {"name" : "$_id", "_id" : 0} }     
]);

To use with another column name than "name", change "$name" to "$column_name"

How to add plus one (+1) to a SQL Server column in a SQL Query

You need both a value and a field to assign it to. The value is TableField + 1, so the assignment is:

SET TableField = TableField + 1

jQuery - how to write 'if not equal to' (opposite of ==)

if ("one" !== 1 )

would evaluate as true, the string "one" is not equal to the number 1

connect to host localhost port 22: Connection refused

My port number is different. i tried using

ssh localhost -p 8088

this worked for me

Disabled form inputs do not appear in the request

I'm updating this answer since is very useful. Just add readonly to the input.

So the form will be:

<form action="/Media/Add">
    <input type="hidden" name="Id" value="123" />
    <input type="textbox" name="Percentage" value="100" readonly/>
</form>

What is difference between cacerts and keystore?

'cacerts' is a truststore. A trust store is used to authenticate peers. A keystore is used to authenticate yourself.

Git Pull vs Git Rebase

git-pull - Fetch from and integrate with another repository or a local branch GIT PULL

Basically you are pulling remote branch to your local, example:

git pull origin master

Will pull master branch into your local repository

git-rebase - Forward-port local commits to the updated upstream head GIT REBASE

This one is putting your local changes on top of changes done remotely by other users. For example:

  • You have committed some changes on your local branch for example called SOME-FEATURE
  • Your friend in the meantime was working on other features and he merged his branch into master

Now you want to see his and your changes on your local branch. So then you checkout master branch:

git checkout master

then you can pull:

git pull origin master

and then you go to your branch:

git checkout SOME-FEATURE

and you can do rebase master to get lastest changes from it and put your branch commits on top:

git rebase master

I hope now it's a bit more clear for you.

How to easily get network path to the file you are working on?

Just paste the below formula in any of the cells, it will render the path of the file:

=LEFT(CELL("filename"),FIND("]",CELL("filename"),1))

The above formula works in any version of Excel.

Find intersection of two nested lists?

A pythonic way of taking the intersection of 2 lists is:

[x for x in list1 if x in list2]

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

I do some quick tests and have the following findings:

1) if using SynchronousQueue:

After the threads reach the maximum size, any new work will be rejected with the exception like below.

Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@3fee733d rejected from java.util.concurrent.ThreadPoolExecutor@5acf9800[Running, pool size = 3, active threads = 3, queued tasks = 0, completed tasks = 0]

at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)

2) if using LinkedBlockingQueue:

The threads never increase from minimum size to maximum size, meaning the thread pool is fixed size as the minimum size.

Why won't my PHP app send a 404 error?

if($_SERVER['PHP_SELF'] == '/index.php'){ 
   header('HTTP/1.0 404 Not Found');
   echo "<h1>404 Not Found</h1>";
   echo "The page that you have requested could not be found.";
   die;
}

never simplify the echo statements, and never forget the semi colon like above, also why run a substr on the page, we can easily just run php_self

How to install PostgreSQL's pg gem on Ubuntu?

For anyone who is still having issues after trying all the answers on this page, the following (finally) worked:

sudo apt-get install libgmp3-dev
gem install pg

This was after doing everything else mentioned on this page.

postgresql 9.5.8
Ubuntu 16.10

How to implement a read only property

yet another way (my favorite), starting with C# 6

private readonly int MyVal = 5;

public int MyProp => MyVal;

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties#expression-body-definitions

How do you get the current page number of a ViewPager for Android?

You will figure out that setOnPageChangeListener is deprecated, use addOnPageChangeListener, as below:

ViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
       if(position == 1){  // if you want the second page, for example
           //Your code here
       }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
});

How do I use 3DES encryption/decryption in Java?

Here is a solution using the javax.crypto library and the apache commons codec library for encoding and decoding in Base64:

import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import org.apache.commons.codec.binary.Base64;

public class TrippleDes {

    private static final String UNICODE_FORMAT = "UTF8";
    public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
    private KeySpec ks;
    private SecretKeyFactory skf;
    private Cipher cipher;
    byte[] arrayBytes;
    private String myEncryptionKey;
    private String myEncryptionScheme;
    SecretKey key;

    public TrippleDes() throws Exception {
        myEncryptionKey = "ThisIsSpartaThisIsSparta";
        myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
        arrayBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
        ks = new DESedeKeySpec(arrayBytes);
        skf = SecretKeyFactory.getInstance(myEncryptionScheme);
        cipher = Cipher.getInstance(myEncryptionScheme);
        key = skf.generateSecret(ks);
    }


    public String encrypt(String unencryptedString) {
        String encryptedString = null;
        try {
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
            byte[] encryptedText = cipher.doFinal(plainText);
            encryptedString = new String(Base64.encodeBase64(encryptedText));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptedString;
    }


    public String decrypt(String encryptedString) {
        String decryptedText=null;
        try {
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] encryptedText = Base64.decodeBase64(encryptedString);
            byte[] plainText = cipher.doFinal(encryptedText);
            decryptedText= new String(plainText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return decryptedText;
    }


    public static void main(String args []) throws Exception
    {
        TrippleDes td= new TrippleDes();

        String target="imparator";
        String encrypted=td.encrypt(target);
        String decrypted=td.decrypt(encrypted);

        System.out.println("String To Encrypt: "+ target);
        System.out.println("Encrypted String:" + encrypted);
        System.out.println("Decrypted String:" + decrypted);

    }

}

Running the above program results with the following output:

String To Encrypt: imparator
Encrypted String:FdBNaYWfjpWN9eYghMpbRA==
Decrypted String:imparator

TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

You have to import FormsModule into not only the root AppModule, but also into every subModule that uses any angular forms directives.

// SubModule A

import { CommonModule } from '@angular/common';
import { FormsModule }   from '@angular/forms';

@NgModule({
  imports: [
    CommonModule,
    FormsModule      //<----------make sure you have added this.
  ],
  ....
})

How to stop/kill a query in postgresql?

What I did is first check what are the running processes by

SELECT * FROM pg_stat_activity WHERE state = 'active';

Find the process you want to kill, then type:

SELECT pg_cancel_backend(<pid of the process>)

This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.

If the process cannot be killed, try:

SELECT pg_terminate_backend(<pid of the process>)

In Powershell what is the idiomatic way of converting a string to an int?

$source = "number35"

$number=$null

$result = foreach ($_ in $source.ToCharArray()){$digit="0123456789".IndexOf($\_,0);if($digit -ne -1){$number +=$\_}}[int32]$number

Just feed it digits and it wil convert to an Int32

nvarchar(max) still being truncated

I was creating a JSON-LD to create a site review script. **DECLARE @json VARCHAR(MAX);** The actual JSON is about 94K.

I got this to work by using the CAST('' AS VARCHAR(MAX)) + @json, as explained by other contributors:- so **SET @json = CAST('' AS VARCHAR(MAX)) + (SELECT .....**

2/ I also had to change the Query Options:- Query Options -> 'results' -> 'grid' -> 'Maximum Characters received' -> 'non-XML Data' SET to 2000000. (I left the 'results' -> 'text' -> 'Maximum number of characters displayed in each column' as the default)

Google Map API v3 — set bounds and center

The setCenter() method is still applicable for latest version of Maps API for Flash where fitBounds() does not exist.

How should I use Outlook to send code snippets?

Would sending the mail as plain-text sort this?

"How to Send a Plain Text Message in Outlook":

  • Select Actions | New Mail Message Using | Plain Text from the menu in Outlook.
  • Create your message as usual.
  • Click Send to deliver it.

Being plain text it shouldn't screw up your code, with "smart" quotes, auto-capitalisation and such.

Another possible option, if this is a common problem within the company perhaps you could setup an internal code-paste site, there's plenty of open-source ones around, like Open Pastebin

toggle show/hide div with button?

Here's a plain Javascript way of doing toggle:

<script>
  var toggle = function() {
  var mydiv = document.getElementById('newpost');
  if (mydiv.style.display === 'block' || mydiv.style.display === '')
    mydiv.style.display = 'none';
  else
    mydiv.style.display = 'block'
  }
</script>

<div id="newpost">asdf</div>
<input type="button" value="btn" onclick="toggle();">

Certificate has either expired or has been revoked

I have the same issue. I solved after cleaned the Project (Shift(?)+Command(?)+K), exit Xcode and open again.

Prevent overwriting a file using cmd if exist

As in the answer of Escobar Ceaser, I suggest to use quotes arround the whole path. It's the common way to wrap the whole path in "", not only separate directory names within the path.

I had a similar issue that it didn't work for me. But it was no option to use "" within the path for separate directory names because the path contained environment variables, which theirself cover more than one directory hierarchies. The conclusion was that I missed the space between the closing " and the (

The correct version, with the space before the bracket, would be

If NOT exist "C:\Documents and Settings\John\Start Menu\Programs\Software Folder" (
 start "\\filer\repo\lab\software\myapp\setup.exe"
 pause
) 

Should I call Close() or Dispose() for stream objects?

The documentation says that these two methods are equivalent:

StreamReader.Close: This implementation of Close calls the Dispose method passing a true value.

StreamWriter.Close: This implementation of Close calls the Dispose method passing a true value.

Stream.Close: This method calls Dispose, specifying true to release all resources.

So, both of these are equally valid:

/* Option 1, implicitly calling Dispose */
using (StreamWriter writer = new StreamWriter(filename)) { 
   // do something
} 

/* Option 2, explicitly calling Close */
StreamWriter writer = new StreamWriter(filename)
try {
    // do something
}
finally {
    writer.Close();
}

Personally, I would stick with the first option, since it contains less "noise".

BEGIN - END block atomic transactions in PL/SQL

You don't mention if this is an anonymous PL/SQL block or a declarative one ie. Package, Procedure or Function. However, in PL/SQL a COMMIT must be explicitly made to save your transaction(s) to the database. The COMMIT actually saves all unsaved transactions to the database from your current user's session.

If an error occurs the transaction implicitly does a ROLLBACK.

This is the default behaviour for PL/SQL.

How do I make a Windows batch script completely silent?

You can redirect stdout to nul to hide it.

COPY %scriptDirectory%test.bat %scriptDirectory%test2.bat >nul

Just add >nul to the commands you want to hide the output from.

Here you can see all the different ways of redirecting the std streams.

How do I set the request timeout for one controller action in an asp.net mvc application

You can set this programmatically in the controller:-

HttpContext.Current.Server.ScriptTimeout = 300;

Sets the timeout to 5 minutes instead of the default 110 seconds (what an odd default?)

How to call a javaScript Function in jsp on page load without using <body onload="disableView()">

Either use window.onload this way

<script>
    window.onload = function() {
        // ...
    }
</script>

or alternatively

<script>
    window.onload = functionName;
</script>

(yes, without the parentheses)


Or just put the script at the very bottom of page, right before </body>. At that point, all HTML DOM elements are ready to be accessed by document functions.

<body>
    ...

    <script>
        functionName();
    </script>
</body>

Laravel - Forbidden You don't have permission to access / on this server

For me, It was just because I had a folder in my public_html named as same as that route!
so please check if you don't have a folder with the address of that route!
hope be helpful

Nested rows with bootstrap grid system?

Bootstrap Version 3.x

As always, read Bootstrap's great documentation:

3.x Docs: https://getbootstrap.com/docs/3.3/css/#grid-nesting

Make sure the parent level row is inside of a .container element. Whenever you'd like to nest rows, just open up a new .row inside of your column.

Here's a simple layout to work from:

<div class="container">
    <div class="row">
        <div class="col-xs-6">
            <div class="big-box">image</div>
        </div>
        <div class="col-xs-6">
            <div class="row">
                <div class="col-xs-6"><div class="mini-box">1</div></div>
                <div class="col-xs-6"><div class="mini-box">2</div></div>
                <div class="col-xs-6"><div class="mini-box">3</div></div>
                <div class="col-xs-6"><div class="mini-box">4</div></div>
            </div>
        </div>
    </div>
</div>

Bootstrap Version 4.0

4.0 Docs: http://getbootstrap.com/docs/4.0/layout/grid/#nesting

Here's an updated version for 4.0, but you should really read the entire docs section on the grid so you understand how to leverage this powerful feature

<div class="container">
  <div class="row">
    <div class="col big-box">
      image
    </div>

    <div class="col">
      <div class="row">
        <div class="col mini-box">1</div>
        <div class="col mini-box">2</div>
      </div>
      <div class="row">
        <div class="col mini-box">3</div>
        <div class="col mini-box">4</div>
      </div>
    </div>

  </div>
</div>

Demo in Fiddle jsFiddle 3.x | jsFiddle 4.0

Which will look like this (with a little bit of added styling):

screenshot

How to return a specific status code and no contents from Controller?

This code might work for non-.NET Core MVC controllers:

this.HttpContext.Response.StatusCode = 418; // I'm a teapot
return Json(new { status = "mer" }, JsonRequestBehavior.AllowGet);

Why is <deny users="?" /> included in the following example?

"At run time, the authorization module iterates through the allow and deny elements, starting at the most local configuration file, until the authorization module finds the first access rule that fits a particular user account. Then, the authorization module grants or denies access to a URL resource depending on whether the first access rule found is an allow or a deny rule. The default authorization rule is . Thus, by default, access is allowed unless configured otherwise."

Article at MSDN

deny = * means deny everyone
deny = ? means deny unauthenticated users

In your 1st example deny * will not affect dan, matthew since they were already allowed by the preceding rule.

According to the docs, here is no difference in your 2 rule sets.

libz.so.1: cannot open shared object file

Check below link: Specially "Install 32 bit libraries (if you're on 64 bit)"

 https://github.com/meteor/meteor/wiki/Mobile-Dev-Install:-Android-on-Linux

How do I calculate the normal vector of a line segment?

If we define dx = x2 - x1 and dy = y2 - y1, then the normals are (-dy, dx) and (dy, -dx).

Note that no division is required, and so you're not risking dividing by zero.

How do I convert hex to decimal in Python?

If by "hex data" you mean a string of the form

s = "6a48f82d8e828ce82b82"

you can use

i = int(s, 16)

to convert it to an integer and

str(i)

to convert it to a decimal string.

Converting a String to a List of Words?

list=mystr.split(" ",mystr.count(" "))

How to completely remove node.js from Windows

Whatever Node.js version you have installed, run its installer again. It asks you to remove Node.js like this:

Node.js Setup window with buttons for Change, Repair, Remove

How to remove specific substrings from a set of strings in Python?

# practices 2
str = "Amin Is A Good Programmer"
new_set = str.replace('Good', '')
print(new_set)

 

print : Amin Is A  Programmer

Connect to sqlplus in a shell script and run SQL scripts

For example:

sqlplus -s admin/password << EOF
whenever sqlerror exit sql.sqlcode;
set echo off 
set heading off

@pl_script_1.sql
@pl_script_2.sql

exit;
EOF

When should I use the new keyword in C++?

The second method creates the instance on the stack, along with such things as something declared int and the list of parameters that are passed into the function.

The first method makes room for a pointer on the stack, which you've set to the location in memory where a new MyClass has been allocated on the heap - or free store.

The first method also requires that you delete what you create with new, whereas in the second method, the class is automatically destructed and freed when it falls out of scope (the next closing brace, usually).

How to pretty print XML from Java?

I should have looked for this page first before coming up with my own solution! Anyway, mine uses Java recursion to parse the xml page. This code is totally self-contained and does not rely on third party libraries. Also .. it uses recursion!

// you call this method passing in the xml text
public static void prettyPrint(String text){
    prettyPrint(text, 0);
}

// "index" corresponds to the number of levels of nesting and/or the number of tabs to print before printing the tag
public static void prettyPrint(String xmlText, int index){
    boolean foundTagStart = false;
    StringBuilder tagChars = new StringBuilder();
    String startTag = "";
    String endTag = "";
    String[] chars = xmlText.split("");
    // find the next start tag
    for(String ch : chars){
        if(ch.equalsIgnoreCase("<")){
            tagChars.append(ch);
            foundTagStart = true;
        } else if(ch.equalsIgnoreCase(">") && foundTagStart){
            startTag = tagChars.append(ch).toString();
            String tempTag = startTag;
            endTag = (tempTag.contains("\"") ? (tempTag.split(" ")[0] + ">") : tempTag).replace("<", "</"); // <startTag attr1=1 attr2=2> => </startTag>
            break;
        } else if(foundTagStart){
            tagChars.append(ch);
        }
    }
    // once start and end tag are calculated, print start tag, then content, then end tag
    if(foundTagStart){
        int startIndex = xmlText.indexOf(startTag);
        int endIndex = xmlText.indexOf(endTag);
        // handle if matching tags NOT found
        if((startIndex < 0) || (endIndex < 0)){
            if(startIndex < 0) {
                // no start tag found
                return;
            } else {
                // start tag found, no end tag found (handles single tags aka "<mytag/>" or "<?xml ...>")
                printTabs(index);
                System.out.println(startTag);
                // move on to the next tag
                // NOTE: "index" (not index+1) because next tag is on same level as this one
                prettyPrint(xmlText.substring(startIndex+startTag.length(), xmlText.length()), index);
                return;
            }
        // handle when matching tags found
        } else {
            String content = xmlText.substring(startIndex+startTag.length(), endIndex);
            boolean isTagContainsTags = content.contains("<"); // content contains tags
            printTabs(index);
            if(isTagContainsTags){ // ie: <tag1><tag2>stuff</tag2></tag1>
                System.out.println(startTag);
                prettyPrint(content, index+1); // "index+1" because "content" is nested
                printTabs(index);
            } else {
                System.out.print(startTag); // ie: <tag1>stuff</tag1> or <tag1></tag1>
                System.out.print(content);
            }
            System.out.println(endTag);
            int nextIndex = endIndex + endTag.length();
            if(xmlText.length() > nextIndex){ // if there are more tags on this level, continue
                prettyPrint(xmlText.substring(nextIndex, xmlText.length()), index);
            }
        }
    } else {
        System.out.print(xmlText);
    }
}

private static void printTabs(int counter){
    while(counter-- > 0){ 
        System.out.print("\t");
    }
}

jquery 3.0 url.indexOf error

Jquery 3.0 has some breaking changes that remove certain methods due to conflicts. Your error is most likely due to one of these changes such as the removal of the .load() event.

Read more in the jQuery Core 3.0 Upgrade Guide

To fix this you either need to rewrite the code to be compatible with Jquery 3.0 or else you can use the JQuery Migrate plugin which restores the deprecated and/or removed APIs and behaviours.

How to declare and add items to an array in Python?

{} represents an empty dictionary, not an array/list. For lists or arrays, you need [].

To initialize an empty list do this:

my_list = []

or

my_list = list()

To add elements to the list, use append

my_list.append(12)

To extend the list to include the elements from another list use extend

my_list.extend([1,2,3,4])
my_list
--> [12,1,2,3,4]

To remove an element from a list use remove

my_list.remove(2)

Dictionaries represent a collection of key/value pairs also known as an associative array or a map.

To initialize an empty dictionary use {} or dict()

Dictionaries have keys and values

my_dict = {'key':'value', 'another_key' : 0}

To extend a dictionary with the contents of another dictionary you may use the update method

my_dict.update({'third_key' : 1})

To remove a value from a dictionary

del my_dict['key']

Where is the syntax for TypeScript comments documented?

Future

The TypeScript team, and other TypeScript involved teams, plan to create a standard formal TSDoc specification. The 1.0.0 draft hasn't been finalised yet: https://github.com/Microsoft/tsdoc#where-are-we-on-the-roadmap

enter image description here

Current

TypeScript uses JSDoc. e.g.

/** This is a description of the foo function. */
function foo() {
}

To learn jsdoc : https://jsdoc.app/

Demo

But you don't need to use the type annotation extensions in JSDoc.

You can (and should) still use other jsdoc block tags like @returns etc.

Example

Just an example. Focus on the types (not the content).

JSDoc version (notice types in docs):

/**
 * Returns the sum of a and b
 * @param {number} a
 * @param {number} b
 * @returns {number}
 */
function sum(a, b) {
    return a + b;
}

TypeScript version (notice the re-location of types):

/**
 * Takes two numbers and returns their sum
 * @param a first input to sum
 * @param b second input to sum
 * @returns sum of a and b
 */
function sum(a: number, b: number): number {
    return a + b;
}

ORDER BY using Criteria API

You can add join type as well:

Criteria c2 = c.createCriteria("mother", "mother", CriteriaSpecification.LEFT_JOIN);
Criteria c3 = c2.createCriteria("kind", "kind", CriteriaSpecification.LEFT_JOIN);

Android : Fill Spinner From Java Code Programmatically

// you need to have a list of data that you want the spinner to display
List<String> spinnerArray =  new ArrayList<String>();
spinnerArray.add("item1");
spinnerArray.add("item2");

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
    this, android.R.layout.simple_spinner_item, spinnerArray);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner sItems = (Spinner) findViewById(R.id.spinner1);
sItems.setAdapter(adapter);

also to find out what is selected you could do something like this

String selected = sItems.getSelectedItem().toString();
if (selected.equals("what ever the option was")) {
}

How to crop a CvMat in OpenCV?

I understand this question has been answered but perhaps this might be useful to someone...

If you wish to copy the data into a separate cv::Mat object you could use a function similar to this:

void ExtractROI(Mat& inImage, Mat& outImage, Rect roi){
    /* Create the image */
    outImage = Mat(roi.height, roi.width, inImage.type(), Scalar(0));

    /* Populate the image */
    for (int i = roi.y; i < (roi.y+roi.height); i++){
        uchar* inP = inImage.ptr<uchar>(i);
        uchar* outP = outImage.ptr<uchar>(i-roi.y);
        for (int j = roi.x; j < (roi.x+roi.width); j++){
            outP[j-roi.x] = inP[j];
        }
    }
}

It would be important to note that this would only function properly on single channel images.

Maintain the aspect ratio of a div with CSS

While most answers are very cool, most of them require to have an image already sized correctly... Other solutions only work for a width and do not care of the height available, but sometimes you want to fit the content in a certain height too.

I've tried to couple them together to bring a fully portable and re-sizable solution... The trick is to use to auto scaling of an image but use an inline svg element instead of using a pre-rendered image or any form of second HTTP request...

_x000D_
_x000D_
div.holder{_x000D_
  background-color:red;_x000D_
  display:inline-block;_x000D_
  height:100px;_x000D_
  width:400px;_x000D_
}_x000D_
svg, img{_x000D_
  background-color:blue;_x000D_
  display:block;_x000D_
  height:auto;_x000D_
  width:auto;_x000D_
  max-width:100%;_x000D_
  max-height:100%;_x000D_
}_x000D_
.content_sizer{_x000D_
  position:relative;_x000D_
  display:inline-block;_x000D_
  height:100%;_x000D_
}_x000D_
.content{_x000D_
  position:absolute;_x000D_
  top:0;_x000D_
  bottom:0;_x000D_
  left:0;_x000D_
  right:0;_x000D_
  background-color:rgba(155,255,0,0.5);_x000D_
}
_x000D_
<div class="holder">_x000D_
  <div class="content_sizer">_x000D_
    <svg width=10000 height=5000 />_x000D_
    <div class="content">_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Notice that I have used big values in the width and height attributes of the SVG, as it needs to be bigger than the maximum expected size as it can only shrink. The example makes the div's ratio 10:5

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

If you have multiply rows to delete and you don't want to alter the structure of your tables you can use cursor. 1-You first need to select rows to delete(in a cursor) 2-Then for each row in the cursor you delete the referencing rows and after that delete the row him self.

Ex:

--id is primary key of MainTable
    declare @id int
    set @id = 1
    declare theMain cursor for select FK from MainTable where MainID = @id
    declare @fk_Id int
    open theMain
    fetch next from theMain into @fk_Id
    while @@fetch_status=0
    begin
        --fkid is the foreign key 
        --Must delete from Main Table first then child.
        delete from MainTable where fkid = @fk_Id
        delete from ReferencingTable where fkid = @fk_Id
        fetch next from theMain into @fk_Id
    end
    close theMain
    deallocate theMain

hope is useful

Returning a boolean from a Bash function

For code readability reasons I believe returning true/false should:

  • be on one line
  • be one command
  • be easy to remember
  • mention the keyword return followed by another keyword (true or false)

My solution is return $(true) or return $(false) as shown:

is_directory()
{
    if [ -d "${1}" ]; then
        return $(true)
    else
        return $(false)
    fi
}

Convert JSON String To C# Object

You can accomplished your requirement easily by using Newtonsoft.Json library. I am writing down the one example below have a look into it.

Class for the type of object you receive:

public class User
{
    public int ID { get; set; }
    public string Name { get; set; }

}

Code:

static void Main(string[] args)
{

      string json = "{\"ID\": 1, \"Name\": \"Abdullah\"}";

      User user = JsonConvert.DeserializeObject<User>(json);

      Console.ReadKey();
}

this is a very simple way to parse your json.

How do I create a file at a specific path?

The file path "c:\Test\blah" will have a tab character for the `\T'. You need to use either:

"C:\\Test"

or

r"C:\Test"

Extracting columns from text file with different delimiters in Linux

If the command should work with both tabs and spaces as the delimiter I would use awk:

awk '{print $100,$101,$102,$103,$104,$105}' myfile > outfile

As long as you just need to specify 5 fields it is imo ok to just type them, for longer ranges you can use a for loop:

awk '{for(i=100;i<=105;i++)print $i}' myfile > outfile

If you want to use cut, you need to use the -f option:

cut -f100-105 myfile > outfile

If the field delimiter is different from TAB you need to specify it using -d:

cut -d' ' -f100-105 myfile > outfile

Check the man page for more info on the cut command.

Load JSON text into class object in c#

copy your Json and paste at textbox on http://json2csharp.com/ and click on Generate button,

A cs class will be generated use that cs file as below:

var generatedcsResponce = JsonConvert.DeserializeObject(yourJson);

where RootObject is the name of the generated cs file;

How to add an item to an ArrayList in Kotlin?

If you want to specifically use java ArrayList then you can do something like this:

fun initList(){
    val list: ArrayList<String> = ArrayList()
    list.add("text")
    println(list)
}

Otherwise @guenhter answer is the one you are looking for.

downcast and upcast

Upcasting (using (Employee)someInstance) is generally easy as the compiler can tell you at compile time if a type is derived from another.

Downcasting however has to be done at run time generally as the compiler may not always know whether the instance in question is of the type given. C# provides two operators for this - is which tells you if the downcast works, and return true/false. And as which attempts to do the cast and returns the correct type if possible, or null if not.

To test if an employee is a manager:

Employee m = new Manager();
Employee e = new Employee();

if(m is Manager) Console.WriteLine("m is a manager");
if(e is Manager) Console.WriteLine("e is a manager");

You can also use this

Employee someEmployee = e  as Manager;
    if(someEmployee  != null) Console.WriteLine("someEmployee (e) is a manager");

Employee someEmployee = m  as Manager;
    if(someEmployee  != null) Console.WriteLine("someEmployee (m) is a manager");

Bootstrap 3 collapsed menu doesn't close on click

Just to share this from solutions on GitHub, this was the popular answer:

https://github.com/twbs/bootstrap/issues/9013#issuecomment-39698247

$(document).on('click','.navbar-collapse.in',function(e) {
    if( $(e.target).is('a') ) {
        $(this).collapse('hide');
    }
});

This is wired to the document, so you don't have to do it on ready() (you can dynamically append links to your menu and it will still work), and it only gets called if the menu is already expanded. Some people have reported weird flashing where the menu opens and then immediately closes with other code that did not verify that the menu had the "in" class.

[UPDATE 2014-11-04] apparently when using sub-menus, the above can cause problems, so the above got modified to:

$(document).on('click','.navbar-collapse.in',function(e) {
    if( $(e.target).is('a:not(".dropdown-toggle")') ) {
        $(this).collapse('hide');
    }
});

How can I hide a TD tag using inline JavaScript or CSS?

Everything is possible (or almost) with css, just use:

display: none; //to hide

display: table-cell //to show

Open PDF in new browser full window

To do it from a Base64 encoding you can use the following function:

function base64ToArrayBuffer(data) {
  const bString = window.atob(data);
  const bLength = bString.length;
  const bytes = new Uint8Array(bLength);
  for (let i = 0; i < bLength; i++) {
      bytes[i] = bString.charCodeAt(i);
  }
  return bytes;
}
function base64toPDF(base64EncodedData, fileName = 'file') {
  const bufferArray = base64ToArrayBuffer(base64EncodedData);
  const blobStore = new Blob([bufferArray], { type: 'application/pdf' });
  if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blobStore);
      return;
  }
  const data = window.URL.createObjectURL(blobStore);
  const link = document.createElement('a');
  document.body.appendChild(link);
  link.href = data;
  link.download = `${fileName}.pdf`;
  link.click();
  window.URL.revokeObjectURL(data);
  link.remove();
}

The matching wildcard is strict, but no declaration can be found for element 'context:component-scan

This path of the schema location is wrong:

http://www.springframework.org/schema/beans

The correct path should end with /:

http://www.springframework.org/schema/beans/

How do I make a PHP form that submits to self?

I guess , you means $_SERVER['PHP_SELF']. And if so , you really shouldn't use it without sanitizing it first. This leaves you open to XSS attacks.

The if(isset($_POST['submit'])) condition should be above all the HTML output, and should contain a header() function with a redirect to current page again (only now , with some nice notice that "emails has been sent" .. or something ). For that you will have to use $_SESSION or $_COOKIE.

And please. Stop using $_REQUEST. It too poses a security threat.

Fastest way to compute entropy in Python

My favorite function for entropy is the following:

def entropy(labels):
    prob_dict = {x:labels.count(x)/len(labels) for x in labels}
    probs = np.array(list(prob_dict.values()))

    return - probs.dot(np.log2(probs))

I am still looking for a nicer way to avoid the dict -> values -> list -> np.array conversion. Will comment again if I found it.

How to round the minute of a datetime object

def get_rounded_datetime(self, dt, freq, nearest_type='inf'):

    if freq.lower() == '1h':
        round_to = 3600
    elif freq.lower() == '3h':
        round_to = 3 * 3600
    elif freq.lower() == '6h':
        round_to = 6 * 3600
    else:
        raise NotImplementedError("Freq %s is not handled yet" % freq)

    # // is a floor division, not a comment on following line:
    seconds_from_midnight = dt.hour * 3600 + dt.minute * 60 + dt.second
    if nearest_type == 'inf':
        rounded_sec = int(seconds_from_midnight / round_to) * round_to
    elif nearest_type == 'sup':
        rounded_sec = (int(seconds_from_midnight / round_to) + 1) * round_to
    else:
        raise IllegalArgumentException("nearest_type should be  'inf' or 'sup'")

    dt_midnight = datetime.datetime(dt.year, dt.month, dt.day)

    return dt_midnight + datetime.timedelta(0, rounded_sec)

How to count down in for loop?

In python, when you have an iterable, usually you iterate without an index:

letters = 'abcdef' # or a list, tupple or other iterable
for l in letters:
    print(l)

If you need to traverse the iterable in reverse order, you would do:

for l in letters[::-1]:
    print(l)

When for any reason you need the index, you can use enumerate:

for i, l in enumerate(letters, start=1): #start is 0 by default
    print(i,l)

You can enumerate in reverse order too...

for i, l in enumerate(letters[::-1])
    print(i,l)

ON ANOTHER NOTE...

Usually when we traverse an iterable we do it to apply the same procedure or function to each element. In these cases, it is better to use map:

If we need to capitilize each letter:

map(str.upper, letters)

Or get the Unicode code of each letter:

map(ord, letters)

What is the best way to create a string array in python?

But what is a reason to use fixed size? There is no actual need in python to use fixed size arrays(lists) so you always have ability to increase it's size using append, extend or decrease using pop, or at least you can use slicing.

x = [''  for x in xrange(10)]

Storing image in database directly or as base64 data?

  • Pro base64: the encoded representation you handle is a pretty safe string. It contains neither control chars nor quotes. The latter point helps against SQL injection attempts. I wouldn't expect any problem to just add the value to a "hand coded" SQL query string.

  • Pro BLOB: the database manager software knows what type of data it has to expect. It can optimize for that. If you'd store base64 in a TEXT field it might try to build some index or other data structure for it, which would be really nice and useful for "real" text data but pointless and a waste of time and space for image data. And it is the smaller, as in number of bytes, representation.

How to utilize date add function in Google spreadsheet?

Using pretty much the same approach as used by Burnash, for the final result you can use ...

=regexextract(A1,"[0-9]+")+A2

where A1 houses the string with text and number and A2 houses the date of interest

How to group time by hour or by 10 minutes

The original answer the author gave works pretty well. Just to extend this idea, you can do something like

group by datediff(minute, 0, [Date])/10

which will allow you to group by a longer period then 60 minutes, say 720, which is half a day etc.

Execute cmd command from VBScript

Set oShell = WScript.CreateObject("WSCript.shell")
oShell.run "cmd cd /d C:dir_test\file_test & sanity_check_env.bat arg1"

How to loop through all the files in a directory in c # .net?

try below code

Directory.GetFiles(txtFolderPath.Text, "*ProfileHandler.cs",SearchOption.AllDirectories)

How to repeat a char using printf?

If you limit yourself to repeating either a 0 or a space you can do:

For spaces:

printf("%*s", count, "");

For zeros:

printf("%0*d", count, 0);

How to apply CSS page-break to print a table with lots of rows?

this is working for me:

<td>
  <div class="avoid">
    Cell content.
  </div>
</td>
...
<style type="text/css">
  .avoid {
    page-break-inside: avoid !important;
    margin: 4px 0 4px 0;  /* to keep the page break from cutting too close to the text in the div */
  }
</style>

From this thread: avoid page break inside row of table

How do I get the total Json record count using JQuery?

Your json isn't an array, it hasn't length property. You must change your data return or the way you get your data count.

handle textview link click in my android app

Here is a more generic solution based on @Arun answer

public abstract class TextViewLinkHandler extends LinkMovementMethod {

    public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
        if (event.getAction() != MotionEvent.ACTION_UP)
            return super.onTouchEvent(widget, buffer, event);

        int x = (int) event.getX();
        int y = (int) event.getY();

        x -= widget.getTotalPaddingLeft();
        y -= widget.getTotalPaddingTop();

        x += widget.getScrollX();
        y += widget.getScrollY();

        Layout layout = widget.getLayout();
        int line = layout.getLineForVertical(y);
        int off = layout.getOffsetForHorizontal(line, x);

        URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
        if (link.length != 0) {
            onLinkClick(link[0].getURL());
        }
        return true;
    }

    abstract public void onLinkClick(String url);
}

To use it just implement onLinkClick of TextViewLinkHandler class. For instance:

    textView.setMovementMethod(new TextViewLinkHandler() {
        @Override
        public void onLinkClick(String url) {
            Toast.makeText(textView.getContext(), url, Toast.LENGTH_SHORT).show();
        }
    });

Bootstrap's JavaScript requires jQuery version 1.9.1 or higher

Bootstrap v3.3.6 isn't compatible with the jQuery 3.0. This will be fixed in the upcoming Bootstrap version 3.3.7. Here's the issue currently open on GitHub. https://github.com/twbs/bootstrap/issues/16834

ASP.NET - How to write some html in the page? With Response.Write?

why don't you give LiteralControl a try?

 myLitCtrl.Text="<h2><p>Notify:</p> Alert</h2>";

How to format dateTime in django template?

This is exactly what you want. Try this:

{{ wpis.entry.lastChangeDate|date:'Y-m-d H:i' }}

Error in plot.new() : figure margins too large in R

Check if your object is a list or a vector. To do this, type is.list(yourobject). If this is true, try renaming it x<-unlist(yourobject). This will make it into a vector you can plot.

Windows git "warning: LF will be replaced by CRLF", is that warning tail backward?

Do just simple thing:

  1. Open git-hub (Shell) and navigate to the directory file belongs to (cd /a/b/c/...)
  2. Execute dos2unix (sometime dos2unix.exe)
  3. Try commit now. If you get same error again. Perform all above steps except instead of dos2unix, do unix2dox (unix2dos.exe sometime)

Multiple INSERT statements vs. single INSERT with multiple VALUES

It is not too surprising: the execution plan for the tiny insert is computed once, and then reused 1000 times. Parsing and preparing the plan is quick, because it has only four values to del with. A 1000-row plan, on the other hand, needs to deal with 4000 values (or 4000 parameters if you parameterized your C# tests). This could easily eat up the time savings you gain by eliminating 999 roundtrips to SQL Server, especially if your network is not overly slow.

How to bring back "Browser mode" in IE11?

In IE11 we can change user agent to IE10, IE9 and even as windows phone. It is really good

How do I shutdown, restart, or log off Windows via a bat file?

If you are on a remote machine, you may also want to add the -f option to force the reboot. Otherwise your session may close and a stubborn app can hang the system.

I use this whenever I want to force an immediate reboot:

shutdown -t 0 -r -f

For a more friendly "give them some time" option, you can use this:

shutdown -t 30 -r

As you can see in the comments, the -f is implied by the timeout.

Brutus 2006 is a utility that provides a GUI for these options.

Task not serializable: java.io.NotSerializableException when calling function outside closure only on classes not objects

I solved this problem using a different approach. You simply need to serialize the objects before passing through the closure, and de-serialize afterwards. This approach just works, even if your classes aren't Serializable, because it uses Kryo behind the scenes. All you need is some curry. ;)

Here's an example of how I did it:

def genMapper(kryoWrapper: KryoSerializationWrapper[(Foo => Bar)])
               (foo: Foo) : Bar = {
    kryoWrapper.value.apply(foo)
}
val mapper = genMapper(KryoSerializationWrapper(new Blah(abc))) _
rdd.flatMap(mapper).collectAsMap()

object Blah(abc: ABC) extends (Foo => Bar) {
    def apply(foo: Foo) : Bar = { //This is the real function }
}

Feel free to make Blah as complicated as you want, class, companion object, nested classes, references to multiple 3rd party libs.

KryoSerializationWrapper refers to: https://github.com/amplab/shark/blob/master/src/main/scala/shark/execution/serialization/KryoSerializationWrapper.scala

How to INNER JOIN 3 tables using CodeIgniter

$this->db->select('*');    
$this->db->from('table1');
$this->db->join('table2', 'table1.id = table2.id', 'inner');
$this->db->join('table3', 'table1.id = table3.id', 'inner');
$this->db->where("table1", $id );
$query = $this->db->get();

Where you can specify which id should be viewed or select in specific table. You can also select which join portion either left, right, outer, inner, left outer, and right outer on the third parameter of join method.

"CAUTION: provisional headers are shown" in Chrome debugger

The resource could be being blocked by an extension (AdBlock in my case).

The message is there because the request to retrieve that resource was never made, so the headers being shown are not the real thing. As explained in the issue you referenced, the real headers are updated when the server responds, but there is no response if the request was blocked.


The way I found about the extension that was blocking my resource was through the net-internals tool in Chrome:

For Latest Versions of chrome

  • Type chrome://net-export/ in the address bar and hit enter.
  • Start Recording. And save Recording file to local.
  • Open the page that is showing problems.
  • Go back to net-internals
  • You can view Recorded Log file Here https://netlog-viewer.appspot.com/#import
  • click on events (###) and use the textfield to find the event related to your resource (use parts of the URL).
  • Finally, click on the event and see if the info shown tells you something.

For Older Versions of chrome

  • Type chrome://net-internals in the address bar and hit enter.
  • Open the page that is showing problems.
  • Go back to net-internals, click on events (###) and use the textfield to find the event related to your resource (use parts of the URL).
  • Finally, click on the event and see if the info shown tells you something.

Get text from DataGridView selected cells

Try this:

Dim i = Datagridview1.currentrow.index
textbox1.text = datagridview1.item(columnindex, i).value

It should work :)

loading json data from local file into React JS

You are opening an asynchronous connection, yet you have written your code as if it was synchronous. The reqListener callback function will not execute synchronously with your code (that is, before React.createClass), but only after your entire snippet has run, and the response has been received from your remote location.

Unless you are on a zero-latency quantum-entanglement connection, this is well after all your statements have run. For example, to log the received data, you would:

function reqListener(e) {
    data = JSON.parse(this.responseText);
    console.log(data);
}

I'm not seeing the use of data in the React component, so I can only suggest this theoretically: why not update your component in the callback?

6 digits regular expression

You can use range quantifier {min,max} to specify minimum of 1 digit and maximum of 6 digits as:

^[0-9]{1,6}$

Explanation:

^     : Start anchor
[0-9] : Character class to match one of the 10 digits
{1,6} : Range quantifier. Minimum 1 repetition and maximum 6.
$     : End anchor

Why did your regex not work ?

You were almost close on the regex:

^[0-9][0-9]\?[0-9]\?[0-9]\?[0-9]\?[0-9]\?$

Since you had escaped the ? by preceding it with the \, the ? was no more acting as a regex meta-character ( for 0 or 1 repetitions) but was being treated literally.

To fix it just remove the \ and you are there.

See it on rubular.

The quantifier based regex is shorter, more readable and can easily be extended to any number of digits.

Your second regex:

^[0-999999]$

is equivalent to:

^[0-9]$

which matches strings with exactly one digit. They are equivalent because a character class [aaaab] is same as [ab].

How to post query parameters with Axios?

In my case, the API responded with a CORS error. I instead formatted the query parameters into query string. It successfully posted data and also avoided the CORS issue.

        var data = {};

        const params = new URLSearchParams({
          contact: this.ContactPerson,
          phoneNumber: this.PhoneNumber,
          email: this.Email
        }).toString();

        const url =
          "https://test.com/api/UpdateProfile?" +
          params;

        axios
          .post(url, data, {
            headers: {
              aaid: this.ID,
              token: this.Token
            }
          })
          .then(res => {
            this.Info = JSON.parse(res.data);
          })
          .catch(err => {
            console.log(err);
          });

Thread Safe C# Singleton Pattern

You could eagerly create the a thread-safe Singleton instance, depending on your application needs, this is succinct code, though I would prefer @andasa's lazy version.

public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();

    private Singleton() { }

    public static Singleton Instance()
    {
        return instance;
    }
}

How to get current moment in ISO 8601 format with date, hour, and minute?

Here's a whole class optimized so that invoking "now()" doesn't do anything more that it has to do.

public class Iso8601Util
{
    private static TimeZone tz = TimeZone.getTimeZone("UTC");
    private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");

    static
    {
        df.setTimeZone(tz);
    }

    public static String now()
    {
        return df.format(new Date());
    }
}

Created Button Click Event c#

Create the Button and add it to Form.Controls list to display it on your form:

Button buttonOk = new Button();
buttonOk.Location = new Point(295, 45);  //or what ever position you want it to give
buttonOk.Text = "OK"; //or what ever you want to write over it
buttonOk.Click += new EventHandler(buttonOk_Click);
this.Controls.Add(buttonOk); //here you add it to the Form's Controls list

Create the button click method here:

void buttonOk_Click(object sender, EventArgs e)
        {
            MessageBox.Show("clicked");
            this.Close(); //all your choice to close it or remove this line
        }

How can I pass arguments to a batch file?

enter image description here

For to use looping get all arguments and in pure batch:

Obs: For using without: ?*&<>


@echo off && setlocal EnableDelayedExpansion

 for %%Z in (%*)do set "_arg_=%%Z" && set/a "_cnt+=1+0" && (
     call set "_arg_[!_cnt!]=!_arg_!" && for /l %%l in (!_cnt! 1 !_cnt!
     )do echo/ The argument n:%%l is: !_arg_[%%l]!
 )

goto :eof 

Your code is ready to do something with the argument number where it needs, like...

 @echo off && setlocal EnableDelayedExpansion

 for %%Z in (%*)do set "_arg_=%%Z" && set/a "_cnt+=1+0" && call set "_arg_[!_cnt!]=!_arg_!"
 
 fake-command /u !_arg_[1]! /p !_arg_[2]! > test-log.txt
 

List method to delete last element in list as well as all elements

To delete the last element of the lists, you could use:

def deleteLast(self):
    if self.Ans:
        del self.Ans[-1]
    if self.masses:
        del self.masses[-1]

How do you specifically order ggplot2 x axis instead of alphabetical order?

It is a little difficult to answer your specific question without a full, reproducible example. However something like this should work:

#Turn your 'treatment' column into a character vector
data$Treatment <- as.character(data$Treatment)
#Then turn it back into a factor with the levels in the correct order
data$Treatment <- factor(data$Treatment, levels=unique(data$Treatment))

In this example, the order of the factor will be the same as in the data.csv file.

If you prefer a different order, you can order them by hand:

data$Treatment <- factor(data$Treatment, levels=c("Y", "X", "Z"))

However this is dangerous if you have a lot of levels: if you get any of them wrong, that will cause problems.

convert a JavaScript string variable to decimal/money

var formatter = new Intl.NumberFormat("ru", {
  style: "currency",
  currency: "GBP"
});

alert( formatter.format(1234.5) ); // 1 234,5 £

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

Mockito How to mock and assert a thrown exception?

BDD Style Solution (Updated to Java 8)

Mockito alone is not the best solution for handling exceptions, use Mockito with Catch-Exception

Mockito + Catch-Exception + AssertJ

given(otherServiceMock.bar()).willThrow(new MyException());

when(() -> myService.foo());

then(caughtException()).isInstanceOf(MyException.class);

Sample code

Dependencies

How do I print out the contents of an object in Rails for easy debugging?

In Rails you can print the result in the View by using the debug' Helper ActionView::Helpers::DebugHelper

#app/view/controllers/post_controller.rb
def index
 @posts = Post.all
end

#app/view/posts/index.html.erb
<%= debug(@posts) %>

#start your server
rails -s

results (in browser)

- !ruby/object:Post
  raw_attributes:
    id: 2
    title: My Second Post
    body: Welcome!  This is another example post
    published_at: '2015-10-19 23:00:43.469520'
    created_at: '2015-10-20 00:00:43.470739'
    updated_at: '2015-10-20 00:00:43.470739'
  attributes: !ruby/object:ActiveRecord::AttributeSet
    attributes: !ruby/object:ActiveRecord::LazyAttributeHash
      types: &5
        id: &2 !ruby/object:ActiveRecord::Type::Integer
          precision: 
          scale: 
          limit: 
          range: !ruby/range
            begin: -2147483648
            end: 2147483648
            excl: true
        title: &3 !ruby/object:ActiveRecord::Type::String
          precision: 
          scale: 
          limit: 
        body: &4 !ruby/object:ActiveRecord::Type::Text
          precision: 
          scale: 
          limit: 
        published_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter
          subtype: &1 !ruby/object:ActiveRecord::Type::DateTime
            precision: 
            scale: 
            limit: 
        created_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter
          subtype: *1
        updated_at: !ruby/object:ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter
          subtype: *1

how do you insert null values into sql server

If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.

Get User Selected Range

You can loop through the Selection object to see what was selected. Here is a code snippet from Microsoft (http://msdn.microsoft.com/en-us/library/aa203726(office.11).aspx):

Sub Count_Selection()
    Dim cell As Object
    Dim count As Integer
    count = 0
    For Each cell In Selection
        count = count + 1
    Next cell
    MsgBox count & " item(s) selected"
End Sub

alternative to "!is.null()" in R

The shiny package provides the convenient functions validate() and need() for checking that variables are both available and valid. need() evaluates an expression. If the expression is not valid, then an error message is returned. If the expression is valid, NULL is returned. One can use this to check if a variable is valid. See ?need for more information.

I suggest defining a function like this:

is.valid <- function(x) {
  require(shiny)
  is.null(need(x, message = FALSE))  
}

This function is.valid() will return FALSE if x is FALSE, NULL, NA, NaN, an empty string "", an empty atomic vector, a vector containing only missing values, a logical vector containing only FALSE, or an object of class try-error. In all other cases, it returns TRUE.

That means, need() (and is.valid()) covers a really broad range of failure cases. Instead of writing:

if (!is.null(x) && !is.na(x) && !is.nan(x)) {
  ...
}

one can write simply:

if (is.valid(x)) {
  ...
}

With the check for class try-error, it can even be used in conjunction with a try() block to silently catch errors: (see https://csgillespie.github.io/efficientR/programming.html#communicating-with-the-user)

bad = try(1 + "1", silent = TRUE)
if (is.valid(bad)) {
  ...
}

Retrieving a Foreign Key value with django-rest-framework serializers

Just use a related field without setting many=True.

Note that also because you want the output named category_name, but the actual field is category, you need to use the source argument on the serializer field.

The following should give you the output you need...

class ItemSerializer(serializers.ModelSerializer):
    category_name = serializers.RelatedField(source='category', read_only=True)

    class Meta:
        model = Item
        fields = ('id', 'name', 'category_name')

Entity Framework: table without primary key

  1. Change the Table structure and add a Primary Column. Update the Model
  2. Modify the .EDMX file in XML Editor and try adding a New Column under tag for this specific table (WILL NOT WORK)
  3. Instead of creating a new Primary Column to Exiting table, I will make a composite key by involving all the existing columns (WORKED)

Entity Framework: Adding DataTable with no Primary Key to Entity Model.

How to extract an assembly from the GAC?

The method described here is very easy:

http://andreasglaser.net/post/2008/08/05/Extract-assembly-from-Global-Assembly-Cache-(GAC)-with-network-drive-mapping.aspx

Summary from Article:

  • Map a Network Drive (Explorer -> Tools)
    • Map to \servername\folder (\\YourServer\C$\Windows\Assembly)
  • No need for sharing if you are the Administrator
  • Browse to the drive and extract your assembly

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

Had the exact same error in a procedure. It turns out the user running it (a technical user in our case) did not have sufficient rigths to create a temporary table.

EXEC sp_addrolemember 'db_ddladmin', 'username_here';

did the trick

The module was expected to contain an assembly manifest

I found another strange reason and i thought maybe another developer confused as me. I did run install.bat that created to install my service in developer Command Prompt of VS2010 but my service generated in VS2012. it was going to this error and drives me to crazy but i try VS2012 Developer Command Prompt tools and everything gone to be OK. I don't no why but my problem was solved. so you can test it and if anyone know reason of that please share with us. Thanks.