Programs & Examples On #Jmail

How to add default signature in Outlook

I figured out a way, but it may be too sloppy for most. I've got a simple Db and I want it to be able to generate emails for me, so here's the down and dirty solution I used:

I found that the beginning of the body text is the only place I see the "<div class=WordSection1>" in the HTMLBody of a new email, so I just did a simple replace, replacing

"<div class=WordSection1><p class=MsoNormal><o:p>"

with

"<div class=WordSection1><p class=MsoNormal><o:p>" & sBody

where sBody is the body content I want inserted. Seems to work so far.

.HTMLBody = Replace(oEmail.HTMLBody, "<div class=WordSection1><p class=MsoNormal><o:p>", "<div class=WordSection1><p class=MsoNormal><o:p>" & sBody)

Equivalent of jQuery .hide() to set visibility: hidden

An even simpler way to do this is to use jQuery's toggleClass() method

CSS

.newClass{visibility: hidden}

HTML

<a href="#" class=trigger>Trigger Element </a>
<div class="hidden_element">Some Content</div>

JS

$(document).ready(function(){
    $(".trigger").click(function(){
        $(".hidden_element").toggleClass("newClass");
    });
});

Div with horizontal scrolling only

try this:

HTML:

<div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
</div>

CSS:

.container {
  width: 200px;
  height: 100px;
  display: flex;
  overflow-x: auto;
}

.item {
  width: 100px;
  flex-shrink: 0;
  height: 100px;
}

The white-space: nowrap; property dont let you wrap text. Just see here for an example: https://codepen.io/oezkany/pen/YoVgYK

How do I make an HTML text box show a hint when empty?

You can set the placeholder using the placeholder attribute in HTML (browser support). The font-style and color can be changed with CSS (although browser support is limited).

_x000D_
_x000D_
input[type=search]::-webkit-input-placeholder { /* Safari, Chrome(, Opera?) */_x000D_
 color:gray;_x000D_
 font-style:italic;_x000D_
}_x000D_
input[type=search]:-moz-placeholder { /* Firefox 18- */_x000D_
 color:gray;_x000D_
 font-style:italic;_x000D_
}_x000D_
input[type=search]::-moz-placeholder { /* Firefox 19+ */_x000D_
 color:gray;_x000D_
 font-style:italic;_x000D_
}_x000D_
input[type=search]:-ms-input-placeholder { /* IE (10+?) */_x000D_
 color:gray;_x000D_
 font-style:italic;_x000D_
}
_x000D_
<input placeholder="Search" type="search" name="q">
_x000D_
_x000D_
_x000D_

How to force link from iframe to be opened in the parent window

I found the best solution was to use the base tag. Add the following to the head of the page in the iframe:

<base target="_parent">

This will load all links on the page in the parent window. If you want your links to load in a new window, use:

<base target="_blank">

Browser Support

Adding HTML entities using CSS content

You have to use the escaped unicode :

Like

.breadcrumbs a:before {
    content: '\0000a0';
}

More info on : http://www.evotech.net/blog/2007/04/named-html-entities-in-numeric-order/

How do I write a for loop in bash

for ((i = 0 ; i < max ; i++ )); do echo "$i"; done

What is "pass-through authentication" in IIS 7?

Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

Setting the selected attribute on a select list using jQuery

This can be a solution

$(document).on('change', 'select', function () {
            var value = $(this).val();
            $(this).find('option[value="' + value + '"]').attr("selected", "selected");
        })

What is the 'open' keyword in Swift?

Read open as

open for inheritance in other modules

I repeat open for inheritance in other modules. So an open class is open for subclassing in other modules that include the defining module. Open vars and functions are open for overriding in other modules. Its the least restrictive access level. It is as good as public access except that something that is public is closed for inheritance in other modules.

From Apple Docs:

Open access applies only to classes and class members, and it differs from public access as follows:

  1. Classes with public access, or any more restrictive access level, can be subclassed only within the module where they’re defined.

  2. Class members with public access, or any more restrictive access level, can be overridden by subclasses only within the module where they’re defined.

  3. Open classes can be subclassed within the module where they’re defined, and within any module that imports the module where they’re defined.

  4. Open class members can be overridden by subclasses within the module where they’re defined, and within any module that imports the module where they’re defined.

jQuery AJAX form data serialize using PHP

_x000D_
_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(document).ready(function(){_x000D_
    var form=$("#myForm");_x000D_
    $("#smt").click(function(){_x000D_
        $.ajax({_x000D_
            type:"POST",_x000D_
            url:form.attr("action"),_x000D_
            data:form.serialize(),_x000D_
            success: function(response){_x000D_
                console.log(response);  _x000D_
            }_x000D_
        });_x000D_
    });_x000D_
});_x000D_
</script>
_x000D_
_x000D_
_x000D_

This is perfect code , there is no problem.. You have to check that in php script.

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I had the same problem of "gpg: keyserver timed out" with a couple of different servers. Finally, it turned out that I didn't need to do that manually at all. On a Debian system, the simple solution which fixed it was just (as root or precede with sudo):

aptitude install debian-archive-keyring

In case it is some other keyring you need, check out

apt-cache search keyring | grep debian

My squeeze system shows all these:

debian-archive-keyring       - GnuPG archive keys of the Debian archive
debian-edu-archive-keyring   - GnuPG archive keys of the Debian Edu archive
debian-keyring               - GnuPG keys of Debian Developers
debian-ports-archive-keyring - GnuPG archive keys of the debian-ports archive
emdebian-archive-keyring     - GnuPG archive keys for the emdebian repository

ASP.net page without a code behind

There are two very different types of pages in SharePoint: Application Pages and Site Pages.

If you are going to use your page as an Application Page, you can safely use inline code or code behind in your page, as Application pages live on the file system.

If it's going to be a Site page, you can safely write inline code as long as you have it like that in the initial deployment. However if your site page is going to be customized at some point in the future, the inline code will no longer work because customized site pages live in the database and are executed in asp.net's "no compile" mode.

Bottom line is - you can write aspx pages with inline code. The only problem is with customized Site pages... which will no longer care for your inline code.

How do I create a round cornered UILabel on the iPhone?

Did you try using the UIButton from the Interface builder (that has rounded corners) and experimenting with the settings to make it look like a label. if all you want is to display static text within.

Can I use an image from my local file system as background in HTML?

You forgot the C: after the file:///
This works for me

<!DOCTYPE html>
<html>
    <head>
        <title>Experiment</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style>
            html,body { width: 100%; height: 100%; }
        </style>
    </head>
    <body style="background: url('file:///C:/Users/Roby/Pictures/battlefield-3.jpg')">
    </body>
</html>

How to get an MD5 checksum in PowerShell

Here's a function I use that handles relative and absolute paths:

function md5hash($path)
{
    $fullPath = Resolve-Path $path
    $md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
    $file = [System.IO.File]::Open($fullPath,[System.IO.Filemode]::Open, [System.IO.FileAccess]::Read)
    try {
        [System.BitConverter]::ToString($md5.ComputeHash($file))
    } finally {
        $file.Dispose()
    }
}

Thanks to @davor above for the suggestion to use Open() instead of ReadAllBytes() and to @jpmc26 for the suggestion to use a finally block.

Why is this printing 'None' in the output?

Because of double print function. I suggest you to use return instead of print inside the function definition.

def lyrics():
    return "The very first line"
print(lyrics())

OR

def lyrics():
    print("The very first line")
lyrics()

How to set ANDROID_HOME path in ubuntu?

Applies to Ubuntu and Linux Mint

In the archive:

sudo nano .bashrc

Add to the end:

export ANDROID_HOME=${HOME}/Android/Sdk

export PATH=${PATH}:${ANDROID_HOME}/platform-tools:${ANDROID_HOME}/tools

Restart the terminal and doing: echo $ HOME or $ PATH, you can know these variables.

The program can't start because libgcc_s_dw2-1.dll is missing

Including -static-libgcc on the compiling line, solves the issue

g++ my.cpp -o my.exe -static-libgcc

According to: @hardmath

You can also, create an alias on your profile [ .profile ] if you're on MSYS2 for example

alias g++="g++ -static-libgcc"

Now your GCC command goes thru too ;-)

Remeber to restart your Terminal

Least common multiple for 3 or more numbers

i was looking for gcd and lcm of array elements and found a good solution in the following link.

https://www.hackerrank.com/challenges/between-two-sets/forum

which includes following code. The algorithm for gcd uses The Euclidean Algorithm explained well in the link below.

https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/the-euclidean-algorithm

private static int gcd(int a, int b) {
    while (b > 0) {
        int temp = b;
        b = a % b; // % is remainder
        a = temp;
    }
    return a;
}

private static int gcd(int[] input) {
    int result = input[0];
    for (int i = 1; i < input.length; i++) {
        result = gcd(result, input[i]);
    }
    return result;
}

private static int lcm(int a, int b) {
    return a * (b / gcd(a, b));
}

private static int lcm(int[] input) {
    int result = input[0];
    for (int i = 1; i < input.length; i++) {
        result = lcm(result, input[i]);
    }
    return result;
}

Can you require two form fields to match with HTML5?

The answers that use pattern and a regex write the user's password into the input properties as plain text pattern='mypassword'. This will only be visible if developer tools are open but it still doesn't seem like a good idea.

Another issue with using pattern to check for a match is that you are likely to want to use pattern to check that the password is of the right form, e.g. mixed letters and numbers.

I also think these methods won't work well if the user switches between inputs.

Here's my solution which uses a bit more JavaScript but performs a simple equality check when either input is updated and then sets a custom HTML validity. Both inputs can still be tested for a pattern such as email format or password complexity.

For a real page you would change the input types to 'password'.

<form>
    <input type="text" id="password1" oninput="setPasswordConfirmValidity();">
    <input type="text" id="password2" oninput="setPasswordConfirmValidity();">
</form>
<script>
    function setPasswordConfirmValidity(str) {
        const password1 = document.getElementById('password1');
        const password2 = document.getElementById('password2');

        if (password1.value === password2.value) {
             password2.setCustomValidity('');
        } else {
            password2.setCustomValidity('Passwords must match');
        }
        console.log('password2 customError ', document.getElementById('password2').validity.customError);
        console.log('password2 validationMessage ', document.getElementById('password2').validationMessage);
    }
</script>

Where can I find the API KEY for Firebase Cloud Messaging?

You can find API KEY from the google-services.json file

Dynamically set value of a file input

I ended up doing something like this for AngularJS in case someone stumbles across this question:

const imageElem = angular.element('#awardImg');

if (imageElem[0].files[0])
    vm.award.imageElem = imageElem;
    vm.award.image = imageElem[0].files[0];

And then:

if (vm.award.imageElem)
    $('#awardImg').replaceWith(vm.award.imageElem);
    delete vm.award.imageElem;

Python List & for-each access (Find/Replace in built-in list)

You could replace something in there by getting the index along with the item.

>>> foo = ['a', 'b', 'c', 'A', 'B', 'C']
>>> for index, item in enumerate(foo):
...     print(index, item)
...
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'A')
(4, 'B')
(5, 'C')
>>> for index, item in enumerate(foo):
...     if item in ('a', 'A'):
...         foo[index] = 'replaced!'
...
>>> foo
['replaced!', 'b', 'c', 'replaced!', 'B', 'C']

Note that if you want to remove something from the list you have to iterate over a copy of the list, else you will get errors since you're trying to change the size of something you are iterating over. This can be done quite easily with slices.

Wrong:

>>> foo = ['a', 'b', 'c', 1, 2, 3]
>>> for item in foo:
...     if isinstance(item, int):
...         foo.remove(item)
...
>>> foo 
['a', 'b', 'c', 2]

The 2 is still in there because we modified the size of the list as we iterated over it. The correct way would be:

>>> foo = ['a', 'b', 'c', 1, 2, 3]
>>> for item in foo[:]:
...     if isinstance(item, int):
...         foo.remove(item)
...
>>> foo 
['a', 'b', 'c']

How to close a thread from within?

If you want force stop your thread: thread._Thread_stop() For me works very good.

Finding an element in an array in Java

You can use one of the many Arrays.binarySearch() methods. Keep in mind that the array must be sorted first.

How to convert a Date to a formatted string in VB.net?

Dim timeFormat As String = "yyyy-MM-dd HH:mm:ss"
objBL.date = Convert.ToDateTime(txtDate.Value).ToString(timeFormat)

best practice to generate random token for forgot password

In PHP, use random_bytes(). Reason: your are seeking the way to get a password reminder token, and, if it is a one-time login credentials, then you actually have a data to protect (which is - whole user account)

So, the code will be as follows:

//$length = 78 etc
$token = bin2hex(random_bytes($length));

Update: previous versions of this answer was referring to uniqid() and that is incorrect if there is a matter of security and not only uniqueness. uniqid() is essentially just microtime() with some encoding. There are simple ways to get accurate predictions of the microtime() on your server. An attacker can issue a password reset request and then try through a couple of likely tokens. This is also possible if more_entropy is used, as the additional entropy is similarly weak. Thanks to @NikiC and @ScottArciszewski for pointing this out.

For more details see

What is the problem with shadowing names defined in outer scopes?

There isn't any big deal in your above snippet, but imagine a function with a few more arguments and quite a few more lines of code. Then you decide to rename your data argument as yadda, but miss one of the places it is used in the function's body... Now data refers to the global, and you start having weird behaviour - where you would have a much more obvious NameError if you didn't have a global name data.

Also remember that in Python everything is an object (including modules, classes and functions), so there's no distinct namespaces for functions, modules or classes. Another scenario is that you import function foo at the top of your module, and use it somewhere in your function body. Then you add a new argument to your function and named it - bad luck - foo.

Finally, built-in functions and types also live in the same namespace and can be shadowed the same way.

None of this is much of a problem if you have short functions, good naming and a decent unit test coverage, but well, sometimes you have to maintain less than perfect code and being warned about such possible issues might help.

jquery, domain, get URL

check this

alert(window.location.hostname);

this will return host name as www.domain.com

How to show current time in JavaScript in the format HH:MM:SS?

_x000D_
_x000D_
function checkTime(i) {_x000D_
  if (i < 10) {_x000D_
    i = "0" + i;_x000D_
  }_x000D_
  return i;_x000D_
}_x000D_
_x000D_
function startTime() {_x000D_
  var today = new Date();_x000D_
  var h = today.getHours();_x000D_
  var m = today.getMinutes();_x000D_
  var s = today.getSeconds();_x000D_
  // add a zero in front of numbers<10_x000D_
  m = checkTime(m);_x000D_
  s = checkTime(s);_x000D_
  document.getElementById('time').innerHTML = h + ":" + m + ":" + s;_x000D_
  t = setTimeout(function() {_x000D_
    startTime()_x000D_
  }, 500);_x000D_
}_x000D_
startTime();
_x000D_
<div id="time"></div>
_x000D_
_x000D_
_x000D_

DEMO using javaScript only

Update

Updated Demo

(function () {
    function checkTime(i) {
        return (i < 10) ? "0" + i : i;
    }

    function startTime() {
        var today = new Date(),
            h = checkTime(today.getHours()),
            m = checkTime(today.getMinutes()),
            s = checkTime(today.getSeconds());
        document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
        t = setTimeout(function () {
            startTime()
        }, 500);
    }
    startTime();
})();

NSRange to Range<String.Index>

I've found the cleanest swift2 only solution is to create a category on NSRange:

extension NSRange {
    func stringRangeForText(string: String) -> Range<String.Index> {
        let start = string.startIndex.advancedBy(self.location)
        let end = start.advancedBy(self.length)
        return Range<String.Index>(start: start, end: end)
    }
}

And then call it from for text field delegate function:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let range = range.stringRangeForText(textField.text)
    let output = textField.text.stringByReplacingCharactersInRange(range, withString: string)

    // your code goes here....

    return true
}

How do you save/store objects in SharedPreferences on Android?

Using Delegation Kotlin we can easily put and get data from shared preferences.

    inline fun <reified T> Context.sharedPrefs(key: String) = object : ReadWriteProperty<Any?, T> {

        val sharedPrefs by lazy { [email protected]("APP_DATA", Context.MODE_PRIVATE) }
        val gson by lazy { Gson() }
        var newData: T = (T::class.java).newInstance()

        override fun getValue(thisRef: Any?, property: KProperty<*>): T {
            return getPrefs()
        }

        override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
            this.newData = value
            putPrefs(newData)
        }

        fun putPrefs(value: T?) {
            sharedPrefs.edit {
                when (value) {
                    is Int -> putInt(key, value)
                    is Boolean -> putBoolean(key, value)
                    is String -> putString(key, value)
                    is Long -> putLong(key, value)
                    is Float -> putFloat(key, value)
                    is Parcelable -> putString(key, gson.toJson(value))
                    else          -> throw Throwable("no such type exist to put data")
                }
            }
        }

        fun getPrefs(): T {
            return when (newData) {
                       is Int -> sharedPrefs.getInt(key, 0) as T
                       is Boolean -> sharedPrefs.getBoolean(key, false) as T
                       is String -> sharedPrefs.getString(key, "") as T ?: "" as T
                       is Long -> sharedPrefs.getLong(key, 0L) as T
                       is Float -> sharedPrefs.getFloat(key, 0.0f) as T
                       is Parcelable -> gson.fromJson(sharedPrefs.getString(key, "") ?: "", T::class.java)
                       else          -> throw Throwable("no such type exist to put data")
                   } ?: newData
        }

    }

    //use this delegation in activity and fragment in following way
        var ourData by sharedPrefs<String>("otherDatas")

How to display an unordered list in two columns?

Now days, for the expected result, display:grid; would do (be the easiest ?):

_x000D_
_x000D_
ul {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
}
_x000D_
<ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
  <li>D</li>
  <li>E</li>
</ul>
_x000D_
_x000D_
_x000D_

you can also get the columns shrinking on the left and able to have different width:

_x000D_
_x000D_
ul {
  display: grid;
  grid-template-columns: repeat(2, auto);
  justify-content: start;
}

li {
  margin-left: 1em;
  border: solid 1px;/*see me */
}
_x000D_
<ul>
  <li>A</li>
  <li>B</li>
  <li>C 123456</li>
  <li>D</li>
  <li>E</li>
</ul>
_x000D_
_x000D_
_x000D_

How to mention C:\Program Files in batchfile

Now that bash is out for windows 10, if you want to access program files from bash, you can do it like so: cd /mnt/c/Program\ Files.

How can I declare a two dimensional string array?

you can also write the code below.

Array lbl_array = Array.CreateInstance(typeof(string), i, j);

where 'i' is the number of rows and 'j' is the number of columns. using the 'typeof(..)' method you can choose the type of your array i.e. int, string, double

Add "Appendix" before "A" in thesis TOC

You can easily achieve what you want using the appendix package. Here's a sample file that shows you how. The key is the titletoc option when calling the package. It takes whatever value you've defined in \appendixname and the default value is Appendix.

\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents

\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
  \chapter{Consectetur adipiscing elit}
  \chapter{Mauris euismod}
\end{appendices}
\end{document}

The output looks like

enter image description here

How to convert a byte array to Stream

Easy, simply wrap a MemoryStream around it:

Stream stream = new MemoryStream(buffer);

How to disable Paste (Ctrl+V) with jQuery?

This now works for IE FF Chrome properly... I have not tested for other browsers though

$(document).ready(function(){
   $('#txtInput').on("cut copy paste",function(e) {
      e.preventDefault();
   });
});

Edit: As pointed out by webeno, .bind() is deprecated hence it is recommended to use .on() instead.

Bootstrap visible and hidden classes not working properly

No CSS required, visible class should like this: visible-md-block not just visible-md and the code should be like this:

<div class="containerdiv hidden-sm hidden-xs visible-md-block visible-lg-block">
    <div class="row">
        <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4 logo">

        </div>
    </div>
</div>

<div class="mobile hidden-md hidden-lg ">
    test
</div>

Extra css is not required at all.

Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?

I think this represents a good answer.

APK Signature Scheme v2 verification

  1. Locate the APK Signing Block and verify that:
    1. Two size fields of APK Signing Block contain the same value.
    2. ZIP Central Directory is immediately followed by ZIP End of Central Directory record.
    3. ZIP End of Central Directory is not followed by more data.
  2. Locate the first APK Signature Scheme v2 Block inside the APK Signing Block. If the v2 Block if present, proceed to step 3. Otherwise, fall back to verifying the APK using v1 scheme.
  3. For each signer in the APK Signature Scheme v2 Block:
    1. Choose the strongest supported signature algorithm ID from signatures. The strength ordering is up to each implementation/platform version.
    2. Verify the corresponding signature from signatures against signed data using public key. (It is now safe to parse signed data.)
    3. Verify that the ordered list of signature algorithm IDs in digests and signatures is identical. (This is to prevent signature stripping/addition.)
    4. Compute the digest of APK contents using the same digest algorithm as the digest algorithm used by the signature algorithm.
    5. Verify that the computed digest is identical to the corresponding digest from digests.
    6. Verify that SubjectPublicKeyInfo of the first certificate of certificates is identical to public key.
  4. Verification succeeds if at least one signer was found and step 3 succeeded for each found signer.

Note: APK must not be verified using the v1 scheme if a failure occurs in step 3 or 4.

JAR-signed APK verification (v1 scheme)

The JAR-signed APK is a standard signed JAR, which must contain exactly the entries listed in META-INF/MANIFEST.MF and where all entries must be signed by the same set of signers. Its integrity is verified as follows:

  1. Each signer is represented by a META-INF/<signer>.SF and META-INF/<signer>.(RSA|DSA|EC) JAR entry.
  2. <signer>.(RSA|DSA|EC) is a PKCS #7 CMS ContentInfo with SignedData structure whose signature is verified over the <signer>.SF file.
  3. <signer>.SF file contains a whole-file digest of the META-INF/MANIFEST.MF and digests of each section of META-INF/MANIFEST.MF. The whole-file digest of the MANIFEST.MF is verified. If that fails, the digest of each MANIFEST.MF section is verified instead.
  4. META-INF/MANIFEST.MF contains, for each integrity-protected JAR entry, a correspondingly named section containing the digest of the entry’s uncompressed contents. All these digests are verified.
  5. APK verification fails if the APK contains JAR entries which are not listed in the MANIFEST.MF and are not part of JAR signature. The protection chain is thus <signer>.(RSA|DSA|EC) ? <signer>.SF ? MANIFEST.MF ? contents of each integrity-protected JAR entry.

GC overhead limit exceeded

From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning

the following

Excessive GC Time and OutOfMemoryError

The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.

The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).

in conjunction with a passage further down

One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,

java -Dsun.rmi.dgc.client.gcInterval=3600000

-Dsun.rmi.dgc.server.gcInterval=3600000 specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.

Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.

Of course, other interpretations are possible.

Select first row in each GROUP BY group?

This way it work for me:

SELECT article, dealer, price
FROM   shop s1
WHERE  price=(SELECT MAX(s2.price)
              FROM shop s2
              WHERE s1.article = s2.article
              GROUP BY s2.article)
ORDER BY article;

Select highest price on each article

Swift Open Link in Safari

It's not "baked in to Swift", but you can use standard UIKit methods to do it. Take a look at UIApplication's openUrl(_:) (deprecated) and open(_:options:completionHandler:).

Swift 4 + Swift 5 (iOS 10 and above)

guard let url = URL(string: "https://stackoverflow.com") else { return }
UIApplication.shared.open(url)

Swift 3 (iOS 9 and below)

guard let url = URL(string: "https://stackoverflow.com") else { return }
UIApplication.shared.openURL(url)

Swift 2.2

guard let url = URL(string: "https://stackoverflow.com") else { return }
UIApplication.sharedApplication().openURL(url)    

.NET Out Of Memory Exception - Used 1.3GB but have 16GB installed

Its worth mentioning that the default for an 'Any CPU' compile now checks the 'Prefer 32bit' check box. Being set to AnyCPU, on a 64bit OS with 16gb of RAM can still hit an out of memory exception at 2gb if this is checked.

Prefer32BitCheckBox

jQuery UI autocomplete with JSON

I understand that its been answered already. but I hope this will help someone in future and saves so much time and pain.

complete code is below: This one I did for a textbox to make it Autocomplete in CiviCRM. Hope it helps someone

CRM.$( 'input[id^=custom_78]' ).autocomplete({
            autoFill: true,
            select: function (event, ui) {
                    var label = ui.item.label;
                    var value = ui.item.value;
                    // Update subject field to add book year and book product
                    var book_year_value = CRM.$('select[id^=custom_77]  option:selected').text().replace('Book Year ','');
                    //book_year_value.replace('Book Year ','');
                    var subject_value = book_year_value + '/' + ui.item.label;
                    CRM.$('#subject').val(subject_value);
                    CRM.$( 'input[name=product_select_id]' ).val(ui.item.value);
                    CRM.$('input[id^=custom_78]').val(ui.item.label);
                    return false;
            },
            source: function(request, response) {
                CRM.$.ajax({
                    url: productUrl,
                        data: {
                                        'subCategory' : cj('select[id^=custom_77]').val(),
                                        's': request.term,
                                    },
                    beforeSend: function( xhr ) {
                        xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                    },

                    success: function(result){
                                result = jQuery.parseJSON( result);
                                //console.log(result);
                                response(CRM.$.map(result, function (val,key) {
                                                         //console.log(key);
                                                         //console.log(val);
                                                         return {
                                                                 label: val,
                                                                 value: key
                                                         };
                                                 }));
                    }
                })
                .done(function( data ) {
                    if ( console && console.log ) {
                     // console.log( "Sample of dataas:", data.slice( 0, 100 ) );
                    }
                });
            }
  });

PHP code on how I'm returning data to this jquery ajax call in autocomplete:

/**
 * This class contains all product related functions that are called using AJAX (jQuery)
 */
class CRM_Civicrmactivitiesproductlink_Page_AJAX {
  static function getProductList() {
        $name   = CRM_Utils_Array::value( 's', $_GET );
    $name   = CRM_Utils_Type::escape( $name, 'String' );
    $limit  = '10';

        $strSearch = "description LIKE '%$name%'";

        $subCategory   = CRM_Utils_Array::value( 'subCategory', $_GET );
    $subCategory   = CRM_Utils_Type::escape( $subCategory, 'String' );

        if (!empty($subCategory))
        {
                $strSearch .= " AND sub_category = ".$subCategory;
        }

        $query = "SELECT id , description as data FROM abc_books WHERE $strSearch";
        $resultArray = array();
        $dao = CRM_Core_DAO::executeQuery( $query );
        while ( $dao->fetch( ) ) {
            $resultArray[$dao->id] = $dao->data;//creating the array to send id as key and data as value
        }
        echo json_encode($resultArray);
    CRM_Utils_System::civiExit();
  }
}

Return list of items in list greater than some value

Use filter (short version without doing a function with lambda, using __le__):

j2 = filter((5).__le__, j)

Example (python 3):

>>> j=[4,5,6,7,1,3,7,5]
>>> j2 = filter((5).__le__, j)
>>> j2
<filter object at 0x000000955D16DC18>
>>> list(j2)
[5, 6, 7, 7, 5]
>>> 

Example (python 2):

>>> j=[4,5,6,7,1,3,7,5]
>>> j2 = filter((5).__le__, j)
>>> j2
[5, 6, 7, 7, 5]
>>>

Use __le__ i recommend this, it's very easy, __le__ is your friend

If want to sort it to desired output (both versions):

>>> j=[4,5,6,7,1,3,7,5]
>>> j2 = filter((5).__le__, j)
>>> sorted(j2)
[5, 5, 6, 7, 7]
>>> 

Use sorted

Timings:

>>> from timeit import timeit
>>> timeit(lambda: [i for i in j if i >= 5]) # Michael Mrozek
1.4558496298222325
>>> timeit(lambda: filter(lambda x: x >= 5, j)) # Justin Ardini
0.693048732089828
>>> timeit(lambda: filter((5).__le__, j)) # Mine
0.714461565831428
>>> 

So Justin wins!!

With number=1:

>>> from timeit import timeit
>>> timeit(lambda: [i for i in j if i >= 5],number=1) # Michael Mrozek
1.642193421957927e-05
>>> timeit(lambda: filter(lambda x: x >= 5, j),number=1) # Justin Ardini
3.421236300482633e-06
>>> timeit(lambda: filter((5).__le__, j),number=1) # Mine
1.8474676011237534e-05
>>> 

So Michael wins!!

>>> from timeit import timeit
>>> timeit(lambda: [i for i in j if i >= 5],number=10) # Michael Mrozek
4.721306089550126e-05
>>> timeit(lambda: filter(lambda x: x >= 5, j),number=10) # Justin Ardini
1.0947956184281793e-05
>>> timeit(lambda: filter((5).__le__, j),number=10) # Mine
1.5053439710754901e-05
>>> 

So Justin wins again!!

How to get a list of all files that changed between two Git commits?

To find the names of all files modified since your last commit:

git diff --name-only

Or (for a bit more information, including untracked files):

git status

How do I calculate the MD5 checksum of a file in Python?

In regards to your error and what's missing in your code. m is a name which is not defined for getmd5() function.

No offence, I know you are a beginner, but your code is all over the place. Let's look at your issues one by one :)

First, you are not using hashlib.md5.hexdigest() method correctly. Please refer explanation on hashlib functions in Python Doc Library. The correct way to return MD5 for provided string is to do something like this:

>>> import hashlib
>>> hashlib.md5("filename.exe").hexdigest()
'2a53375ff139d9837e93a38a279d63e5'

However, you have a bigger problem here. You are calculating MD5 on a file name string, where in reality MD5 is calculated based on file contents. You will need to basically read file contents and pipe it though MD5. My next example is not very efficient, but something like this:

>>> import hashlib
>>> hashlib.md5(open('filename.exe','rb').read()).hexdigest()
'd41d8cd98f00b204e9800998ecf8427e'

As you can clearly see second MD5 hash is totally different from the first one. The reason for that is that we are pushing contents of the file through, not just file name.

A simple solution could be something like that:

# Import hashlib library (md5 method is part of it)
import hashlib

# File to check
file_name = 'filename.exe'

# Correct original md5 goes here
original_md5 = '5d41402abc4b2a76b9719d911017c592'  

# Open,close, read file and calculate MD5 on its contents 
with open(file_name) as file_to_check:
    # read contents of the file
    data = file_to_check.read()    
    # pipe contents of the file through
    md5_returned = hashlib.md5(data).hexdigest()

# Finally compare original MD5 with freshly calculated
if original_md5 == md5_returned:
    print "MD5 verified."
else:
    print "MD5 verification failed!."

Please look at the post Python: Generating a MD5 checksum of a file. It explains in detail a couple of ways how it can be achieved efficiently.

Best of luck.

Check array position for null/empty

If the array contains integers, the value cannot be NULL. NULL can be used if the array contains pointers.

SomeClass* myArray[2];
myArray[0] = new SomeClass();
myArray[1] = NULL;

if (myArray[0] != NULL) { // this will be executed }
if (myArray[1] != NULL) { // this will NOT be executed }

As http://en.cppreference.com/w/cpp/types/NULL states, NULL is a null pointer constant!

Jmeter - get current date and time

Use this format: ${__time(yyyy-MM-dd'T'hh:mm:ss.SS'Z')}

Which will give you: 2018-01-16T08:32:28.75Z

Can I set a breakpoint on 'memory access' in GDB?

watch only breaks on write, rwatch let you break on read, and awatch let you break on read/write.

You can set read watchpoints on memory locations:

gdb$ rwatch *0xfeedface
Hardware read watchpoint 2: *0xfeedface

but one limitation applies to the rwatch and awatch commands; you can't use gdb variables in expressions:

gdb$ rwatch $ebx+0xec1a04f
Expression cannot be implemented with read/access watchpoint.

So you have to expand them yourself:

gdb$ print $ebx 
$13 = 0x135700
gdb$ rwatch *0x135700+0xec1a04f
Hardware read watchpoint 3: *0x135700 + 0xec1a04f
gdb$ c
Hardware read watchpoint 3: *0x135700 + 0xec1a04f

Value = 0xec34daf
0x9527d6e7 in objc_msgSend ()

Edit: Oh, and by the way. You need either hardware or software support. Software is obviously much slower. To find out if your OS supports hardware watchpoints you can see the can-use-hw-watchpoints environment setting.

gdb$ show can-use-hw-watchpoints
Debugger's willingness to use watchpoint hardware is 1.

How to print the full NumPy array, without truncation?

import numpy as np
np.set_printoptions(threshold=np.inf)

I suggest using np.inf instead of np.nan which is suggested by others. They both work for your purpose, but by setting the threshold to "infinity" it is obvious to everybody reading your code what you mean. Having a threshold of "not a number" seems a little vague to me.

How to click a browser button with JavaScript automatically?

document.getElementById('youridhere').click()

How do you align left / right a div without using float?

It is dirty better use the overflow: hidden; hack:

<div class="container">
  <div style="float: left;">Left Div</div>
  <div style="float: right;">Right Div</div>
</div>

.container { overflow: hidden; }

Or if you are going to do some fancy CSS3 drop-shadow stuff and you get in trouble with the above solution:

http://web.archive.org/web/20120414135722/http://fordinteractive.com/2009/12/goodbye-overflow-clearing-hack

PS

If you want to go for clean I would rather worry about that inline javascript rather than the overflow: hidden; hack :)

How to get client IP address using jQuery

function GetUserIP(){
  var ret_ip;
  $.ajaxSetup({async: false});
  $.get('http://jsonip.com/', function(r){ 
    ret_ip = r.ip; 
  });
  return ret_ip;
}

If you want to use the IP and assign it to a variable, Try this. Just call GetUserIP()

Problems with entering Git commit message with Vim

If it is VIM for Windows, you can do the following:

  • enter your message following the presented guidelines
  • press Esc to make sure you are out of the insert mode
  • then type :wqEnter or ZZ.

Note that in VIM there are often several ways to do one thing. Here there is a slight difference though. :wqEnter always writes the current file before closing it, while ZZ, :xEnter, :xiEnter, :xitEnter, :exiEnter and :exitEnter only write it if the document is modified.
All these synonyms just have different numbers of keypresses.

C#: How to add subitems in ListView

Suppose you have a List Collection containing many items to show in a ListView, take the following example that iterates through the List Collection:

foreach (Inspection inspection in anInspector.getInspections())
  {
    ListViewItem item = new ListViewItem();
    item.Text=anInspector.getInspectorName().ToString();
    item.SubItems.Add(inspection.getInspectionDate().ToShortDateString());
    item.SubItems.Add(inspection.getHouse().getAddress().ToString());
    item.SubItems.Add(inspection.getHouse().getValue().ToString("C"));
    listView1.Items.Add(item);
  }

That code produces the following output in the ListView (of course depending how many items you have in the List Collection):

Basically the first column is a listviewitem containing many subitems (other columns). It may seem strange but listview is very flexible, you could even build a windows-like file explorer with it!

How do I find out what License has been applied to my SQL Server installation?

I know this post is older, but haven't seen a solution that provides the actual information, so I want to share what I use for SQL Server 2012 and above. the link below leads to the screenshot showing the information.

First (so no time is wasted):

SQL Server 2000:
SELECT SERVERPROPERTY('LicenseType'), SERVERPROPERTY('NumLicenses')

SQL Server 2005+

The "SELECT SERVERPROPERTY('LicenseType'), SERVERPROPERTY('NumLicenses')" is not in use anymore. You can see more details on MSFT documentation: https://docs.microsoft.com/en-us/sql/t-sql/functions/serverproperty-transact-sql?view=sql-server-2017

SQL Server 2005 - 2008R2 you would have to:

Using PowerShell: https://www.ryadel.com/en/sql-server-retrieve-product-key-from-an-existing-installation/

Using TSQL (you would need to know the registry key path off hand): https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-server-registry-transact-sql?view=sql-server-2017

SQL Server 2012+

Now, you can extract SQL Server Licensing information from the SQL Server Error Log, granted it may not be formatted the way you want, but the information is there and can be parsed, along with more descriptive information that you probably didn't expect.

EXEC sp_readerrorlog @p1 = 0
                    ,@p2 = 1
                    ,@p3 = N'licensing'

NOTE: I tried pasting the image directly, but since I am new at stakoverflow we have to follow the link below.

SQL Server License information via sp_readerrorlog

JVM heap parameters

To summarize the information found after the link: The JVM allocates the amount specified by -Xms but the OS usually does not allocate real pages until they are needed. So the JVM allocates virtual memory as specified by Xms but only allocates physical memory as is needed.

You can see this by using Process Explorer by Sysinternals instead of task manager on windows.

So there is a real difference between using -Xms64M and -Xms512M. But I think the most important difference is the one you already pointed out: the garbage collector will run more often if you really need the 512MB but only started with 64MB.

How does jQuery work when there are multiple elements with the same ID value?

jQuery's id selector only returns one result. The descendant and multiple selectors in the second and third statements are designed to select multiple elements. It's similar to:

Statement 1

var length = document.getElementById('a').length;

...Yields one result.

Statement 2

var length = 0;
for (i=0; i<document.body.childNodes.length; i++) {
    if (document.body.childNodes.item(i).id == 'a') {
        length++;
    }
}

...Yields two results.

Statement 3

var length = document.getElementById('a').length + document.getElementsByTagName('div').length;

...Also yields two results.

Find the line number where a specific word appears with "grep"

You can call tail +[line number] [file] and pipe it to grep -n which shows the line number:

tail +[line number] [file] | grep -n /regex/

The only problem with this method is the line numbers reported by grep -n will be [line number] - 1 less than the actual line number in [file].

Convert time fields to strings in Excel

This kind of this is always a pain in Excel, you have to convert the values using a function because once Excel converts the cells to Time they are stored internally as numbers. Here is the best way I know how to do it:

I'll assume that your times are in column A starting at row 1. In cell B1 enter this formula: =TEXT(A1,"hh:mm:ss AM/PM") , drag the formula down column B to the end of your data in column A. Select the values from column B, copy, go to column C and select "Paste Special", then select "Values". Select the cells you just copied into column C and format the cells as "Text".

How to read a line from the console in C?

On BSD systems and Android you can also use fgetln:

#include <stdio.h>

char *
fgetln(FILE *stream, size_t *len);

Like so:

size_t line_len;
const char *line = fgetln(stdin, &line_len);

The line is not null terminated and contains \n (or whatever your platform is using) in the end. It becomes invalid after the next I/O operation on stream.

What represents a double in sql server?

float is the closest equivalent.

SqlDbType Enumeration

For Lat/Long as OP mentioned.

A metre is 1/40,000,000 of the latitude, 1 second is around 30 metres. Float/double give you 15 significant figures. With some quick and dodgy mental arithmetic... the rounding/approximation errors would be the about the length of this fill stop -> "."

What does the Visual Studio "Any CPU" target mean?

Here's a quick overview that explains the different build targets.

From my own experience, if you're looking to build a project that will run on both x86 and x64 platforms, and you don't have any specific x64 optimizations, I'd change the build to specifically say "x86."

The reason for this is sometimes you can get some DLL files that collide or some code that winds up crashing WoW in the x64 environment. By specifically specifying x86, the x64 OS will treat the application as a pure x86 application and make sure everything runs smoothly.

How do I decode a base64 encoded string?

The m000493 method seems to perform some kind of XOR encryption. This means that the same method can be used for both encrypting and decrypting the text. All you have to do is reverse m0001cd:

string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));

string result = m000493(p0, "_p0lizei.");
//    result == "gaia^unplugged^Ta..."

with return m0001cd(builder3.ToString()); changed to return builder3.ToString();.

How to undo a git pull?

Find the <SHA#> for the commit you want to go. You can find it in github or by typing git log or git reflog show at the command line and then do git reset --hard <SHA#>

Add Favicon to Website

  1. This is not done in PHP. It's part of the <head> tags in a HTML page.
  2. That icon is called a favicon. According to Wikipedia:

    A favicon (short for favorites icon), also known as a shortcut icon, website icon, URL icon, or bookmark icon is a 16×16 or 32×32 pixel square icon associated with a particular website or webpage.

  3. Adding it is easy. Just add an .ico image file that is either 16x16 pixels or 32x32 pixels. Then, in the web pages, add <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> to the <head> element.
  4. You can easily generate favicons here.

Going through a text file line by line in C

In addition to the other answers, on a recent C library (Posix 2008 compliant), you could use getline. See this answer (to a related question).

How do you round a number to two decimal places in C#?

Personally I never round anything. Keep it as resolute as possible, since rounding is a bit of a red herring in CS anyway. But you do want to format data for your users, and to that end, I find that string.Format("{0:0.00}", number) is a good approach.

What is the best way to delete a value from an array in Perl?

splice will remove array element(s) by index. Use grep, as in your example, to search and remove.

How can I dynamically set the position of view in Android?

I found that @Stefan Haustein comes very close to my experience, but not sure 100%. My suggestion is:

  • setLeft() / setRight() / setBottom() / setTop() won't work sometimes.
  • If you want to set a position temporarily (e.g for doing animation, not affected a hierachy) when the view was added and shown, just use setX()/ setY() instead. (You might want search more in difference setLeft() and setX())
  • And note that X, Y seem to be absolute, and it was supported by AbsoluteLayout which now is deprecated. Thus, you feel X, Y is likely not supported any more. And yes, it is, but only partly. It means if your view is added, setX(), setY() will work perfectly; otherwise, when you try to add a view into view group layout (e.g FrameLayout, LinearLayout, RelativeLayout), you must set its LayoutParams with marginLeft, marginTop instead (setX(), setY() in this case won't work sometimes).
  • Set position of the view by marginLeft and marginTop is an unsynchronized process. So it needs a bit time to update hierarchy. If you use the view straight away after set margin for it, you might get a wrong value.

Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

I solved it doing

run devenv /resetuserdata

in this path:

[x64] C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE

I assume that in x86 it works in this path:

[x86] C:\Program Files\Microsoft Visual Studio 14.0\Common7\IDE

Create a list from two object lists with linq

This is Linq

var mergedList = list1.Union(list2).ToList();

This is Normaly (AddRange)

var mergedList=new List<Person>();
mergeList.AddRange(list1);
mergeList.AddRange(list2);

This is Normaly (Foreach)

var mergedList=new List<Person>();

foreach(var item in list1)
{
    mergedList.Add(item);
}
foreach(var item in list2)
{
     mergedList.Add(item);
}

This is Normaly (Foreach-Dublice)

var mergedList=new List<Person>();

foreach(var item in list1)
{
    mergedList.Add(item);
}
foreach(var item in list2)
{
   if(!mergedList.Contains(item))
   {
     mergedList.Add(item);
   }
}

push object into array

Well, ["Title", "Ramones"] is an array of strings. But [{"01":"Title", "02", "Ramones"}] is an array of object.

If you are willing to push properties or value into one object, you need to access that object and then push data into that. Example: nietos[indexNumber].yourProperty=yourValue; in real application:

nietos[0].02 = "Ramones";

If your array of object is already empty, make sure it has at least one object, or that object in which you are going to push data to.

Let's say, our array is myArray[], so this is now empty array, the JS engine does not know what type of data does it have, not string, not object, not number nothing. So, we are going to push an object (maybe empty object) into that array. myArray.push({}), or myArray.push({""}).

This will push an empty object into myArray which will have an index number 0, so your exact object is now myArray[0]

Then push property and value into that like this:

myArray[0].property = value;
//in your case:
myArray[0]["01"] = "value";

how to change namespace of entire project?

You can use ReSharper for namespace refactoring. It will give 30 days free trial. It will change namespace as per folder structure.

Steps:

  1. Right click on the project/folder/files you want to refactor.

  2. If you have installed ReSharper then you will get an option Refactor->Adjust Namespaces.... So click on this.

enter image description here

It will automatically change the name spaces of all the selected files.

How to change Label Value using javascript

This will work in Chrome

// get your input
var input = document.getElementById('txt206451');
// get it's (first) label
var label = input.labels[0];
// change it's content
label.textContent = 'thanks'

But after looking, labels doesn't seem to be widely supported..


You can use querySelector

// get txt206451's (first) label
var label = document.querySelector('label[for="txt206451"]');
// change it's content
label.textContent = 'thanks'

Angularjs loading screen on ajax request

Include this in your "app.config":

 $httpProvider.interceptors.push('myHttpInterceptor');

And add this code:

app.factory('myHttpInterceptor', function ($q, $window,$rootScope) {
    $rootScope.ActiveAjaxConectionsWithouthNotifications = 0;
    var checker = function(parameters,status){
            //YOU CAN USE parameters.url TO IGNORE SOME URL
            if(status == "request"){
                $rootScope.ActiveAjaxConectionsWithouthNotifications+=1;
                $('#loading_view').show();
            }
            if(status == "response"){
                $rootScope.ActiveAjaxConectionsWithouthNotifications-=1;

            }
            if($rootScope.ActiveAjaxConectionsWithouthNotifications<=0){
                $rootScope.ActiveAjaxConectionsWithouthNotifications=0;
                $('#loading_view').hide();

            }


    };
return {
    'request': function(config) {
        checker(config,"request");
        return config;
    },
   'requestError': function(rejection) {
       checker(rejection.config,"request");
      return $q.reject(rejection);
    },
    'response': function(response) {
         checker(response.config,"response");
      return response;
    },
   'responseError': function(rejection) {
        checker(rejection.config,"response");
      return $q.reject(rejection);
    }
  };
});

Does swift have a trim method on String?

Swift 3

let result = " abc ".trimmingCharacters(in: .whitespacesAndNewlines)

Dropping Unique constraint from MySQL table

You can DROP a unique constraint from a table using phpMyAdmin as requested as shown in the table below. A unique constraint has been placed on the Wingspan field. The name of the constraint is the same as the field name, in this instance.

alt text

Best way to "negate" an instanceof

I don't know what you imagine when you say "beautiful", but what about this? I personally think it's worse than the classic form you posted, but somebody might like it...

if (str instanceof String == false) { /* ... */ }

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes)

Well try ini_set('memory_limit', '256M');

134217728 bytes = 128 MB

Or rewrite the code to consume less memory.

Left-pad printf with spaces

If you want the word "Hello" to print in a column that's 40 characters wide, with spaces padding the left, use the following.

char *ptr = "Hello";
printf("%40s\n", ptr);

That will give you 35 spaces, then the word "Hello". This is how you format stuff when you know how wide you want the column, but the data changes (well, it's one way you can do it).

If you know you want exactly 40 spaces then some text, just save the 40 spaces in a constant and print them. If you need to print multiple lines, either use multiple printf statements like the one above, or do it in a loop, changing the value of ptr each time.

Select all where [first letter starts with B]

You can use:

WHERE LEFT (name_field, 1) = 'B';

Setting SMTP details for php mail () function

Under Windows only: You may try to use ini_set() functionDocs for the SMTPDocs and smtp_portDocs settings:

ini_set('SMTP', 'mysmtphost'); 
ini_set('smtp_port', 25); 

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

How to redirect stderr and stdout to different files in the same line in script?

Try this:

your_command 2>stderr.log 1>stdout.log

More information

The numerals 0 through 9 are file descriptors in bash. 0 stands for standard input, 1 stands for standard output, 2 stands for standard error. 3 through 9 are spare for any other temporary usage.

Any file descriptor can be redirected to a file or to another file descriptor using the operator >. You can instead use the operator >> to appends to a file instead of creating an empty one.

Usage:

file_descriptor > filename

file_descriptor > &file_descriptor

Please refer to Advanced Bash-Scripting Guide: Chapter 20. I/O Redirection.

SQL Query to add a new column after an existing column in SQL Server 2005

If you want to alter order for columns in Sql server, There is no direct way to do this in SQL Server currently.

Have a look at http://blog.sqlauthority.com/2008/04/08/sql-server-change-order-of-column-in-database-tables/

You can change order while edit design for table.

Change DataGrid cell colour based on values

This may be of help to you. It isn't the stock WPF datagrid however.

I used DevExpress with a custom ColorFormatter behaviour. I couldn't find anything on the market that did this out of the box. This took me a few days to develop. My code attaached below, hopefully this helps someone out there.

Edit: I used POCO view models and MVVM however you could change this to not use POCO if you desire.

Example

Viewmodel.cs

namespace ViewModel
{
    [POCOViewModel]
    public class Table2DViewModel
    {
        public ITable2DView Table2DView { get; set; }

        public DataTable ItemsTable { get; set; }


        public Table2DViewModel()
        {
        }

        public Table2DViewModel(MainViewModel mainViewModel, ITable2DView table2DView) : base(mainViewModel)
        {
            Table2DView = table2DView;   
            CreateTable();
        }

        private void CreateTable()
        {
            var dt = new DataTable();
            var xAxisStrings = new string[]{"X1","X2","X3"};
            var yAxisStrings = new string[]{"Y1","Y2","Y3"};

            //TODO determine your min, max number for your colours
            var minValue = 0;
            var maxValue = 100;
            Table2DView.SetColorFormatter(minValue,maxValue, null);

            //Add the columns
            dt.Columns.Add(" ", typeof(string));
            foreach (var x in xAxisStrings) dt.Columns.Add(x, typeof(double));

            //Add all the values
            double z = 0;
            for (var y = 0; y < yAxisStrings.Length; y++)
            {
                var dr = dt.NewRow();
                dr[" "] = yAxisStrings[y];
                for (var x = 0; x < xAxisStrings.Length; x++)
                {
                    //TODO put your actual values here!
                    dr[xAxisStrings[x]] = z++; //Add a random values
                }
                dt.Rows.Add(dr);
            }
            ItemsTable = dt;
        }


        public static Table2DViewModel Create(MainViewModel mainViewModel, ITable2DView table2DView)
        {
            var factory = ViewModelSource.Factory((MainViewModel mainVm, ITable2DView view) => new Table2DViewModel(mainVm, view));
            return factory(mainViewModel, table2DView);
        }
    }

}

IView.cs

namespace Interfaces
    {
        public interface ITable2DView
        {
            void SetColorFormatter(float minValue, float maxValue, ColorScaleFormat colorScaleFormat);
        }
    }

View.xaml.cs

namespace View
{
    public partial class Table2DView : ITable2DView
    {
        public Table2DView()
        {
            InitializeComponent();
        }

        static ColorScaleFormat defaultColorScaleFormat = new ColorScaleFormat
        {
            ColorMin = (Color)ColorConverter.ConvertFromString("#FFF8696B"),
            ColorMiddle = (Color)ColorConverter.ConvertFromString("#FFFFEB84"),
            ColorMax = (Color)ColorConverter.ConvertFromString("#FF63BE7B")
        };

        public void SetColorFormatter(float minValue, float maxValue, ColorScaleFormat colorScaleFormat = null)
        {
            if (colorScaleFormat == null) colorScaleFormat = defaultColorScaleFormat;
            ConditionBehavior.MinValue = minValue;
            ConditionBehavior.MaxValue = maxValue;
            ConditionBehavior.ColorScaleFormat = colorScaleFormat;
        }
    }
}

DynamicConditionBehavior.cs

namespace Behaviors
{
    public class DynamicConditionBehavior : Behavior<GridControl>
    {
        GridControl Grid => AssociatedObject;

        protected override void OnAttached()
        {
            base.OnAttached();
            Grid.ItemsSourceChanged += OnItemsSourceChanged;
        }

        protected override void OnDetaching()
        {
            Grid.ItemsSourceChanged -= OnItemsSourceChanged;
            base.OnDetaching();
        }

        public ColorScaleFormat ColorScaleFormat { get; set;}
        public float MinValue { get; set; }
        public float MaxValue { get; set; }

        private void OnItemsSourceChanged(object sender, EventArgs e)
        {
            var view = Grid.View as TableView;

            if (view == null) return;

            view.FormatConditions.Clear();

            foreach (var col in Grid.Columns)
            {
                view.FormatConditions.Add(new ColorScaleFormatCondition
                {
                    MinValue = MinValue,
                    MaxValue = MaxValue,
                    FieldName = col.FieldName,
                    Format = ColorScaleFormat,
                });
            }

        }
    }
}

View.xaml

<UserControl x:Class="View"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm" 
             xmlns:ViewModels="clr-namespace:ViewModel"
             xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid"
             xmlns:behaviors="clr-namespace:Behaviors"
             xmlns:dxdo="http://schemas.devexpress.com/winfx/2008/xaml/docking"
             DataContext="{dxmvvm:ViewModelSource Type={x:Type ViewModels:ViewModel}}"
             mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="800">

    <UserControl.Resources>
        <Style TargetType="{x:Type dxg:GridColumn}">
            <Setter Property="Width" Value="50"/>
            <Setter Property="HorizontalHeaderContentAlignment" Value="Center"/>
        </Style>

        <Style TargetType="{x:Type dxg:HeaderItemsControl}">
            <Setter Property="FontWeight" Value="DemiBold"/>
        </Style>
    </UserControl.Resources>

        <!--<dxmvvm:Interaction.Behaviors>
            <dxmvvm:EventToCommand EventName="" Command="{Binding OnLoadedCommand}"/>
        </dxmvvm:Interaction.Behaviors>-->
        <dxg:GridControl ItemsSource="{Binding ItemsTable}"
                     AutoGenerateColumns="AddNew"
                     EnableSmartColumnsGeneration="True">

        <dxmvvm:Interaction.Behaviors >
            <behaviors:DynamicConditionBehavior x:Name="ConditionBehavior" />
            </dxmvvm:Interaction.Behaviors>
            <dxg:GridControl.View>
                <dxg:TableView ShowGroupPanel="False"
                           AllowPerPixelScrolling="True"/>
            </dxg:GridControl.View>
        </dxg:GridControl>
  </UserControl>

svn : how to create a branch from certain revision of trunk

$ svn copy http://svn.example.com/repos/calc/trunk@192 \
   http://svn.example.com/repos/calc/branches/my-calc-branch \
   -m "Creating a private branch of /calc/trunk."

Where 192 is the revision you specify

You can find this information from the SVN Book, specifically here on the page about svn copy

Support for the experimental syntax 'classProperties' isn't currently enabled

yarn add --dev @babel/plugin-proposal-class-properties

or

npm install @babel/plugin-proposal-class-properties --save-dev .babelrc

Keras model.summary() result - Understanding the # of Parameters

The number of parameters is 7850 because with every hidden unit you have 784 input weights and one weight of connection with bias. This means that every hidden unit gives you 785 parameters. You have 10 units so it sums up to 7850.

The role of this additional bias term is really important. It significantly increases the capacity of your model. You can read details e.g. here Role of Bias in Neural Networks.

Implement Validation for WPF TextBoxes

When it comes to Muhammad Mehdi's answer, it is better to do:

private void salary_texbox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
     Regex regex = new Regex ( "[^0-9]+" );
     if(regex.IsMatch(e.Text))
     {
         MessageBox.Show("Error");
     }
}

Because when comparing with the TextCompositionEventArgs it gets also the last character, while with the textbox.Text it does not. With textbox, the error will show after next inserted character.

Rails and PostgreSQL: Role postgres does not exist

Actually, for some unknown reason, I found the issue was actually because the postgresql role hadn't been created.

Try running:

createuser -s -r postgres

Note that roles are the way that PostgreSQL maintains database permissions. If there is no role for the postgres user, then it can't access anything. The createuser command is a thin wrapper around the commands CREATE USER, CREATE ROLE, etc.

Change width of select tag in Twitter Bootstrap

I did a workaround by creating a new css class in my custom stylesheet as follows:

.selectwidthauto
{
     width:auto !important;
}

And then applied this class to all my select elements either manually like:

<select id="State" class="selectwidthauto">
...
</select>

Or using jQuery:

$('select').addClass('selectwidthauto');

How to import multiple csv files in a single load?

Use wildcard, e.g. replace 2008 with *:

df = sqlContext.read
       .format("com.databricks.spark.csv")
       .option("header", "true")
       .load("../Downloads/*.csv") // <-- note the star (*)

Spark 2.0

// these lines are equivalent in Spark 2.0
spark.read.format("csv").option("header", "true").load("../Downloads/*.csv")
spark.read.option("header", "true").csv("../Downloads/*.csv")

Notes:

  1. Replace format("com.databricks.spark.csv") by using format("csv") or csv method instead. com.databricks.spark.csv format has been integrated to 2.0.

  2. Use spark not sqlContext

EXCEL Multiple Ranges - need different answers for each range

use

=VLOOKUP(D4,F4:G9,2)

with the range F4:G9:

0   0.1
1   0.15
5   0.2
15  0.3
30  1
100 1.3

and D4 being the value in question, e.g. 18.75 -> result: 0.3

Rollback one specific migration in Laravel

Rollback one step. Natively.

php artisan migrate:rollback --step=1

Rollback two step. Natively.

php artisan migrate:rollback --step=2

SOAP Action WSDL

I have solved this problem, in Java Code, adding:

 MimeHeaders headers = message.getMimeHeaders();
 headers.addHeader("SOAPAction", endpointURL);

How to alter SQL in "Edit Top 200 Rows" in SSMS 2008

If you right click on any result of "Edit Top 200 Rows" query in SSMS you will see the option "Pane -> SQL". It then shows the SQL Query that was run, which you can edit as you wish.

In SMSS 2012 and 2008, you can use Ctrl+3 to quickly get there.

Tensorflow: Using Adam optimizer

The AdamOptimizer class creates additional variables, called "slots", to hold values for the "m" and "v" accumulators.

See the source here if you're curious, it's actually quite readable: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/training/adam.py#L39 . Other optimizers, such as Momentum and Adagrad use slots too.

These variables must be initialized before you can train a model.

The normal way to initialize variables is to call tf.initialize_all_variables() which adds ops to initialize the variables present in the graph when it is called.

(Aside: unlike its name suggests, initialize_all_variables() does not initialize anything, it only add ops that will initialize the variables when run.)

What you must do is call initialize_all_variables() after you have added the optimizer:

...build your model...
# Add the optimizer
train_op = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
# Add the ops to initialize variables.  These will include 
# the optimizer slots added by AdamOptimizer().
init_op = tf.initialize_all_variables()

# launch the graph in a session
sess = tf.Session()
# Actually intialize the variables
sess.run(init_op)
# now train your model
for ...:
  sess.run(train_op)

javascript create array from for loop

even shorter if you can lose the yearStart value:

var yearStart = 2000;
var yearEnd = 2040;

var arr = [];

while(yearStart < yearEnd+1){
  arr.push(yearStart++);
}

UPDATE: If you can use the ES6 syntax you can do it the way proposed here:

let yearStart = 2000;
let yearEnd = 2040;
let years = Array(yearEnd-yearStart+1)
    .fill()
    .map(() => yearStart++);

How do I add a new column to a Spark DataFrame (using PySpark)?

To add a column using a UDF:

df = sqlContext.createDataFrame(
    [(1, "a", 23.0), (3, "B", -23.0)], ("x1", "x2", "x3"))

from pyspark.sql.functions import udf
from pyspark.sql.types import *

def valueToCategory(value):
   if   value == 1: return 'cat1'
   elif value == 2: return 'cat2'
   ...
   else: return 'n/a'

# NOTE: it seems that calls to udf() must be after SparkContext() is called
udfValueToCategory = udf(valueToCategory, StringType())
df_with_cat = df.withColumn("category", udfValueToCategory("x1"))
df_with_cat.show()

## +---+---+-----+---------+
## | x1| x2|   x3| category|
## +---+---+-----+---------+
## |  1|  a| 23.0|     cat1|
## |  3|  B|-23.0|      n/a|
## +---+---+-----+---------+

How to create a CPU spike with a bash command

Using examples mentioned here, but also help from IRC, I developed my own CPU stress testing script. It uses a subshell per thread and the endless loop technique. You can also specify the number of threads and the amount of time interactively.

#!/bin/bash
# Simple CPU stress test script

# Read the user's input
echo -n "Number of CPU threads to test: "
read cpu_threads
echo -n "Duration of the test (in seconds): "
read cpu_time

# Run an endless loop on each thread to generate 100% CPU
echo -e "\E[32mStressing ${cpu_threads} threads for ${cpu_time} seconds...\E[37m"
for i in $(seq ${cpu_threads}); do
    let thread=${i}-1
    (taskset -cp ${thread} $BASHPID; while true; do true; done) &
done

# Once the time runs out, kill all of the loops
sleep ${cpu_time}
echo -e "\E[32mStressing complete.\E[37m"
kill 0

org.hibernate.MappingException: Unknown entity: annotations.Users

Initially I trying with the below code which didn't work for me

MetadataSources metadataSources = new MetadataSources(serviceRegistry);
Metadata metadata = metadataSources.getMetadataBuilder().build();
SessionFactory sessionFactory= metadata.getSessionFactoryBuilder().build();

For me below configuration worked. All the hibernate properties i provided from the code itself and using hibernate version 5+. I'm trying to connect to the Postgressql db.

imports:

 import org.hibernate.Session;
 import org.hibernate.SessionFactory;
 import org.hibernate.Transaction;
 import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
 import org.hibernate.cfg.Configuration;
 import org.hibernate.cfg.Environment;
 import org.hibernate.service.ServiceRegistry;

code:

    Configuration configuration = new Configuration();
    configuration.setProperty("hibernate.current_session_context_class", "thread");
    configuration.setProperty(Environment.DRIVER, "org.postgresql.Driver");
    configuration.setProperty(Environment.URL, lmsParams.getDbProperties().getDbURL());
    configuration.setProperty(Environment.USER, lmsParams.getDbProperties().getUsername());
    configuration.setProperty(Environment.PASS, lmsParams.getDbProperties().getPassword());

    configuration.setProperty("hibernate.connection.release_mode", "auto");
    configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
    configuration.setProperty("hibernate.show_sql", "true");
    configuration.setProperty(Environment.HBM2DDL_AUTO, "create");
    configuration.addAnnotatedClass(LMSSourceTable.class);
    ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties())
            .build();
    SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

Latest Update: One more option worked for me using the Reflections package as a dependency. This i tried with both mysql and postgress and it works fine.

Some info about Reflections: The Reflections library works as a classpath scanner. It indexes the scanned metadata and allows us to query it at runtime. It can also save this information, so we can collect and use it at any point during our project, without having to re-scan the classpath again

if you are using maven:

<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.11</version>
</dependency>

code:

 MetadataSources metadataSources = new 
 MetadataSources(serviceRegistry);
 Reflections entityPackageReflections = new Reflections("com.company.abc.package.name");
    entityPackageReflections.getTypesAnnotatedWith(Entity.class).forEach(metadataSources::addAnnotatedClass);
    Metadata metadata = metadataSources.getMetadataBuilder().build();
    SessionFactory sessionFactory=  metadata.getSessionFactoryBuilder().build();

Apache won't run in xampp

There are 2 ways to solving this problem.

  1. If you want to run Apache in another port then:Replace in xampp/apache/conf/httpd.conf "ServerName localhost:80" by "ServerName localhost:81" At line 184. After that even it may not work.Then replace
#Listen 0.0.0.0:80
#Listen [::]:80
Listen 80 

by

#Listen 0.0.0.0:81
#Listen [::]:81
Listen 81

at line 45

  1. If you want to use port 80. Then follow this. In Windows 8 “World Wide Publishing Service is using this port and stopping this service will free the port 80 and you can connect Apache using this port. To stop the service go to the “Task manager –> Services tab”, right click the “World Wide Publishing Service” and stop. If you don't find there then Then go to "Run > services.msc" and again find there and right click the “World Wide Publishing Service” and stop.

If you didn't find “World Wide Publishing Service” there then go to "Run>>resmon.exe>> Network Tab>>Listening Ports" and see which process is using port 80

enter image description here

And from "Overview>>CPU" just Right click on that process and click "End Process Tree". If that process is system that might be a critical issue.

How to diff a commit with its parent?

If you know how far back, you can try something like:

# Current branch vs. parent
git diff HEAD^ HEAD

# Current branch, diff between commits 2 and 3 times back
git diff HEAD~3 HEAD~2

Prior commits work something like this:

# Parent of HEAD
git show HEAD^1

# Grandparent
git show HEAD^2

There are a lot of ways you can specify commits:

# Great grandparent
git show HEAD~3

See this page for details.

How to control the width of select tag?

Add div wrapper

<div id=myForm>
<select name=countries>
 <option value=af>Afghanistan</option>
 <option value=ax>Åland Islands</option>
 ...
 <option value=gs>South Georgia and the South Sandwich Islands</option>
 ...
</select>
</div>

and then write CSS

#myForm select { 
width:200px; }

#myForm select:focus {
width:auto; }

Hope this will help.

SQL where datetime column equals today's date?

Can you try this?

SELECT [Title], [Firstname], [Surname], [Company_name], [Interest] 
FROM [dbo].[EXTRANET_users] 
WHERE CAST(Submission_date AS DATE) = CAST(GETDATE() AS DATE)

T-SQL doesn't really have the "implied" casting like C# does - you need to explicitly use CAST (or CONVERT).

Also, use GETDATE() or CURRENT_TIMESTAMP to get the "now" date and time.

Update: since you're working against SQL Server 2000 - none of those approaches so far work. Try this instead:

SELECT [Title], [Firstname], [Surname], [Company_name], [Interest] 
FROM [dbo].[EXTRANET_users] 
WHERE DATEADD(dd, 0, DATEDIFF(dd, 0, submission_date)) = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))

How do I redirect with JavaScript?

You can't redirect to a function. What you can do is pass some flag on the URL when redirecting, then check that flag in the server side code and if raised, execute the function.

For example:

document.location = "MyPage.php?action=DoThis";

Then in your PHP code check for "action" in the query string and if equal to "DoThis" execute whatever function you need.

Docker expose all ports or range of ports from 7000 to 8000

For anyone facing this issue and ending up on this post...the issue is still open - https://github.com/moby/moby/issues/11185

Set mouse focus and move cursor to end of input using jQuery

At the first you have to set focus on selected textbox object and next you set the value.

$('#inputID').focus();
$('#inputID').val('someValue')

How to reset Android Studio

Linux Android Studio 0.8.6:

rm -R ~/.AndroidStudioBeta/config/

Linux Android Studio 1.0.0:

rm -R ~/.AndroidStudio/config/

How to type a new line character in SQL Server Management Studio

You can paste the lines in from a text editor that uses UNIX-style line endings (CR+LF). I use Notepad++. First go to Settings/Preferences/New Document and change the format from Windows to Unix. Then open a new document, type in your lines, and copy them into SSMS.

How to make multiple divs display in one line but still retain width?

Flex is the better way. Just try..

display: flex;

C++: How to round a double to an int?

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    double x=54.999999999999943157;
    int y=ceil(x);//The ceil() function returns the smallest integer no less than x
    return 0;
}

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

Python convert decimal to hex

It is good to write your own functions for conversions between numeral systems to learn something. For "real" code I would recommend to use build in conversion function from Python like bin(x), hex(x), int(x). Some examples can be found here.

What exactly is a Maven Snapshot and why do we need it?

I'd like to make a point about terminology. The other answers gave good explanations about what a "snapshot" version is in the context of Maven. But does it follow that a non-snapshot version should be termed a "release" version?

There is some tension between the semantic versioning idea of a "release" version, which would seem to be any version that does not have a qualifier such as -SNAPSHOT but also does not have a qualifier such as -beta.4; and Maven's idea idea of a "release" version, which only seems to include the absence of -SNAPSHOT.

In other words, there is a semantic ambiguity of whether "release" means "we can release it to Maven Central" or "the software is in its final release to the public". We could consider -beta.4 to be a "release" version if we release it to the public, but it's not a "final release". Semantic versioning clearly says that something like -beta.4 is a "pre-release" version, so it wouldn't make sense for it to be called a "release" version, even without -SNAPSHOT. In fact by definition even -rc.5 is a release candidate, not an actual release, even though we may allow public access for testing.

So Maven notwithstanding, in my opinion it seems more appropriate only to call a "release" version one that doesn't have any qualifier at all, not even -beta.4. Perhaps a better name for a Maven non-snapshot version would be a "stable" version (inspired by another answer). Thus we would have:

  • 1.2.3-beta.4-SNAPSHOT: A snapshot version of a pre-release version.
  • 1.2.3-SNAPSHOT: A snapshot version of a release version.
  • 1.2.3-beta.4: A stable version of a pre-release version.
  • 1.2.3: A release version (which is a stable, non-snapshot version, obviously).

ORA-01882: timezone region not found

Happens when you use the wrong version of OJDBC jar.

You need to use 11.2.0.4

Convert Pandas column containing NaNs to dtype `int`

If you absolutely want to combine integers and NaNs in a column, you can use the 'object' data type:

df['col'] = (
    df['col'].fillna(0)
    .astype(int)
    .astype(object)
    .where(df['col'].notnull())
)

This will replace NaNs with an integer (doesn't matter which), convert to int, convert to object and finally reinsert NaNs.

Linq select to new object

Read : 101 LINQ Samples in that LINQ - Grouping Operators from Microsoft MSDN site

var x = from t in types  group t by t.Type
         into grp    
         select new { type = grp.key, count = grp.Count() };

forsingle object make use of stringbuilder and append it that will do or convert this in form of dictionary

    // fordictionary 
  var x = (from t in types  group t by t.Type
     into grp    
     select new { type = grp.key, count = grp.Count() })
   .ToDictionary( t => t.type, t => t.count); 

   //for stringbuilder not sure for this 
  var x = from t in types  group t by t.Type
         into grp    
         select new { type = grp.key, count = grp.Count() };
  StringBuilder MyStringBuilder = new StringBuilder();

  foreach (var res in x)
  {
       //: is separator between to object
       MyStringBuilder.Append(result.Type +" , "+ result.Count + " : ");
  }
  Console.WriteLine(MyStringBuilder.ToString());   

How can I stop .gitignore from appearing in the list of untracked files?

After you add the .gitignore file and commit it, it will no longer show up in the "untracked files" list.

git add .gitignore
git commit -m "add .gitignore file"
git status

XML Error: Extra content at the end of the document

I've found that this error is also generated if the document is empty. In this case it's also because there is no root element - but the error message "Extra content and the end of the document" is misleading in this situation.

Program to find largest and second largest number in array

(I'm going to ignore handling input, its just a distraction.)

The easy way is to sort it.

#include <stdlib.h>
#include <stdio.h>

int cmp_int( const void *a, const void *b ) {
    return *(int*)a - *(int*)b;
}

int main() {
    int a[] = { 1, 5, 3, 2, 0, 5, 7, 6 };
    const int n = sizeof(a) / sizeof(a[0]);

    qsort(a, n, sizeof(a[0]), cmp_int);
    printf("%d %d\n", a[n-1], a[n-2]);
}

But that isn't the most efficient because it's O(n log n), meaning as the array gets bigger the number of comparisons gets bigger faster. Not too fast, slower than exponential, but we can do better.

We can do it in O(n) or "linear time" meaning as the array gets bigger the number of comparisons grows at the same rate.

Loop through the array tracking the max, that's the usual way to find the max. When you find a new max, the old max becomes the 2nd highest number.

Instead of having a second loop to find the 2nd highest number, throw in a special case for running into the 2nd highest number.

#include <stdio.h>
#include <limits.h>

int main() {
    int a[] = { 1, 5, 3, 2, 0, 5, 7, 6 };
    // This trick to get the size of an array only works on stack allocated arrays.
    const int n = sizeof(a) / sizeof(a[0]);

    // Initialize them to the smallest possible integer.
    // This avoids having to special case the first elements.
    int max = INT_MIN;
    int second_max = INT_MIN;

    for( int i = 0; i < n; i++ ) {
        // Is it the max?
        if( a[i] > max ) {
            // Make the old max the new 2nd max.
            second_max = max;
            // This is the new max.
            max = a[i];
        }
        // It's not the max, is it the 2nd max?
        else if( a[i] > second_max ) {
            second_max = a[i];
        }
    }

    printf("max: %d, second_max: %d\n", max, second_max);
}

There might be a more elegant way to do it, but that will do, at most, 2n comparisons. At best it will do n.

Note that there's an open question of what to do with { 1, 2, 3, 3 }. Should that return 3, 3 or 2, 3? I'll leave that to you to decide and adjust accordingly.

How to compile multiple java source files in command line

OR you could just use javac file1.java and then also use javac file2.java afterwards.

In Laravel, the best way to pass different types of flash messages in the session

Simply return with the 'flag' that you want to be treated without using any additional user function. The Controller:

return \Redirect::back()->withSuccess( 'Message you want show in View' );

Notice that I used the 'Success' flag.

The View:

@if( Session::has( 'success' ))
     {{ Session::get( 'success' ) }}
@elseif( Session::has( 'warning' ))
     {{ Session::get( 'warning' ) }} <!-- here to 'withWarning()' -->
@endif

Yes, it really works!

How to retrieve element value of XML using Java?

If you are just looking to get a single value from the XML you may want to use Java's XPath library. For an example see my answer to a previous question:

It would look something like:

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class Demo {

    public static void main(String[] args) {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder builder = domFactory.newDocumentBuilder();
            Document dDoc = builder.parse("E:/test.xml");

            XPath xPath = XPathFactory.newInstance().newXPath();
            Node node = (Node) xPath.evaluate("/Request/@name", dDoc, XPathConstants.NODE);
            System.out.println(node.getNodeValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Regular expression to return text between parenthesis

If you want to find all occurences:

>>> re.findall('\(.*?\)',s)
[u"(date='2/xc2/xb2',time='/case/test.png')", u'(eee)']

>>> re.findall('\((.*?)\)',s)
[u"date='2/xc2/xb2',time='/case/test.png'", u'eee']

Convert DOS line endings to Linux line endings in Vim

The comment about getting the ^M to appear is what worked for me. Merely typing "^M" in my vi got nothing (not found). The CTRL+V CTRL+M sequence did it perfectly though.

My working substitution command was

:%s/Ctrl-V Ctrl-M/\r/g

and it looked like this on my screen:

:%s/^M/\r/g

LDAP Authentication using Java

// this class will authenticate LDAP UserName or Email

// simply call LdapAuth.authenticateUserAndGetInfo (username,password);

//Note: Configure ldapURI ,requiredAttributes ,ADSearchPaths,accountSuffex 

import java.util.*;

import javax.naming.*;

import java.util.regex.*;

import javax.naming.directory.*;

import javax.naming.ldap.InitialLdapContext;

import javax.naming.ldap.LdapContext;

public class LdapAuth {


private final static String ldapURI = "ldap://20.200.200.200:389/DC=corp,DC=local";

private final static String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";

private  static String[] requiredAttributes = {"cn","givenName","sn","displayName","userPrincipalName","sAMAccountName","objectSid","userAccountControl"};


// see you active directory user OU's hirarchy 

private  static String[] ADSearchPaths = 

{ 

    "OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=In-House,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Torbram Users,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Migrated Users,OU=TES-Users"

};


private static String accountSuffex = "@corp.local"; // this will be used if user name is just provided


private static void authenticateUserAndGetInfo (String user, String password) throws Exception {

    try {


        Hashtable<String,String> env = new Hashtable <String,String>();

        env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);

        env.put(Context.PROVIDER_URL, ldapURI);     

        env.put(Context.SECURITY_AUTHENTICATION, "simple");

        env.put(Context.SECURITY_PRINCIPAL, user);

        env.put(Context.SECURITY_CREDENTIALS, password);

        DirContext ctx = new InitialDirContext(env);

        String filter = "(sAMAccountName="+user+")";  // default for search filter username

        if(user.contains("@"))  // if user name is a email then
        {
            //String parts[] = user.split("\\@");
            //use different filter for email
            filter = "(userPrincipalName="+user+")";
        }

        SearchControls ctrl = new SearchControls();
        ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctrl.setReturningAttributes(requiredAttributes);

        NamingEnumeration userInfo = null;


        Integer i = 0;
        do
        {
            userInfo = ctx.search(ADSearchPaths[i], filter, ctrl);
            i++;

        } while(!userInfo.hasMore() && i < ADSearchPaths.length );

        if (userInfo.hasMore()) {

            SearchResult UserDetails = (SearchResult) userInfo.next();
            Attributes userAttr = UserDetails.getAttributes();System.out.println("adEmail = "+userAttr.get("userPrincipalName").get(0).toString());

            System.out.println("adFirstName = "+userAttr.get("givenName").get(0).toString());

            System.out.println("adLastName = "+userAttr.get("sn").get(0).toString());

            System.out.println("name = "+userAttr.get("cn").get(0).toString());

            System.out.println("AdFullName = "+userAttr.get("cn").get(0).toString());

        }

        userInfo.close();

    }
    catch (javax.naming.AuthenticationException e) {

    }
}   
}

Split column at delimiter in data frame

@Taesung Shin is right, but then just some more magic to make it into a data.frame. I added a "x|y" line to avoid ambiguities:

df <- data.frame(ID=11:13, FOO=c('a|b','b|c','x|y'))
foo <- data.frame(do.call('rbind', strsplit(as.character(df$FOO),'|',fixed=TRUE)))

Or, if you want to replace the columns in the existing data.frame:

within(df, FOO<-data.frame(do.call('rbind', strsplit(as.character(FOO), '|', fixed=TRUE))))

Which produces:

  ID FOO.X1 FOO.X2
1 11      a      b
2 12      b      c
3 13      x      y

Comparing two java.util.Dates to see if they are in the same day

you can apply the same logic as the SimpleDateFormat solution without relying on SimpleDateFormat

date1.getFullYear()*10000 + date1.getMonth()*100 + date1.getDate() == 
date2.getFullYear()*10000 + date2.getMonth()*100 + date2.getDate()

Unable to Connect to GitHub.com For Cloning

You can try to clone using the HTTPS protocol. Terminal command:

git clone https://github.com/RestKit/RestKit.git

Create an empty list in python with certain size

This code generates an array that contains 10 random numbers.

import random
numrand=[]
for i in range(0,10):
   a = random.randint(1,50)
   numrand.append(a)
   print(a,i)
print(numrand)

How do you make a HTTP request with C++?

The HTTP protocol is very simple, so it is very simple to write a HTTP client. Here is one

https://github.com/pedro-vicente/lib_netsockets

It uses HTTP GET to retrieve a file from a web server, both server and file are command line parameters. The remote file is saved to a local copy.

Disclaimer: I am the author

check http.cc https://github.com/pedro-vicente/lib_netsockets/blob/master/src/http.cc

int http_client_t::get(const char *path_remote_file)
{
  char buf_request[1024];

  //construct request message using class input parameters
  sprintf(buf_request, "GET %s HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", path_remote_file, m_server_ip.c_str());

  //send request, using built in tcp_client_t socket
  if (this->write_all(buf_request, (int)strlen(buf_request)) < 0)
  {
    return -1;
  }

EDIT: edited URL

Is SQL syntax case sensitive?

My understanding is that the SQL standard calls for case-insensitivity. I don't believe any databases follow the standard completely, though.

MySQL has a configuration setting as part of its "strict mode" (a grab bag of several settings that make MySQL more standards-compliant) for case sensitive or insensitive table names. Regardless of this setting, column names are still case-insensitive, although I think it affects how the column-names are displayed. I believe this setting is instance-wide, across all databases within the RDBMS instance, although I'm researching today to confirm this (and hoping the answer is no).

I like how Oracle handles this far better. In straight SQL, identifiers like table and column names are case insensitive. However, if for some reason you really desire to get explicit casing, you can enclose the identifier in double-quotes (which are quite different in Oracle SQL from the single-quotes used to enclose string data). So:

SELECT fieldName
FROM tableName;

will query fieldname from tablename, but

SELECT "fieldName"
FROM "tableName";

will query fieldName from tableName.

I'm pretty sure you could even use this mechanism to insert spaces or other non-standard characters into an identifier.

In this situation if for some reason you found explicitly-cased table and column names desirable it was available to you, but it was still something I would highly caution against.

My convention when I used Oracle on a daily basis was that in code I would put all Oracle SQL keywords in uppercase and all identifiers in lowercase. In documentation I would put all table and column names in uppercase. It was very convenient and readable to be able to do this (although sometimes a pain to type so many capitals in code -- I'm sure I could've found an editor feature to help, here).

In my opinion MySQL is particularly bad for differing about this on different platforms. We need to be able to dump databases on Windows and load them into UNIX, and doing so is a disaster if the installer on Windows forgot to put the RDBMS into case-sensitive mode. (To be fair, part of the reason this is a disaster is our coders made the bad decision, long ago, to rely on the case-sensitivity of MySQL on UNIX.) The people who wrote the Windows MySQL installer made it really convenient and Windows-like, and it was great to move toward giving people a checkbox to say "Would you like to turn on strict mode and make MySQL more standards-compliant?" But it is very convenient for MySQL to differ so signficantly from the standard, and then make matters worse by turning around and differing from its own de facto standard on different platforms. I'm sure that on differing Linux distributions this may be further compounded, as packagers for different distros probably have at times incorporated their own preferred MySQL configuration settings.

Here's another SO question that gets into discussing if case-sensitivity is desirable in an RDBMS.

Adjusting and image Size to fit a div (bootstrap)

You can explicitly define the width and height of images, but the results may not be the best looking.

.food1 img {
    width:100%;
    height: 230px;
}

jsFiddle


...per your comment, you could also just block any overflow - see this example to see an image restricted by height and cut off because it's too wide.

.top1 {
    height:390px;
    background-color:#FFFFFF;
    margin-top:10px;
    overflow: hidden;
}

.top1 img {
    height:100%;
}

When and where to use GetType() or typeof()?

typeof is applied to a name of a type or generic type parameter known at compile time (given as identifier, not as string). GetType is called on an object at runtime. In both cases the result is an object of the type System.Type containing meta-information on a type.

Example where compile-time and run-time types are equal

string s = "hello";

Type t1 = typeof(string);
Type t2 = s.GetType();

t1 == t2 ==> true

Example where compile-time and run-time types are different

object obj = "hello";

Type t1 = typeof(object); // ==> object
Type t2 = obj.GetType();  // ==> string!

t1 == t2 ==> false

i.e., the compile time type (static type) of the variable obj is not the same as the runtime type of the object referenced by obj.


Testing types

If, however, you only want to know whether mycontrol is a TextBox then you can simply test

if (mycontrol is TextBox)

Note that this is not completely equivalent to

if (mycontrol.GetType() == typeof(TextBox))    

because mycontrol could have a type that is derived from TextBox. In that case the first comparison yields true and the second false! The first and easier variant is OK in most cases, since a control derived from TextBox inherits everything that TextBox has, probably adds more to it and is therefore assignment compatible to TextBox.

public class MySpecializedTextBox : TextBox
{
}

MySpecializedTextBox specialized = new MySpecializedTextBox();
if (specialized is TextBox)       ==> true

if (specialized.GetType() == typeof(TextBox))        ==> false

Casting

If you have the following test followed by a cast and T is nullable ...

if (obj is T) {
    T x = (T)obj; // The casting tests, whether obj is T again!
    ...
}

... you can change it to ...

T x = obj as T;
if (x != null) {
    ...
}

Testing whether a value is of a given type and casting (which involves this same test again) can both be time consuming for long inheritance chains. Using the as operator followed by a test for null is more performing.

Starting with C# 7.0 you can simplify the code by using pattern matching:

if (obj is T t) {
    // t is a variable of type T having a non-null value.
    ...
}

Btw.: this works for value types as well. Very handy for testing and unboxing. Note that you cannot test for nullable value types:

if (o is int? ni) ===> does NOT compile!

This is because either the value is null or it is an int. This works for int? o as well as for object o = new Nullable<int>(x);:

if (o is int i) ===> OK!

I like it, because it eliminates the need to access the Nullable<T>.Value property.

The container 'Maven Dependencies' references non existing library - STS

Although it's too late , But here is my experience .

Whenever you get your maven project from a source controller or just copying your project from one machine to another , you need to update the dependencies .

For this Right-click on Project on project explorer -> Maven -> Update Project.

Please consider checking the "Force update of snapshot/releases" checkbox.

If you have not your dependencies in m2/repository then you need internet connection to get from the remote maven repository.

In case you have get from the source controller and you have not any unit test , It's probably your test folder does not include in the source controller in the first place , so you don't have those in the new repository.so you need to create those folders manually.

I have had both these cases .

Getting an odd error, SQL Server query using `WITH` clause

In some cases this also occurs if you have table hints and you have spaces between WITH clause and your hint, so best to type it like:

SELECT Column1 FROM Table1 t1 WITH(NOLOCK)
INNER JOIN Table2 t2 WITH(NOLOCK) ON t1.Column1 = t2.Column1

And not:

SELECT Column1 FROM Table1 t1 WITH (NOLOCK)
INNER JOIN Table2 t2 WITH (NOLOCK) ON t1.Column1 = t2.Column1

How to give color to each class in scatter plot in R?

Here is a solution using traditional graphics (and Dirk's data):

> DF <- data.frame(x=1:10, y=rnorm(10)+5, z=sample(letters[1:3], 10, replace=TRUE)) 
> DF
    x        y z
1   1 6.628380 c
2   2 6.403279 b
3   3 6.708716 a
4   4 7.011677 c
5   5 6.363794 a
6   6 5.912945 b
7   7 2.996335 a
8   8 5.242786 c
9   9 4.455582 c
10 10 4.362427 a
> attach(DF); plot(x, y, col=c("red","blue","green")[z]); detach(DF)

This relies on the fact that DF$z is a factor, so when subsetting by it, its values will be treated as integers. So the elements of the color vector will vary with z as follows:

> c("red","blue","green")[DF$z]
 [1] "green" "blue"  "red"   "green" "red"   "blue"  "red"   "green" "green" "red"    

You can add a legend using the legend function:

legend(x="topright", legend = levels(DF$z), col=c("red","blue","green"), pch=1)

How to Fill an array from user input C#?

Try:

array[i] = Convert.ToDouble(Console.Readline());

You might also want to use double.TryParse() to make sure that the user didn't enter bogus text and handle that somehow.

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

For some databases, you can just explicitly insert a NULL into the auto_increment column:

INSERT INTO table_name VALUES (NULL, 'my name', 'my group')

Android TextView padding between lines

If you want padding between text try LineSpacingExtra="10dp"

<TextView
        android:layout_width="match_parent"
        android:layout_height="180dp"
        android:lineSpacingExtra="10dp"/>

Using Tempdata in ASP.NET MVC - Best practice

TempData is a bucket where you can dump data that is only needed for the following request. That is, anything you put into TempData is discarded after the next request completes. This is useful for one-time messages, such as form validation errors. The important thing to take note of here is that this applies to the next request in the session, so that request can potentially happen in a different browser window or tab.

To answer your specific question: there's no right way to use it. It's all up to usability and convenience. If it works, makes sense and others are understanding it relatively easy, it's good. In your particular case, the passing of a parameter this way is fine, but it's strange that you need to do that (code smell?). I'd rather keep a value like this in resources (if it's a resource) or in the database (if it's a persistent value). From your usage, it seems like a resource, since you're using it for the page title.

Hope this helps.

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

I had the same error and SOLVED by removing the DB roles db_denydatawriter and db_denydatreader of the DB user. For that, select the appropriate DB user on logins >> properties >> user mappings >> find out DB and select it >> uncheck the mentioned Db user roles. Thats it !!

WCF timeout exception detailed investigation

Looks like this exception message is quite generic and can be received due to a variety of reasons. We ran into this while deploying the client on Windows 8.1 machines. Our WCF client runs inside of a windows service and continuously polls the WCF service. The windows service runs under a non-admin user. The issue was fixed by setting the clientCredentialType to "Windows" in the WCF configuration to allow the authentication to pass-through, as in the following:

      <security mode="None">
        <transport clientCredentialType="Windows" proxyCredentialType="None"
          realm="" />
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>

What is a singleton in C#?

Here's what singleton is: http://en.wikipedia.org/wiki/Singleton_pattern

I don't know C#, but it's actually the same thing in all languages, only implementation differs.

You should generally avoid singleton when it's possible, but in some situations it's very convenient.

Sorry for my English ;)

rebase in progress. Cannot commit. How to proceed or stop (abort)?

I setup my git to autorebase on a git checkout

# in my ~/.gitconfig file
[branch]
    autosetupmerge = always
    autosetuprebase = always

Otherwise, it automatically merges when you switch between branches, which I think is the worst possible choice as the default.

However, this has a side effect, when I switch to a branch and then git cherry-pick <commit-id> I end up in this weird state every single time it has a conflict.

I actually have to abort the rebase, but first I fix the conflict, git add /path/to/file the file (another very strange way to resolve the conflict in this case?!), then do a git commit -i /path/to/file. Now I can abort the rebase:

git checkout <other-branch>
git cherry-pick <commit-id>
...edit-conflict(s)...
git add path/to/file
git commit -i path/to/file
git rebase --abort
git commit .
git push --force origin <other-branch>

The second git commit . seems to come from the abort. I'll fix my answer if I find out that I should abort the rebase sooner.

The --force on the push is required if you skip other commits and both branches are not smooth (both are missing commits from the other).

Xpath: select div that contains class AND whose specific child element contains text

You could use the xpath :

//div[@class="measure-tab" and .//span[contains(., "someText")]]

Input :

<root>
<div class="measure-tab">
  <td> someText</td>
</div>
<div class="measure-tab">
  <div>
    <div2>
       <span>someText2</span>
   </div2>
  </div>
</div>
</root>

Output :

    Element='<div class="measure-tab">
  <div>
    <div2>
      <span>someText2</span>
    </div2>
  </div>
</div>'

Simple example of threading in C++

Well, technically any such object will wind up being built over a C-style thread library because C++ only just specified a stock std::thread model in c++0x, which was just nailed down and hasn't yet been implemented. The problem is somewhat systemic, technically the existing c++ memory model isn't strict enough to allow for well defined semantics for all of the 'happens before' cases. Hans Boehm wrote an paper on the topic a while back and was instrumental in hammering out the c++0x standard on the topic.

http://www.hpl.hp.com/techreports/2004/HPL-2004-209.html

That said there are several cross-platform thread C++ libraries that work just fine in practice. Intel thread building blocks contains a tbb::thread object that closely approximates the c++0x standard and Boost has a boost::thread library that does the same.

http://www.threadingbuildingblocks.org/

http://www.boost.org/doc/libs/1_37_0/doc/html/thread.html

Using boost::thread you'd get something like:

#include <boost/thread.hpp>

void task1() { 
    // do stuff
}

void task2() { 
    // do stuff
}

int main (int argc, char ** argv) {
    using namespace boost; 
    thread thread_1 = thread(task1);
    thread thread_2 = thread(task2);

    // do other stuff
    thread_2.join();
    thread_1.join();
    return 0;
}

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

As @user3483203 pointed out, numpy.select is the best approach

Store your conditional statements and the corresponding actions in two lists

conds = [(df['eri_hispanic'] == 1),(df[['eri_afr_amer', 'eri_asian', 'eri_hawaiian', 'eri_nat_amer', 'eri_white']].sum(1).gt(1)),(df['eri_nat_amer'] == 1),(df['eri_asian'] == 1),(df['eri_afr_amer'] == 1),(df['eri_hawaiian'] == 1),(df['eri_white'] == 1,])

actions = ['Hispanic', 'Two Or More', 'A/I AK Native', 'Asian', 'Black/AA', 'Haw/Pac Isl.', 'White']

You can now use np.select using these lists as its arguments

df['label_race'] = np.select(conds,actions,default='Other')

Reference: https://numpy.org/doc/stable/reference/generated/numpy.select.html

How to get complete month name from DateTime

You can use Culture to get month name for your country like:

System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("ar-EG");
string FormatDate = DateTime.Now.ToString("dddd., MMM dd yyyy, hh:MM tt", culture);

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

for this error:

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

you need to:

Import java.sql.*;
Import com.mysql.jdbc.Driver;

even if its not used till app running.

How to check if an element is visible with WebDriver

    try{
        if( driver.findElement(By.xpath("//div***")).isDisplayed()){
          System.out.println("Element is Visible");
        }
}
catch(NoSuchElementException e){
   else{
     System.out.println("Element is InVisible");
        }
}

How can I add private key to the distribution certificate?

This site explain step by step that what you need to do Certificates, Identifiers & Profiles and as your question

"Valid Signing identity not found"?

You need the private key that were used to sign the code base with provisioning profile. . If you don't have then you can generate a new signing request on the iOS developer portal.

For Export:

Xcode -> Organizer, select your team. Click Export. Specify a filename and a password, and click Save.`

For Import:

Xcode -> Organizer, select your team. Click Import. Select the file containing your code signing assets. Enter the password for the file, and click Open.

Setting initial values on load with Select2 with Ajax

Maybe this work for you!! This works for me...

initSelection: function (element, callback) {

            callback({ id: 1, text: 'Text' });
}

Check very well that code is correctly spelled, my issue was in the initSelection, I had initselection

TextView - setting the text size programmatically doesn't seem to work

This fixed the issue for me. I got uniform font size across all devices.

 textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,getResources().getDimension(R.dimen.font));

Python read-only property

Notice that instance methods are also attributes (of the class) and that you could set them at the class or instance level if you really wanted to be a badass. Or that you may set a class variable (which is also an attribute of the class), where handy readonly properties won't work neatly out of the box. What I'm trying to say is that the "readonly attribute" problem is in fact more general than it's usually perceived to be. Fortunately there are conventional expectations at work that are so strong as to blind us wrt these other cases (after all, almost everything is an attribute of some sort in python).

Building upon these expectations I think the most general and lightweight approach is to adopt the convention that "public" (no leading underscore) attributes are readonly except when explicitly documented as writeable. This subsumes the usual expectation that methods won't be patched and class variables indicating instance defaults are better let alone. If you feel really paranoid about some special attribute, use a readonly descriptor as a last resource measure.

what does this mean ? image/png;base64?

It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.

(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)

Is there a css cross-browser value for "width: -moz-fit-content;"?

Why not use some brs?

<div class="mydiv-centerer">
    <div class="mydiv">Some content</div><br />
    <div class="mydiv">More content than before</div><br />
    <div class="mydiv">Here is a lot of content that
                       I was not anticipating</div>    
</div>

CSS

.mydiv-centerer{
    text-align: center;
}

.mydiv{
    background: none no-repeat scroll 0 0 rgba(1, 56, 110, 0.7);
    border-radius: 10px 10px 10px 10px;
    box-shadow: 0 0 5px #0099FF;
    color: white;
    margin: 10px auto;
    padding: 10px;
    text-align: justify;
    display:inline-block;
}

Example: http://jsfiddle.net/YZV25/

how do I loop through a line from a csv file in powershell

A slightly other way of iterating through each column of each line of a CSV-file would be

$path = "d:\scratch\export.csv"
$csv = Import-Csv -path $path

foreach($line in $csv)
{ 
    $properties = $line | Get-Member -MemberType Properties
    for($i=0; $i -lt $properties.Count;$i++)
    {
        $column = $properties[$i]
        $columnvalue = $line | Select -ExpandProperty $column.Name

        # doSomething $column.Name $columnvalue 
        # doSomething $i $columnvalue 
    }
} 

so you have the choice: you can use either $column.Name to get the name of the column, or $i to get the number of the column

Difference between Console.Read() and Console.ReadLine()?

Console.Read()

=> reads only one character from the standard input

Console.ReadLine()

=> reads all characters in the line from the standard input

Matrix multiplication in OpenCV

You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.

Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple * operator:

C = A * B

Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul() function:

output = A.mul(B);

How do I remove the title bar from my app?

this.requestWindowFeature(Window.FEATURE_NO_TITLE);

in onCreate() works!

Proper use of mutexes in Python

You have to unlock your Mutex at sometime...

Java Initialize an int array in a constructor

This is because, in the constructor, you declared a local variable with the same name as an attribute.

To allocate an integer array which all elements are initialized to zero, write this in the constructor:

data = new int[3];

To allocate an integer array which has other initial values, put this code in the constructor:

int[] temp = {2, 3, 7};
data = temp;

or:

data = new int[] {2, 3, 7};

Scroll to bottom of div with Vue.js

2021 easy solution that won't hurt your brain... use el.scrollIntoView()

Here is a fiddle.

This solution will not hurt your brain having to think about scrollTop or scrollHeight, has smooth scrolling built in, and even works in IE.

scrollIntoView() has options you can pass it like scrollIntoView({behavior: 'smooth'}) to get smooth scrolling.

methods: {
  scrollToElement() {
    const el = this.$el.getElementsByClassName('scroll-to-me')[0];

    if (el) {
      // Use el.scrollIntoView() to instantly scroll to the element
      el.scrollIntoView({behavior: 'smooth'});
    }
  }
}

Then if you wanted to scroll to this element on page load you could call this method like this:

mounted() {
  this.scrollToElement();
}

Else if you wanted to scroll to it on a button click or some other action you could call it the same way:

<button @click="scrollToElement">scroll to me</button>

The scroll works all the way down to IE 8. The smooth scroll effect does not work out of the box in IE or Safari. If needed there is a polyfill available for this here as @mostafaznv mentioned in the comments.

Are querystring parameters secure in HTTPS (HTTP + SSL)?

The entire transmission, including the query string, the whole URL, and even the type of request (GET, POST, etc.) is encrypted when using HTTPS.

How to get a value inside an ArrayList java

import java.util.*;
import java.lang.*;
import java.io.*;

class hari
{
public static void main (String[] args) throws Exception
{  Scanner s=new Scanner(System.in);
    int i=0;
    int b=0;
    HashSet<Integer> h=new HashSet<Integer>();
    try{
        for(i=0;i<1000;i++)
    {   b=s.nextInt();
        h.add(b);
    }
    }
    catch(Exception e){
        System.out.println(h+","+h.size());
    }
}}

ValueError: invalid literal for int () with base 10

This could also happen when you have to map space separated integers to a list but you enter the integers line by line using the .input(). Like for example I was solving this problem on HackerRank Bon-Appetit, and the got the following error while compiling enter image description here

So instead of giving input to the program line by line try to map the space separated integers into a list using the map() method.

Converting an object to a string

There is actually one easy option (for recent browsers and Node.js) missing in the existing answers:

console.log('Item: %o', o);

I would prefer this as JSON.stringify() has certain limitations (e.g. with circular structures).

Count with IF condition in MySQL query

Better still (or shorter anyway):

SUM(ccc_news_comments.id = 'approved')

This works since the Boolean type in MySQL is represented as INT 0 and 1, just like in C. (May not be portable across DB systems though.)

As for COALESCE() as mentioned in other answers, many language APIs automatically convert NULL to '' when fetching the value. For example with PHP's mysqli interface it would be safe to run your query without COALESCE().

Emulate/Simulate iOS in Linux

BrowserStack.com
On this site, you can emulate a lot of iOS's devices online.

Java: Rotating Images

This is how you can do it. This code assumes the existance of a buffered image called 'image' (like your comment says)

// The required drawing location
int drawLocationX = 300;
int drawLocationY = 300;

// Rotation information

double rotationRequired = Math.toRadians (45);
double locationX = image.getWidth() / 2;
double locationY = image.getHeight() / 2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);

// Drawing the rotated image at the required drawing locations
g2d.drawImage(op.filter(image, null), drawLocationX, drawLocationY, null);

Getting NetworkCredential for current user (C#)

You can get the user name using System.Security.Principal.WindowsIdentity.GetCurrent() but there is not way to get current user password!

Compiling a C++ program with gcc

use g++ instead of gcc.

Regular expression for validating names and surnames?

This one worked perfectly for me in JavaScript: ^[a-zA-Z]+[\s|-]?[a-zA-Z]+[\s|-]?[a-zA-Z]+$

Here is the method:

function isValidName(name) {
    var found = name.search(/^[a-zA-Z]+[\s|-]?[a-zA-Z]+[\s|-]?[a-zA-Z]+$/);
    return found > -1;
}

Initializing IEnumerable<string> In C#

public static IEnumerable<string> GetData()
{
    yield return "1";
    yield return "2";
    yield return "3";
}

IEnumerable<string> m_oEnum = GetData();

Real differences between "java -server" and "java -client"?

One difference I've just noticed is that in "client" mode, it seems the JVM actually gives some unused memory back to the operating system, whereas with "server" mode, once the JVM grabs the memory, it won't give it back. Thats how it appears on Solaris with Java6 anyway (using prstat -Z to see the amount of memory allocated to a process).

How do I get Flask to run on port 80?

If you want your application on same port i.e port=5000 then just in your terminal run this command:

fuser -k 5000/tcp

and then run:

python app.py

If you want to run on a specified port, e.g. if you want to run on port=80, in your main file just mention this:

if __name__ == '__main__':  
    app.run(host='0.0.0.0', port=80)

Can I convert a C# string value to an escaped string literal

Hallgrim's answer is excellent, but the "+", newline and indent additions were breaking functionality for me. An easy way around it is:

private static string ToLiteral(string input)
{
    using (var writer = new StringWriter())
    {
        using (var provider = CodeDomProvider.CreateProvider("CSharp"))
        {
            provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, new CodeGeneratorOptions {IndentString = "\t"});
            var literal = writer.ToString();
            literal = literal.Replace(string.Format("\" +{0}\t\"", Environment.NewLine), "");
            return literal;
        }
    }
}

Missing MVC template in Visual Studio 2015

I had the same issue with the MVC template not appearing in VS2015.

I checked Web Developer Tools when originally installing. It was still checked when trying to Modify the install. I tried unchecking and updating the install but next time I went back to Modify, it was still checked. And still no MVC template.

I got it working by uninstalling: Microsoft ASP.NET Web Frameworks and Tools 2015 via the Programs and Features windows and re-installing. Here's the link for those who don't have it.

Get Current date & time with [NSDate date]

NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];  

or use

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM 
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);

How can I convert a std::string to int?

From http://www.cplusplus.com/reference/string/stoi/

// stoi example
#include <iostream>   // std::cout
#include <string>     // std::string, std::stoi

int main ()
{
  std::string str_dec = "2001, A Space Odyssey";
  std::string str_hex = "40c3";
  std::string str_bin = "-10010110001";
  std::string str_auto = "0x7f";

  std::string::size_type sz;   // alias of size_t

  int i_dec = std::stoi (str_dec,&sz);
  int i_hex = std::stoi (str_hex,nullptr,16);
  int i_bin = std::stoi (str_bin,nullptr,2);
  int i_auto = std::stoi (str_auto,nullptr,0);

  std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";
  std::cout << str_hex << ": " << i_hex << '\n';
  std::cout << str_bin << ": " << i_bin << '\n';
  std::cout << str_auto << ": " << i_auto << '\n';

  return 0;
}

Output:

2001, A Space Odyssey: 2001 and [, A Space Odyssey]

40c3: 16579

-10010110001: -1201

0x7f: 127

How to override and extend basic Django admin templates?

for app index add this line to somewhere common py file like url.py

admin.site.index_template = 'admin/custom_index.html'

for app module index : add this line to admin.py

admin.AdminSite.app_index_template = "servers/servers-home.html"

for change list : add this line to admin class:

change_list_template = "servers/servers_changelist.html"

for app module form template : add this line to your admin class

change_form_template = "servers/server_changeform.html"

etc. and find other in same admin's module classes

How to return history of validation loss in Keras

The following simple code works great for me:

    seqModel =model.fit(x_train, y_train,
          batch_size      = batch_size,
          epochs          = num_epochs,
          validation_data = (x_test, y_test),
          shuffle         = True,
          verbose=0, callbacks=[TQDMNotebookCallback()]) #for visualization

Make sure you assign the fit function to an output variable. Then you can access that variable very easily

# visualizing losses and accuracy
train_loss = seqModel.history['loss']
val_loss   = seqModel.history['val_loss']
train_acc  = seqModel.history['acc']
val_acc    = seqModel.history['val_acc']
xc         = range(num_epochs)

plt.figure()
plt.plot(xc, train_loss)
plt.plot(xc, val_loss)

Hope this helps. source: https://keras.io/getting-started/faq/#how-can-i-record-the-training-validation-loss-accuracy-at-each-epoch

Access-Control-Allow-Origin error sending a jQuery Post to Google API's

I solved the Access-Control-Allow-Origin error modifying the dataType parameter to dataType:'jsonp' and adding a crossDomain:true

$.ajax({

    url: 'https://www.googleapis.com/moderator/v1/series?key='+key,
    data: myData,
    type: 'GET',
    crossDomain: true,
    dataType: 'jsonp',
    success: function() { alert("Success"); },
    error: function() { alert('Failed!'); },
    beforeSend: setHeader
});

Add empty columns to a dataframe with specified names from a vector

The problem with your code is in the line:

for(i in length(namevector))

You need to ask yourself: what is length(namevector)? It's one number. So essentially you're saying:

for(i in 11)
df[,i] <- NA

Or more simply:

df[,11] <- NA

That's why you're getting an error. What you want is:

for(i in namevector)
    df[,i] <- NA

Or more simply:

df[,namevector] <- NA

Add/delete row from a table

Hi I would do something like this:

var id = 4; // inital number of rows plus one
function addRow(){
   // add a new tr with id 
   // increment id;
}

function deleteRow(id){
   $("#" + id).remove();
}

and i would have a table like this:

<table id = 'dsTable' >
      <tr id=1>
         <td> Relationship Type </td>
         <td> Date of Birth </td>
         <td> Gender </td>
      </tr>
      <tr id=2>
         <td> Spouse </td>
         <td> 1980-22-03 </td>
         <td> female </td>
         <td> <input type="button" id ="addDep" value="Add" onclick = "add()" </td>
         <td> <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(2)"  </td>
      </tr>
       <tr id=3>
         <td> Child </td>
         <td> 2008-23-06 </td>
         <td> female </td>
         <td> <input type="button" id ="addDep" value="Add" onclick = "add()"</td>
         <td>  <input type="button" id ="deleteDep" value="Delete" onclick = "deleteRow(3)" </td>
      </tr>
   </table>

Also if you want you can make a loop to build up the table. So it will be easy to build the table. The same you can do with edit:)

Alternative Windows shells, besides CMD.EXE?

  1. Hard to copy and paste.

    Not true. Enable QuickEdit, either in the properties of the shortcut, or in the properties of the CMD window (right-click on the title bar), and you can mark text directly. Right-click copies marked text into the clipboard. When no text is marked, a right-click pastes text from the clipboard.

    enter image description here

  2. Hard to resize the window.

    True. Console2 (see below) does not have this limitation.

  3. Hard to open another window (no menu options do this).

    Not true. Use start cmd or define an alias if that's too much hassle:

    doskey nw=start cmd /k $*
    
  4. Seems to always start in C:\Windows\System32, which is super useless.

    Not true. Or rather, not true if you define a start directory in the properties of the shortcut

    enter image description here

    or by modifying the AutoRun registry value. Shift-right-click on a folder allows you to launch a command prompt in that folder.

  5. Weird scrolling. Sometimes it scrolls down really far into blank space, and you have to scroll up to where the window is actually populated

    Never happened to me.

An alternative to plain CMD is Console2, which uses CMD under the hood, but provides a lot more configuration options.

javax.servlet.ServletException cannot be resolved to a type in spring web app

It seems to me that eclipse doesn't recognize the java ee web api (servlets, el, and so on). If you're using maven and don't want to configure eclipse with a specified server runtime, put the dependecy below in your web project pom:

<dependency>  
    <groupId>javax</groupId>    
    <artifactId>javaee-web-api</artifactId>    
    <version>7.0</version> <!-- Put here the version of your Java EE app, in my case 7.0 -->
    <scope>provided</scope>
</dependency>

Undefined symbols for architecture armv7

In my case, I'd added a framework that must be using Objective C++. I found this post:

XCode .m vs. .mm

that explained how the main.m needed to be renamed to main.mm so that the Objective-C++ classes could be compiled, too.

That fixed it for me.

batch file to check 64bit or 32bit OS

I use either of the following:

:CheckOS
IF EXIST "%PROGRAMFILES(X86)%" (GOTO 64BIT) ELSE (GOTO 32BIT)

:64BIT
echo 64-bit...
GOTO END

:32BIT
echo 32-bit...
GOTO END

:END

or I set the bit variable, which I later use in my script to run the correct setup.

:CheckOS
IF EXIST "%PROGRAMFILES(X86)%" (set bit=x64) ELSE (set bit=x86)

or...

:CheckOS
IF "%PROCESSOR_ARCHITECTURE%"=="x86" (set bit=x86) else (set bit=x64)

Hope this helps.

How to check if a file exists in the Documents directory in Swift?

Nowadays (2016) Apple recommends more and more to use the URL related API of NSURL, NSFileManager etc.

To get the documents directory in iOS and Swift 2 use

let documentDirectoryURL = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, 
                                 inDomain: .UserDomainMask, 
                        appropriateForURL: nil, 
                                   create: true)

The try! is safe in this case because this standard directory is guaranteed to exist.

Then append the appropriate path component for example an sqlite file

let databaseURL = documentDirectoryURL.URLByAppendingPathComponent("MyDataBase.sqlite")

Now check if the file exists with checkResourceIsReachableAndReturnError of NSURL.

let fileExists = databaseURL.checkResourceIsReachableAndReturnError(nil)

If you need the error pass the NSError pointer to the parameter.

var error : NSError?
let fileExists = databaseURL.checkResourceIsReachableAndReturnError(&error)
if !fileExists { print(error) }

Swift 3+:

let documentDirectoryURL = try! FileManager.default.url(for: .documentDirectory, 
                                in: .userDomainMask, 
                    appropriateFor: nil, 
                            create: true)

let databaseURL = documentDirectoryURL.appendingPathComponent("MyDataBase.sqlite")

checkResourceIsReachable is marked as can throw

do {
    let fileExists = try databaseURL.checkResourceIsReachable()
    // handle the boolean result
} catch let error as NSError {
    print(error)
}

To consider only the boolean return value and ignore the error use the nil-coalescing operator

let fileExists = (try? databaseURL.checkResourceIsReachable()) ?? false