Programs & Examples On #Nimbus

Nimbus is a polished cross-platform look and feel introduced in the Java SE 6 Update 10 (6u10) release of the Java platform. Nimbus uses Java 2D vector graphics to draw the user interface, rather than static bitmaps, so the UI can be crisply rendered at any resolution.

Can a website detect when you are using Selenium with chromedriver?

It seems to me the simplest way to do it with Selenium is to intercept the XHR that sends back the browser fingerprint.

But since this is a Selenium-only problem, its better just to use something else. Selenium is supposed to make things like this easier, not way harder.

How to show first commit by 'git log'?

Not the most beautiful way of doing it I guess:

git log --pretty=oneline | wc -l

This gives you a number then

git log HEAD~<The number minus one>

How to load local html file into UIWebView

by this you can load html file which is in your project Assets(bundle) to webView.

 UIWebView *web = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
    [web loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] 
                                pathForResource:@"test" ofType:@"html"]isDirectory:NO]]];

may be this is useful to you.

How can I simulate a click to an anchor tag?

Here is a complete test case that simulates the click event, calls all handlers attached (however they have been attached), maintains the "target" attribute ("srcElement" in IE), bubbles like a normal event would, and emulates IE's recursion-prevention. Tested in FF 2, Chrome 2.0, Opera 9.10 and of course IE (6):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function fakeClick(event, anchorObj) {
  if (anchorObj.click) {
    anchorObj.click()
  } else if(document.createEvent) {
    if(event.target !== anchorObj) {
      var evt = document.createEvent("MouseEvents"); 
      evt.initMouseEvent("click", true, true, window, 
          0, 0, 0, 0, 0, false, false, false, false, 0, null); 
      var allowDefault = anchorObj.dispatchEvent(evt);
      // you can check allowDefault for false to see if
      // any handler called evt.preventDefault().
      // Firefox will *not* redirect to anchorObj.href
      // for you. However every other browser will.
    }
  }
}
</script>
</head>
<body>

<div onclick="alert('Container clicked')">
  <a id="link" href="#" onclick="alert((event.target || event.srcElement).innerHTML)">Normal link</a>
</div>

<button type="button" onclick="fakeClick(event, document.getElementById('link'))">
  Fake Click on Normal Link
</button>

<br /><br />

<div onclick="alert('Container clicked')">
    <div onclick="fakeClick(event, this.getElementsByTagName('a')[0])"><a id="link2" href="#" onclick="alert('foo')">Embedded Link</a></div>
</div>

<button type="button" onclick="fakeClick(event, document.getElementById('link2'))">Fake Click on Embedded Link</button>

</body>
</html>

Demo here.

It avoids recursion in non-IE browsers by inspecting the event object that is initiating the simulated click, by inspecting the target attribute of the event (which remains unchanged during propagation).

Obviously IE does this internally holding a reference to its global event object. DOM level 2 defines no such global variable, so for that reason the simulator must pass in its local copy of event.

How do we check if a pointer is NULL pointer?

Apparently the thread you refer is about C++.

In C your snippet will always work. I like the simpler if (p) { /* ... */ }.

Compare two Lists for differences

I think you're looking for a method like this:

public static IEnumerable<TResult> CompareSequences<T1, T2, TResult>(IEnumerable<T1> seq1,
    IEnumerable<T2> seq2, Func<T1, T2, TResult> comparer)
{
    var enum1 = seq1.GetEnumerator();
    var enum2 = seq2.GetEnumerator();

    while (enum1.MoveNext() && enum2.MoveNext())
    {
        yield return comparer(enum1.Current, enum2.Current);
    }
}

It's untested, but it should do the job nonetheless. Note that what's particularly useful about this method is that it's full generic, i.e. it can take two sequences of arbitrary (and different) types and return objects of any type.

This solution of course assumes that you want to compare the nth item of seq1 with the nth item in seq2. If you want to do match the elements in the two sequences based on a particular property/comparison, then you'll want to perform some sort of join operation (as suggested by danbruc using Enumerable.Join. Do let me know if it neither of these approaches is quite what I'm after and maybe I can suggest something else.

Edit: Here's an example of how you might use the CompareSequences method with the comparer function you originally posted.

// Prints out to the console all the results returned by the comparer function (CompareTwoClass_ReturnDifferences in this case).
var results = CompareSequences(list1, list2, CompareTwoClass_ReturnDifferences);
int index;    

foreach(var element in results)
{
    Console.WriteLine("{0:#000} {1}", index++, element.ToString());
}

How do I install Maven with Yum?

This is what I went through on Amazon/AWS EMR v5. (Adapted from the previous answers), to have Maven and Java8.

sudo wget https://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo
sudo sed -i s/\$releasever/6/g /etc/yum.repos.d/epel-apache-maven.repo
sudo yum install -y apache-maven
sudo alternatives --config java

pick Java8

sudo alternatives --config javac

pick Java8

Now, if you run:

mvn -version

You should get:

Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T07:58:13Z)
Maven home: /usr/share/apache-maven
Java version: 1.8.0_171, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.171-8.b10.38.amzn1.x86_64/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "4.14.47-56.37.amzn1.x86_64", arch: "amd64", family: “unix"

Vue.js: Conditional class style binding

the problem is blade, try this

<i class="fa" v-bind:class="['{{content['cravings']}}' ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline']"></i>

Possible to view PHP code of a website?

A bug or security vulnerability in the server (either Apache or the PHP engine), or your own PHP code, might allow an attacker to obtain access to your code.

For instance if you have a PHP script to allow people to download files, and an attacker can trick this script into download some of your PHP files, then your code can be leaked.

Since it's impossible to eliminate all bugs from the software you're using, if someone really wants to steal your code, and they have enough resources, there's a reasonable chance they'll be able to.

However, as long as you keep your server up-to-date, someone with casual interest is not able to see the PHP source unless there are some obvious security vulnerabilities in your code.

Read the Security section of the PHP manual as a starting point to keeping your code safe.

Hash function for a string

Hash functions for algorithmic use have usually 2 goals, first they have to be fast, second they have to evenly distibute the values across the possible numbers. The hash function also required to give the all same number for the same input value.

if your values are strings, here are some examples for bad hash functions:

  1. string[0] - the ASCII characters a-Z are way more often then others
  2. string.lengh() - the most probable value is 1

Good hash functions tries to use every bit of the input while keeping the calculation time minimal. If you only need some hash code, try to multiply the bytes with prime numbers, and sum them.

How to kill a process in MacOS?

If kill -9 isn't working, then neither will killall (or even killall -9 which would be more "intense"). Apparently the chromium process is stuck in a non-interruptible system call (i.e., in the kernel, not in userland) -- didn't think MacOSX had any of those left, but I guess there's always one more:-(. If that process has a controlling terminal you can probably background it and kill it while backgrounded; otherwise (or if the intense killing doesn't work even once the process is bakcgrounded) I'm out of ideas and I'm thinking you might have to reboot:-(.

How to override Bootstrap's Panel heading background color?

Just check the bootstrap. CSS and search for the class panel-heading and copy the default code.

Copy the default CSS to your personal CSS but vive it a diference classname like my-panel-header for example.

Edit the css Code from the new clones class created.

Add line break to 'git commit -m' from the command line

I don't see anyone mentioning that if you don't provide a message it will open nano for you (at least in Linux) where you can write multiple lines...

Only this is needed:

git commit

How to transform array to comma separated words string?

You're looking for implode()

$string = implode(",", $array);

add string to String array

You cannot resize an array in java.

Once the size of array is declared, it remains fixed.

Instead you can use ArrayList that has dynamic size, meaning you don't need to worry about its size. If your array list is not big enough to accommodate new values then it will be resized automatically.

ArrayList<String> ar = new ArrayList<String>();
String s1 ="Test1";
String s2 ="Test2";
String s3 ="Test3";
ar.add(s1);
ar.add(s2);
ar.add(s3);

String s4 ="Test4";
ar.add(s4);

PHP Fatal error: Cannot redeclare class

Did You use Zend Framework? I have the same problem too.
I solved it by commenting out this the following line in config/application.ini:

;includePaths.library = APPLICATION_PATH "/../library"

I hope this will help you.

How can I close a Twitter Bootstrap popover with a click from anywhere (else) on the page?

I do it as below

$("a[rel=popover]").click(function(event){
    if(event.which == 1)
    {   
        $thisPopOver = $(this);
        $thisPopOver.popover('toggle');
        $thisPopOver.parent("li").click(function(event){
            event.stopPropagation();
            $("html").click(function(){
                $thisPopOver.popover('hide');
            });
        });
    }
});

Hope this helps!

Convert integer to hex and hex to integer

Below are two functions: dbo.HexToInt and dbo.IntToHex, I use them for such conversion:

if OBJECT_ID('dbo.HexToInt') is not null
    drop function dbo.HexToInt
GO
create function dbo.HexToInt (@chars varchar(max))
returns int
begin
    declare @char varchar(1), @len int, @i int, @r int, @tmp int, @pow int
    set @chars = RTRIM(LTRIM(@chars))
    set @len = LEN(@chars)
    set @i = 1
    set @r = 0
    while @i <= @len
    begin
        set @pow = @len - @i
        set @char = SUBSTRING(@chars, @i, 1)
        if @char = '0'
            set @tmp = 0
        else if @char = '1'
            set @tmp = 1
        else if @char = '2'
            set @tmp = 2
        else if @char = '3'
            set @tmp = 3
        else if @char = '4'
            set @tmp = 4
        else if @char = '5'
            set @tmp = 5
        else if @char = '6'
            set @tmp = 6
        else if @char = '7'
            set @tmp = 7
        else if @char = '8'
            set @tmp = 8
        else if @char = '9'
            set @tmp = 9
        else if @char = 'A'
            set @tmp = 10
        else if @char = 'B'
            set @tmp = 11
        else if @char = 'C'
            set @tmp = 12
        else if @char = 'D'
            set @tmp = 13
        else if @char = 'E'
            set @tmp = 14
        else if @char = 'F'
            set @tmp = 15
        set @r = @r + @tmp * POWER(16,@pow)
        set @i = @i + 1     
    end
    return @r
end

And the second one:

if OBJECT_ID('dbo.IntToHex') is not null
    drop function dbo.IntToHex
GO
create function dbo.IntToHex (@val int)
returns varchar(max)
begin
    declare @r varchar(max), @tmp int, @v1 int, @v2 int, @char varchar(1)
    set @tmp = @val
    set @r = ''
    while 1=1
    begin
        set @v1 = @tmp / 16
        set @v2 = @tmp % 16
        if @v2 = 0
            set @char = '0'
        else if @v2 = 1
            set @char = '1'
        else if @v2 = 2
            set @char = '2'
        else if @v2 = 3
            set @char = '3'
        else if @v2 = 4
            set @char = '4'
        else if @v2 = 5
            set @char = '5'
        else if @v2 = 6
            set @char = '6'
        else if @v2 = 7
            set @char = '7'
        else if @v2 = 8
            set @char = '8'
        else if @v2 = 9
            set @char = '9'
        else if @v2 = 10
            set @char = 'A'
        else if @v2 = 11
            set @char = 'B'
        else if @v2 = 12
            set @char = 'C'
        else if @v2 = 13
            set @char = 'D'
        else if @v2 = 14
            set @char = 'E'
        else if @v2 = 15
            set @char = 'F'
        set @tmp = @v1 
        set @r = @char + @r
        if @tmp = 0
            break
    end
    return @r
end

Move cursor to end of file in vim

Try doing SHIFT + G and you will be at the end of the page, but you can't edit yet. Go to the top by doing G + G

Hiding a button in Javascript

<script>
    $('#btn_hide').click( function () {
      $('#btn_hide').hide();
    });
</script>
<input type="button" id="btn_hide"/>

this will be enough

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

For session cookies it doesn't seem to be supported in Tomcat yet. See the bug report Need to add support for HTTPOnly session cookie parameter. A somewhat involved work-around for now can be found here, which basically boils down to manually patching Tomcat. Can't really find an easy way to do it at this moment at this point I'm affraid.

To summarize the work-around, it involves downloading the 5.5 source, and then change the source in the following places:

org.apache.catalina.connector.Request.java

//this is what needs to be changed
//response.addCookieInternal(cookie);

//this is whats new
response.addCookieInternal(cookie, true);
}

org.apache.catalina.connectorResponse.addCookieInternal

public void addCookieInternal(final Cookie cookie) {
addCookieInternal(cookie, false);
}

public void addCookieInternal(final Cookie cookie, boolean HTTPOnly) {

if (isCommitted())
return;

final StringBuffer sb = new StringBuffer();
//web application code can receive a IllegalArgumentException
//from the appendCookieValue invokation
if (SecurityUtil.isPackageProtectionEnabled()) {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run(){
ServerCookie.appendCookieValue
(sb, cookie.getVersion(), cookie.getName(),
cookie.getValue(), cookie.getPath(),
cookie.getDomain(), cookie.getComment(),
cookie.getMaxAge(), cookie.getSecure());
return null;
}
});
} else {
ServerCookie.appendCookieValue
(sb, cookie.getVersion(), cookie.getName(), cookie.getValue(),
cookie.getPath(), cookie.getDomain(), cookie.getComment(),
cookie.getMaxAge(), cookie.getSecure());
}
//of course, we really need to modify ServerCookie
//but this is the general idea
if (HTTPOnly) {
sb.append("; HttpOnly");
}

//if we reached here, no exception, cookie is valid
// the header name is Set-Cookie for both "old" and v.1 ( RFC2109 )
// RFC2965 is not supported by browsers and the Servlet spec
// asks for 2109.
addHeader("Set-Cookie", sb.toString());

cookies.add(cookie);
}

What is difference between cacerts and keystore?

Check your JAVA_HOME path. As systems looks for a java.policy file which is located in JAVA_HOME/jre/lib/security. Your JAVA_HOME should always be ../JAVA/JDK.

How to use the IEqualityComparer

The inclusion of your comparison class (or more specifically the AsEnumerable call you needed to use to get it to work) meant that the sorting logic went from being based on the database server to being on the database client (your application). This meant that your client now needs to retrieve and then process a larger number of records, which will always be less efficient that performing the lookup on the database where the approprate indexes can be used.

You should try to develop a where clause that satisfies your requirements instead, see Using an IEqualityComparer with a LINQ to Entities Except clause for more details.

AngularJS ng-click stopPropagation

I wrote a directive which lets you limit the areas where a click has effect. It could be used for certain scenarios like this one, so instead of having to deal with the click on a case by case basis you can just say "clicks won't come out of this element".

You would use it like this:

<table>
  <tr ng-repeat="user in users" ng-click="showUser(user)">
    <td>{{user.firstname}}</td>
    <td>{{user.lastname}}</td>
    <td isolate-click>
      <button class="btn" ng-click="deleteUser(user.id, $index);">
        Delete
      </button>
    </td>              
  </tr>
</table>

Keep in mind that this would prevent all clicks on the last cell, not just the button. If that's not what you want you may want to wrap the button like this:

<span isolate-click>
    <button class="btn" ng-click="deleteUser(user.id, $index);">
        Delete
    </button>
</span>

Here is the directive's code:

angular.module('awesome', []).directive('isolateClick', function() {
    return {
        link: function(scope, elem) {
            elem.on('click', function(e){
                e.stopPropagation();
            });
        }
   };
});

Regex remove all special characters except numbers?

To remove the special characters, try

var name = name.replace(/[!@#$%^&*]/g, "");

How to get first character of a string in SQL?

INPUT

STRMIDDLENAME
--------------
Aravind Chaterjee
Shivakumar
Robin Van Parsee

SELECT STRMIDDLENAME, 
CASE WHEN INSTR(STRMIDDLENAME,' ',1,2) != 0 THEN SUBSTR(STRMIDDLENAME,1,1) || SUBSTR(STRMIDDLENAME,INSTR(STRMIDDLENAME,' ',1,1)+1,1)||
SUBSTR(STRMIDDLENAME,INSTR(STRMIDDLENAME,' ',1,2)+1,1)
WHEN INSTR(STRMIDDLENAME,' ',1,1) != 0 THEN SUBSTR(STRMIDDLENAME,1,1) || SUBSTR(STRMIDDLENAME,INSTR(STRMIDDLENAME,' ',1,1)+1,1)
ELSE SUBSTR(STRMIDDLENAME,1,1)
END AS FIRSTLETTERS
FROM Dual;

OUTPUT
STRMIDDLENAME                    FIRSTLETTERS
---------                        -----------------
Aravind Chaterjee                AC           
Shivakumar                       S
Robin Van Parsee                 RVP

No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?

You must have to define no-args or default constructor if you are creating your own constructor.

You can read why default or no argument constructor is required.

why-default-or-no-argument-constructor-java-class.html

How can I check if mysql is installed on ubuntu?

"mysql" may be found even if mysql and mariadb is uninstalled, but not "mysqld".

Faster than rpm -qa | grep mysqld is:

which mysqld

Changing file permission in Python

Just add 0 before the permission number:
For example - we want to give all permissions - 777
Syntax: os.chmod("file_name" , permission)

import os
os.chmod("file_name" , 0777)

Python version 3.7 does not support this syntax. It requires '0o' prefix for octal literals - this is the comment I have got in PyCharm

So for python 3.7, it will be

import os
os.chmod("file_name" , 0o777)

Get element type with jQuery

you should use tagName property and attr('type') for inputs

How to replace multiple white spaces with one white space

Smallest solution:

var regExp=/\s+/g, newString=oldString.replace(regExp,' ');

How to use TLS 1.2 in Java 6

I think that the solution of @Azimuts (https://stackoverflow.com/a/33375677/6503697) is for HTTP only connection. For FTPS connection you can use Bouncy Castle with org.apache.commons.net.ftp.FTPSClient without the need for rewrite FTPS protocol.

I have a program running on JRE 1.6.0_04 and I can not update the JRE.

The program has to connect to an FTPS server that work only with TLS 1.2 (IIS server).

I struggled for days and finally I have understood that there are few versions of bouncy castle library right in my use case: bctls-jdk15on-1.60.jar and bcprov-jdk15on-1.60.jar are ok, but 1.64 versions are not.

The version of apache commons-net is 3.1 .

Following is a small snippet of code that should work:

import java.io.ByteArrayOutputStream;
import java.security.SecureRandom;
import java.security.Security;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPSClient;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jsse.provider.BouncyCastleJsseProvider;
import org.junit.Test;


public class FtpsTest {

// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return null;
    }

    public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
    }

    public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
    }
} };

@Test public void test() throws Exception {


    Security.insertProviderAt(new BouncyCastleProvider(), 1);
    Security.addProvider(new BouncyCastleJsseProvider());


    SSLContext sslContext = SSLContext.getInstance("TLS", new BouncyCastleJsseProvider());
    sslContext.init(null, trustAllCerts, new SecureRandom());
    org.apache.commons.net.ftp.FTPSClient ftpClient = new FTPSClient(sslContext);
    ByteArrayOutputStream out = null;
    try {

        ftpClient.connect("hostaname", 21);
        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            String msg = "Il server ftp ha rifiutato la connessione.";
            throw new Exception(msg);
        }
        if (!ftpClient.login("username", "pwd")) {
            String msg = "Il server ftp ha rifiutato il login con username:  username  e pwd:  password  .";
            ftpClient.disconnect();
            throw new Exception(msg);
        }


        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.setDataTimeout(60000);
        ftpClient.execPBSZ(0); // Set protection buffer size
        ftpClient.execPROT("P"); // Set data channel protection to private
        int bufSize = 1024 * 1024; // 1MB
        ftpClient.setBufferSize(bufSize);
        out = new ByteArrayOutputStream(bufSize);
        ftpClient.retrieveFile("remoteFileName", out);
        out.toByteArray();
    }
    finally {
        if (out != null) {
            out.close();
        }
        ftpClient.disconnect();

    }

}

}

How to change RGB color to HSV?

This is the VB.net version which works fine for me ported from the C code in BlaM's post.

There's a C implementation here:

http://www.cs.rit.edu/~ncs/color/t_convert.html

Should be very straightforward to convert to C#, as almost no functions are called - just > calculations.


Public Sub HSVtoRGB(ByRef r As Double, ByRef g As Double, ByRef b As Double, ByVal h As Double, ByVal s As Double, ByVal v As Double)
    Dim i As Integer
    Dim f, p, q, t As Double

    If (s = 0) Then
        ' achromatic (grey)
        r = v
        g = v
        b = v
        Exit Sub
    End If

    h /= 60 'sector 0 to 5
    i = Math.Floor(h)
    f = h - i 'factorial part of h
    p = v * (1 - s)
    q = v * (1 - s * f)
    t = v * (1 - s * (1 - f))

    Select Case (i)
        Case 0
            r = v
            g = t
            b = p
            Exit Select
        Case 1
            r = q
            g = v
            b = p
            Exit Select
        Case 2
            r = p
            g = v
            b = t
            Exit Select
        Case 3
            r = p
            g = q
            b = v
            Exit Select
        Case 4
            r = t
            g = p
            b = v
            Exit Select
        Case Else   'case 5:
            r = v
            g = p
            b = q
            Exit Select
    End Select
End Sub

Ignoring SSL certificate in Apache HttpClient 4.3

Simpler and shorter working code:

We are using HTTPClient 4.3.5 and we tried almost all solutions exist on the stackoverflow but nothing, After thinking and figuring out the problem, we come to the following code which works perfectly, just add it before creating HttpClient instance.

some method which you use to make post request...

SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    });

    SSLConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(builder.build(),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslSF).build();
    HttpPost postRequest = new HttpPost(url);

continue calling and using HttpPost instance in the normal form

How to allow http content within an iframe on a https site

add <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"> in head

reference: http://thehackernews.com/2015/04/disable-mixed-content-warning.html

browser compatibility: http://caniuse.com/#feat=upgradeinsecurerequests

Calculate RSA key fingerprint

On Windows, if you're running PuTTY/Pageant, the fingerprint is listed when you load your PuTTY (.ppk) key into Pageant. It is pretty useful in case you forget which one you're using.

Enter image description here

Configuration System Failed to Initialize

Try to save the .config file as utf-8 if you have some "special" characters in there. That was the issue in my case of a console application.

font-family is inherit. How to find out the font-family in chrome developer pane?

The inherit value, when used, means that the value of the property is set to the value of the same property of the parent element. For the root element (in HTML documents, for the html element) there is no parent element; by definition, the value used is the initial value of the property. The initial value is defined for each property in CSS specifications.

The font-family property is special in the sense that the initial value is not fixed in the specification but defined to be browser-dependent. This means that the browser’s default font family is used. This value can be set by the user.

If there is a continuous chain of elements (in the sense of parent-child relationships) from the root element to the current element, all with font-family set to inherit or not set at all in any style sheet (which also causes inheritance), then the font is the browser default.

This is rather uninteresting, though. If you don’t set fonts at all, browsers defaults will be used. Your real problem might be different – you seem to be looking at the part of style sheets that constitute a browser style sheet. There are probably other, more interesting style sheets that affect the situation.

Switch statement for string matching in JavaScript

It may be easier. Try to think like this:

  • first catch a string between regular characters
  • after that find "case"

:

// 'www.dev.yyy.com'
// 'xxx.foo.pl'

var url = "xxx.foo.pl";

switch (url.match(/\..*.\./)[0]){
   case ".dev.yyy." :
          console.log("xxx.dev.yyy.com");break;

   case ".some.":
          console.log("xxx.foo.pl");break;
} //end switch

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

In httpd.conf, search for "ServerName". It's usually commented out by default on Mac. Just uncomment it and fill it in. Make sure you also have the name/ip combo set in /etc/hosts.

Node.js: How to send headers with form data using request module?

I found the solution of this problem and i should work i'm sure about this because i also face the same problem

here is my solution----->

var request = require('request');

//set url
var url = 'http://localhost:8088/example';

//set header
var headers = {
    'Authorization': 'Your authorization'
};

//set form data
var form = {first_name: first_name, last_name: last_name};

//set request parameter
request.post({headers: headers, url: url, form: form, method: 'POST'}, function (e, r, body) {

    var bodyValues = JSON.parse(body);
    res.send(bodyValues);
});

Python os.path.join on Windows

To be even more pedantic, the most python doc consistent answer would be:

mypath = os.path.join('c:', os.sep, 'sourcedir')

Since you also need os.sep for the posix root path:

mypath = os.path.join(os.sep, 'usr', 'lib')

How to control the width of select tag?

USE style="max-width:90%;"

<select name=countries  style="max-width:90%;">
 <option value=af>Afghanistan</option>
 <option value=ax>Åland Islands</option>
 ...
 <option value=gs>South Georgia and the South Sandwich Islands</option>
 ...
</select>  

LIVE DEMO

process.env.NODE_ENV is undefined

If you faced this probem in React, you need [email protected] and higher. Also for other environment variables than NODE_ENV to work in React, they need to be prefixed with REACT_APP_.

How to force div to appear below not next to another?

I think what you want requires an extra wrapper div.

_x000D_
_x000D_
#map {_x000D_
    float: left; _x000D_
    width: 700px; _x000D_
    height: 500px;_x000D_
}_x000D_
#wrapper {_x000D_
    float: left;_x000D_
    width: 200px;_x000D_
}_x000D_
#list {_x000D_
    background: #eee;_x000D_
    list-style: none; _x000D_
    padding: 0; _x000D_
}_x000D_
#similar {_x000D_
    background: #000; _x000D_
}
_x000D_
<div id="map">Lorem Ipsum</div>        _x000D_
<div id="wrapper">_x000D_
  <ul id="list"><li>Dolor</li><li>Sit</li><li>Amet</li></ul>_x000D_
  <div id ="similar">_x000D_
    this text should be below, not next to ul._x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

numpy array TypeError: only integer scalar arrays can be converted to a scalar index

This could be unrelated to this specific problem, but I ran into a similar issue where I used NumPy indexing on a Python list and got the same exact error message:

# incorrect
weights = list(range(1, 129)) + list(range(128, 0, -1))
mapped_image = weights[image[:, :, band]] # image.shape = [800, 600, 3]
# TypeError: only integer scalar arrays can be converted to a scalar index

It turns out I needed to turn weights, a 1D Python list, into a NumPy array before I could apply multi-dimensional NumPy indexing. The code below works:

# correct
weights = np.array(list(range(1, 129)) + list(range(128, 0, -1)))
mapped_image = weights[image[:, :, band]] # image.shape = [800, 600, 3]

How to count TRUE values in a logical vector

Another option is to use summary function. It gives a summary of the Ts, Fs and NAs.

> summary(hival)
   Mode   FALSE    TRUE    NA's 
logical    4367      53    2076 
> 

Is there a date format to display the day of the week in java?

I know the question is about getting the day of week as string (e.g. the short name), but for anybody who is looking for the numeric day of week (as I was), you can use the new "u" format string, supported since Java 7. For example:

new SimpleDateFormat("u").format(new Date());

returns today's day-of-week index, namely: 1 = Monday, 2 = Tuesday, ..., 7 = Sunday.

PHP how to get local IP of system

If you are in a dev environment on OS X, connected via Wifi:

echo exec("/sbin/ifconfig en1 | grep 'inet ' | cut -d ' ' -f2");

get list of packages installed in Anaconda

For more conda list usage details:

usage: conda-script.py list [-h][-n ENVIRONMENT | -p PATH][--json] [-v] [-q]
[--show-channel-urls] [-c] [-f] [--explicit][--md5] [-e] [-r] [--no-pip][regex]

Node.js global proxy setting

Unfortunately, it seems that proxy information must be set on each call to http.request. Node does not include a mechanism for global proxy settings.

The global-tunnel-ng module on NPM appears to handle this, however:

var globalTunnel = require('global-tunnel-ng');

globalTunnel.initialize({
  host: '10.0.0.10',
  port: 8080,
  proxyAuth: 'userId:password', // optional authentication
  sockets: 50 // optional pool size for each http and https
});

After the global settings are establish with a call to initialize, both http.request and the request library will use the proxy information.

The module can also use the http_proxy environment variable:

process.env.http_proxy = 'http://proxy.example.com:3129';
globalTunnel.initialize();

The meaning of NoInitialContextException error

you need to use jboss-client.jar in your client project and you need to use jnp-client jar in your ejb project

How to create a multiline UITextfield?

If you must have a UITextField with 2 lines of text, one option is to add a UILabel as a subview of the UITextField for the second line of text. I have a UITextField in my app that users often do not realize is editable by tapping, and I wanted to add some small subtitle text that says "Tap to Edit" to the UITextField.

CGFloat tapLlblHeight = 10;
UILabel *tapEditLbl = [[UILabel alloc] initWithFrame:CGRectMake(20, textField.frame.size.height - tapLlblHeight - 2, 70, tapLlblHeight)];
tapEditLbl.backgroundColor = [UIColor clearColor];
tapEditLbl.textColor = [UIColor whiteColor];
tapEditLbl.text = @"Tap to Edit";

[textField addSubview:tapEditLbl];

How to get the current time in Python

This is what I ended up going with:

>>>from time import strftime
>>>strftime("%m/%d/%Y %H:%M")
01/09/2015 13:11

Also, this table is a necessary reference for choosing the appropriate format codes to get the date formatted just the way you want it (from Python "datetime" documentation here).

strftime format code table

Get installed applications in a system

Might I suggest you take a look at WMI (Windows Management Instrumentation). If you add the System.Management reference to your C# project, you'll gain access to the class `ManagementObjectSearcher', which you will probably find useful.

There are various WMI Classes for Installed Applications, but if it was installed with Windows Installer, then the Win32_Product class is probably best suited to you.

ManagementObjectSearcher s = new ManagementObjectSearcher("SELECT * FROM Win32_Product");

python, sort descending dataframe with pandas

New syntax (either):

 test = df.sort_values(['one'], ascending=[False])
 test = df.sort_values(['one'], ascending=[0])

How to debug heap corruption errors?

What sort of things can cause these errors?

Doing naughty things with memory, e.g. writing after the end of a buffer, or writing to a buffer after it's been freed back to the heap.

How do I debug them?

Use an instrument which adds automated bounds-checking to your executable: i.e. valgrind on Unix, or a tool like BoundsChecker (Wikipedia suggests also Purify and Insure++) on Windows.

Beware that these will slow your application, so they may be unusable if yours is a soft-real-time application.

Another possible debugging aid/tool might be MicroQuill's HeapAgent.

How do I tokenize a string sentence in NLTK?

This is actually on the main page of nltk.org:

>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']

jQuery: Load Modal Dialog Contents via Ajax

<button class="btn" onClick="openDialog('New Type','Sample.html')">Middle</button>

<script type="text/javascript">
    function openDialog(title,url) {
        $('.opened-dialogs').dialog("close");

        $('<div class="opened-dialogs">').html('loading...').dialog({
            position:  ['center',20],
            open: function () {
                $(this).load(url);

            },
            close: function(event, ui) {
                    $(this).remove();
            },

            title: title,
            minWidth: 600            
        });

        return false;
    }
</script>

How do you specify a debugger program in Code::Blocks 12.11?

  1. Click on settings in top tool bar;

  2. Click on debugger;

  3. In tree, highlight "gdb/cdb debugger" by clicking it

  4. Click "create configuration"

  5. Add "gdb.exe" (no quotes) as a configuration

  6. Delete default configuration

  7. Click on gdb.exe that you created in the tree (it should be the only one) and a dialogue will appear to the right for "executable path" with a button to the right.

  8. Click on that button and it will bring up the file that codeblocks is installed in. Just keep clicking until you create the path to the gdb.exe (it sort of finds itself).

Use custom build output folder when using create-react-app

Based on the answers by Ben Carp and Wallace Sidhrée:

This is what I use to copy my entire build folder to my wamp public folder.

package.json

{
  "name": "[your project name]",
  "homepage": "http://localhost/[your project name]/",
  "version": "0.0.1",
  [...]
  "scripts": {
    "build": "react-scripts build",
    "postbuild": "@powershell -NoProfile -ExecutionPolicy Unrestricted -Command ./post_build.ps1",
    [...]
  },
}

post_build.ps1

Copy-Item "./build/*" -Destination "C:/wamp64/www/[your project name]" -Recurse -force

The homepage line is only needed if you are deploying to a subfolder on your server (See This answer from another question).

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

Here is the detailed explanation of why "Random.nextInt(n) is both more efficient and less biased than Math.random() * n" from the Sun forums post that Gili linked to:

Math.random() uses Random.nextDouble() internally.

Random.nextDouble() uses Random.next() twice to generate a double that has approximately uniformly distributed bits in its mantissa, so it is uniformly distributed in the range 0 to 1-(2^-53).

Random.nextInt(n) uses Random.next() less than twice on average- it uses it once, and if the value obtained is above the highest multiple of n below MAX_INT it tries again, otherwise is returns the value modulo n (this prevents the values above the highest multiple of n below MAX_INT skewing the distribution), so returning a value which is uniformly distributed in the range 0 to n-1.

Prior to scaling by 6, the output of Math.random() is one of 2^53 possible values drawn from a uniform distribution.

Scaling by 6 doesn't alter the number of possible values, and casting to an int then forces these values into one of six 'buckets' (0, 1, 2, 3, 4, 5), each bucket corresponding to ranges encompassing either 1501199875790165 or 1501199875790166 of the possible values (as 6 is not a disvisor of 2^53). This means that for a sufficient number of dice rolls (or a die with a sufficiently large number of sides), the die will show itself to be biased towards the larger buckets.

You will be waiting a very long time rolling dice for this effect to show up.

Math.random() also requires about twice the processing and is subject to synchronization.

How to detect when facebook's FB.init is complete

The Facebook API watches for the FB._apiKey so you can watch for this before calling your own application of the API with something like:

window.fbAsyncInit = function() {
  FB.init({
    //...your init object
  });
  function myUseOfFB(){
    //...your FB API calls
  };
  function FBreadyState(){
    if(FB._apiKey) return myUseOfFB();
    setTimeout(FBreadyState, 100); // adjust time as-desired
  };
  FBreadyState();
}; 

Not sure this makes a difference but in my case--because I wanted to be sure the UI was ready--I've wrapped the initialization with jQuery's document ready (last bit above):

  $(document).ready(FBreadyState);

Note too that I'm NOT using async = true to load Facebook's all.js, which in my case seems to be helping with signing into the UI and driving features more reliably.

How To Get Selected Value From UIPickerView

You have to use the didSelectRow delegate method, because a UIPickerView can have an arbitrary number of components. There is no "objectValue" or anything like that, because that's entirely up to you.

Git 'fatal: Unable to write new index file'

It happened to me that the file .git/index was in use by another process (my local development web server). I shut down the process and then it worked.

setImmediate vs. nextTick

Use setImmediate if you want to queue the function behind whatever I/O event callbacks that are already in the event queue. Use process.nextTick to effectively queue the function at the head of the event queue so that it executes immediately after the current function completes.

So in a case where you're trying to break up a long running, CPU-bound job using recursion, you would now want to use setImmediate rather than process.nextTick to queue the next iteration as otherwise any I/O event callbacks wouldn't get the chance to run between iterations.

SSIS Convert Between Unicode and Non-Unicode Error

The missing piece here is Data Conversion object. It should be in between OLE DB Source and Destination object.

enter image description here

How can I solve equations in Python?

There are two ways to approach this problem: numerically and symbolically.

To solve it numerically, you have to first encode it as a "runnable" function - stick a value in, get a value out. For example,

def my_function(x):
    return 2*x + 6

It is quite possible to parse a string to automatically create such a function; say you parse 2x + 6 into a list, [6, 2] (where the list index corresponds to the power of x - so 6*x^0 + 2*x^1). Then:

def makePoly(arr):
    def fn(x):
        return sum(c*x**p for p,c in enumerate(arr))
    return fn

my_func = makePoly([6, 2])
my_func(3)    # returns 12

You then need another function which repeatedly plugs an x-value into your function, looks at the difference between the result and what it wants to find, and tweaks its x-value to (hopefully) minimize the difference.

def dx(fn, x, delta=0.001):
    return (fn(x+delta) - fn(x))/delta

def solve(fn, value, x=0.5, maxtries=1000, maxerr=0.00001):
    for tries in xrange(maxtries):
        err = fn(x) - value
        if abs(err) < maxerr:
            return x
        slope = dx(fn, x)
        x -= err/slope
    raise ValueError('no solution found')

There are lots of potential problems here - finding a good starting x-value, assuming that the function actually has a solution (ie there are no real-valued answers to x^2 + 2 = 0), hitting the limits of computational accuracy, etc. But in this case, the error minimization function is suitable and we get a good result:

solve(my_func, 16)    # returns (x =) 5.000000000000496

Note that this solution is not absolutely, exactly correct. If you need it to be perfect, or if you want to try solving families of equations analytically, you have to turn to a more complicated beast: a symbolic solver.

A symbolic solver, like Mathematica or Maple, is an expert system with a lot of built-in rules ("knowledge") about algebra, calculus, etc; it "knows" that the derivative of sin is cos, that the derivative of kx^p is kpx^(p-1), and so on. When you give it an equation, it tries to find a path, a set of rule-applications, from where it is (the equation) to where you want to be (the simplest possible form of the equation, which is hopefully the solution).

Your example equation is quite simple; a symbolic solution might look like:

=> LHS([6, 2]) RHS([16])

# rule: pull all coefficients into LHS
LHS, RHS = [lh-rh for lh,rh in izip_longest(LHS, RHS, 0)], [0]

=> LHS([-10,2]) RHS([0])

# rule: solve first-degree poly
if RHS==[0] and len(LHS)==2:
    LHS, RHS = [0,1], [-LHS[0]/LHS[1]]

=> LHS([0,1]) RHS([5])

and there is your solution: x = 5.

I hope this gives the flavor of the idea; the details of implementation (finding a good, complete set of rules and deciding when each rule should be applied) can easily consume many man-years of effort.

React JSX: selecting "selected" on selected <select> option

I have a simple solution is following the HTML basic.

<input
  type="select"
  defaultValue=""
  >
  <option value="" disabled className="text-hide">Please select</option>
  <option>value1</option>
  <option>value1</option>
</input>

.text-hide is a bootstrap's class, if you not using bootstrap, here you are:

.text-hide {
  font: 0/0 a;
  color: transparent;
  text-shadow: none;
  background-color: transparent;
  border: 0;
}

Windows could not start the SQL Server (MSSQLSERVER) on Local Computer... (error code 3417)

I copied a master.mdf und mastlog.ldf from another Computer (luckily, we have a lot of Clients with the same configuration, otherwise template data would be perhaps necessary). I backed up the damaged master.mdf and mastlog.mdf. After that I replaced the bad ones with the ones from another Computer. And it worked. I needed to start the MSSQLSERVER Service of course. But, after that I had Problem that the user was already existing but orphaned (error code 15023), I executed the query

USE Database_name EXEC sp_change_users_login 'Auto_Fix', 'username'

after that, everything was working smoothly. Hope this helps you and many thanks for this thread, saved me :)

Retrieve specific commit from a remote Git repository

I did a pull on my git repo:

git pull --rebase <repo> <branch>

Allowing git to pull in all the code for the branch and then I went to do a reset over to the commit that interested me.

git reset --hard <commit-hash>

Hope this helps.

Get final URL after curl is redirected

Thanks, that helped me. I made some improvements and wrapped that in a helper script "finalurl":

#!/bin/bash
curl $1 -s -L -I -o /dev/null -w '%{url_effective}'
  • -o output to /dev/null
  • -I don't actually download, just discover the final URL
  • -s silent mode, no progressbars

This made it possible to call the command from other scripts like this:

echo `finalurl http://someurl/`

How to get image width and height in OpenCV?

Also for openCV in python you can do:

img = cv2.imread('myImage.jpg')
height, width, channels = img.shape 

passing form data to another HTML page

*first html page*

<form action="display.jsp" >
    <input type="text" name="serialNumber" />
    <input type="submit" value="Submit" />
</form>


*Second html page*
<body>
<p>The serial number is:<%=request.getParameter("serialNumber") %></p>
</body>


you will get the value of the textbox on another page.

how to change listen port from default 7001 to something different?

The following lines are used to control the listen-port of a server, both are necessary:

    <listen-port>7002</listen-port>
    <listen-port-enabled>true</listen-port-enabled>

What does InitializeComponent() do, and how does it work in WPF?

The call to InitializeComponent() (which is usually called in the default constructor of at least Window and UserControl) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).

This method locates a URI to the XAML for the Window/UserControl that is loading, and passes it to the System.Windows.Application.LoadComponent() static method. LoadComponent() loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.

In more detail, LoadComponent creates an instance of the XamlParser, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode(). This gets passed to the BamlRecordWriter class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.

Note: Interestingly, the InitializeComponent is a method on the System.Windows.Markup.IComponentConnector interface, of which Window/UserControl implement in the partial generated class.

Hope this helps!

Repeat each row of data.frame the number of times specified in a column

Use expandRows() from the splitstackshape package:

library(splitstackshape)
expandRows(df, "freq")

Simple syntax, very fast, works on data.frame or data.table.

Result:

    var1 var2
1      a    d
2      b    e
2.1    b    e
3      c    f
3.1    c    f
3.2    c    f

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Yes. Bootstrap uses CSS transitions so it can be done easily without any Javascript.

The CSS:

.carousel .item {-webkit-transition: opacity 3s; -moz-transition: opacity 3s; -ms-transition: opacity 3s; -o-transition: opacity 3s; transition: opacity 3s;}
.carousel .active.left {left:0;opacity:0;z-index:2;}
.carousel .next {left:0;opacity:1;z-index:1;}

I noticed however that the transition end event was firing prematurely with the default interval of 5s and a fade transition of 3s. Bumping the carousel interval to 8s provides a nice effect.

Very smooth.

jQuery callback on image load (even when the image is cached)

You can solve your problem using JAIL plugin that also allows you to lazy load images (improving the page performance) and passing the callback as parameter

$('img').asynchImageLoader({callback : function(){...}});

The HTML should look like

<img name="/global/images/sample1.jpg" src="/global/images/blank.gif" width="width" height="height" />

Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

I ran into a similar issue today - my ruby version didn't match my rvm installs.

> ruby -v
ruby 2.0.0p481

> rvm list
rvm rubies
   ruby-2.1.2 [ x86_64 ]
=* ruby-2.2.1 [ x86_64 ]
   ruby-2.2.3 [ x86_64 ]

Also, rvm current failed.

> rvm current
Warning! PATH is not properly set up, '/Users/randallreed/.rvm/gems/ruby-2.2.1/bin' is not at first place...

The error message recommended this useful command, which resolved the issue for me:

> rvm get stable --auto-dotfiles

Assign value from successful promise resolve to external variable

This is one "trick" you can do since your out of an async function so can't use await keywork

Do what you want to do with vm.feed inside a setTimeout

vm.feed = getFeed().then(function(data) {return data;});

 setTimeout(() => {
    // do you stuf here
    // after the time you promise will be revolved or rejected
    // if you need some of the values in here immediately out of settimeout
    // might occur an error if promise wore not yet resolved or rejected
    console.log("vm.feed",vm.feed);
 }, 100);

Replace duplicate spaces with a single space in T-SQL

Found this while digging for an answer:

SELECT REPLACE(
        REPLACE(
             REPLACE(
                LTRIM(RTRIM('1 2  3   4    5     6'))
            ,'  ',' '+CHAR(7))
        ,CHAR(7)+' ','')
    ,CHAR(7),'') AS CleanString
where charindex('  ', '1 2  3   4    5     6') > 0

The full answer (with explanation) was pulled from: http://techtipsbysatish.blogspot.com/2010/08/sql-server-replace-multiple-spaces-with.html

On second look, seems to be just a slightly different version of the selected answer.

Control the dashed border stroke length and distance between strokes

The native dashed border property value does not offer control over the dashes themselves... so bring on the border-image property!

Brew your own border with border-image

Compatibility: It offers great browser support (IE 11 and all modern browsers). A normal border can be set as a fallback for older browsers.

Let's create these

These borders will display exactly the same cross-browser!

Goal example Goal example with wider gaps

Step 1 - Create a suitable image

This example is 15 pixels wide by 15 pixels high and the gaps are currently 5px wide. It is a .png with transparency.

This is what it looks like in photoshop when zoomed in:

Example Border Image Background Blown Up

This is what it looks like to scale:

Example Border Image Background Actual Size

Controlling gap and stroke length

To create wider / shorter gaps or strokes, widen / shorten the gaps or strokes in the image.

Here is an image with wider 10px gaps:

Larger gaps correctly scaled = Larger gaps to scale

Step 2 - Create the CSS — this example requires 4 basic steps

  1. Define the border-image-source:

    border-image-source:url("http://i.stack.imgur.com/wLdVc.png");  
    
  2. Optional - Define the border-image-width:

    border-image-width: 1;
    

    The default value is 1. It can also be set with a pixel value, percentage value, or as another multiple (1x, 2x, 3x etc). This overrides any border-width set.

  3. Define the border-image-slice:

    In this example, the thickness of the images top, right, bottom and left borders is 2px, and there is no gap outside of them, so our slice value is 2:

    border-image-slice: 2; 
    

    The slices look like this, 2 pixels from the top, right, bottom and left:

    Slices example

  4. Define the border-image-repeat:

    In this example, we want the pattern to repeat itself evenly around our div. So we choose:

    border-image-repeat: round;
    

Writing shorthand

The properties above can be set individually, or in shorthand using border-image:

border-image: url("http://i.stack.imgur.com/wLdVc.png") 2 round;

Complete example

Note the border: dashed 4px #000 fallback. Non-supporting browsers will receive this border.

_x000D_
_x000D_
.bordered {_x000D_
  display: inline-block;_x000D_
  padding: 20px;_x000D_
  /* Fallback dashed border_x000D_
     - the 4px width here is overwritten with the border-image-width (if set)_x000D_
     - the border-image-width can be omitted below if it is the same as the 4px here_x000D_
  */_x000D_
  border: dashed 4px #000;_x000D_
  _x000D_
  /* Individual border image properties */_x000D_
  border-image-source: url("http://i.stack.imgur.com/wLdVc.png");_x000D_
  border-image-slice: 2;_x000D_
  border-image-repeat: round;  _x000D_
  _x000D_
  /* or use the shorthand border-image */_x000D_
  border-image: url("http://i.stack.imgur.com/wLdVc.png") 2 round;_x000D_
}_x000D_
_x000D_
_x000D_
/*The border image of this one creates wider gaps*/_x000D_
.largeGaps {_x000D_
  border-image-source: url("http://i.stack.imgur.com/LKclP.png");_x000D_
  margin: 0 20px;_x000D_
}
_x000D_
<div class="bordered">This is bordered!</div>_x000D_
_x000D_
<div class="bordered largeGaps">This is bordered and has larger gaps!</div>
_x000D_
_x000D_
_x000D_

Correct way to pass multiple values for same parameter name in GET request

Solutions above didn't work. It simply displayed the last key/value pairs, but this did:

http://localhost/?key[]=1&key[]=2

Returns:

Array
(
[key] => Array
    (
        [0] => 1
        [1] => 2
    )

Removing certain characters from a string in R

try: gsub('\\$', '', '$5.00$')

How to get DATE from DATETIME Column in SQL?

Use Getdate()

 select sum(transaction_amount) from TransactionMaster
 where Card_No=' 123' and transaction_date =convert(varchar(10), getdate(), 102)

What is an NP-complete in computer science?

NP stands for Non-deterministic Polynomial time.

This means that the problem can be solved in Polynomial time using a Non-deterministic Turing machine (like a regular Turing machine but also including a non-deterministic "choice" function). Basically, a solution has to be testable in poly time. If that's the case, and a known NP problem can be solved using the given problem with modified input (an NP problem can be reduced to the given problem) then the problem is NP complete.

The main thing to take away from an NP-complete problem is that it cannot be solved in polynomial time in any known way. NP-Hard/NP-Complete is a way of showing that certain classes of problems are not solvable in realistic time.

Edit: As others have noted, there are often approximate solutions for NP-Complete problems. In this case, the approximate solution usually gives an approximation bound using special notation which tells us how close the approximation is.

How can I format a number into a string with leading zeros?

For interpolated strings:

$"Int value: {someInt:D4} or {someInt:0000}. Float: {someFloat: 00.00}"

iOS / Android cross platform development

There is also BatteryTech which we've been using for the past 18 months and have released several games off of it. http://www.batterypoweredgames.com/batterytech

All C++, Android and iOS support, all users get full source. The new v2 includes lua bindings.

How to change font of UIButton with Swift

For Swift 3.0:

button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)

where "boldSystemFont" and "16" can be replaced with your custom font and size.

Update statement with inner join on Oracle

 UPDATE ( SELECT t1.value, t2.CODE
          FROM table1 t1
          INNER JOIN table2 t2 ON t1.Value = t2.DESC
          WHERE t1.UPDATETYPE='blah')
 SET t1.Value= t2.CODE

How to free memory in Java?

Entirely from javacoffeebreak.com/faq/faq0012.html

A low priority thread takes care of garbage collection automatically for the user. During idle time, the thread may be called upon, and it can begin to free memory previously allocated to an object in Java. But don't worry - it won't delete your objects on you!

When there are no references to an object, it becomes fair game for the garbage collector. Rather than calling some routine (like free in C++), you simply assign all references to the object to null, or assign a new class to the reference.

Example :

public static void main(String args[])
{
  // Instantiate a large memory using class
  MyLargeMemoryUsingClass myClass = new MyLargeMemoryUsingClass(8192);

  // Do some work
  for ( .............. )
  {
      // Do some processing on myClass
  }

  // Clear reference to myClass
  myClass = null;

  // Continue processing, safe in the knowledge
  // that the garbage collector will reclaim myClass
}

If your code is about to request a large amount of memory, you may want to request the garbage collector begin reclaiming space, rather than allowing it to do so as a low-priority thread. To do this, add the following to your code

System.gc();

The garbage collector will attempt to reclaim free space, and your application can continue executing, with as much memory reclaimed as possible (memory fragmentation issues may apply on certain platforms).

How to pass objects to functions in C++?

Pass by value:

void func (vector v)

Pass variables by value when the function needs complete isolation from the environment i.e. to prevent the function from modifying the original variable as well as to prevent other threads from modifying its value while the function is being executed.

The downside is the CPU cycles and extra memory spent to copy the object.

Pass by const reference:

void func (const vector& v);

This form emulates pass-by-value behavior while removing the copying overhead. The function gets read access to the original object, but cannot modify its value.

The downside is thread safety: any change made to the original object by another thread will show up inside the function while it's still executing.

Pass by non-const reference:

void func (vector& v)

Use this when the function has to write back some value to the variable, which will ultimately get used by the caller.

Just like the const reference case, this is not thread-safe.

Pass by const pointer:

void func (const vector* vp);

Functionally same as pass by const-reference except for the different syntax, plus the fact that the calling function can pass NULL pointer to indicate it has no valid data to pass.

Not thread-safe.

Pass by non-const pointer:

void func (vector* vp);

Similar to non-const reference. The caller typically sets the variable to NULL when the function is not supposed to write back a value. This convention is seen in many glibc APIs. Example:

void func (string* str, /* ... */) {
    if (str != NULL) {
        *str = some_value; // assign to *str only if it's non-null
    }
}

Just like all pass by reference/pointer, not thread-safe.

Reverse engineering from an APK file to a project

For the Android platform, you can try ShowJava, available on the Play Store.

You can consult the generated code through the app interface and the generated java files and folders structure are stored in ShowJava folder in /sdcard, alongside the resulting .jar file from the conversion.

The app is free with an ad banner at the bottom of the main view, but there is an in-app purchase option (3,99$) to remove it. In-app purchase does not add any functionality beside removing the ad banner.

Disclosure : I'm not the developer of the app neither I'm affiliated with him in any way.

How to empty/destroy a session in rails?

To clear only certain parameters, you can use:

[:param1, :param2, :param3].each { |k| session.delete(k) }

Validate form field only on submit or user input

If you want to show error messages on form submission, you can use condition form.$submitted to check if an attempt was made to submit the form. Check following example.

<form name="myForm" novalidate ng-submit="myForm.$valid && createUser()">
  <input type="text" name="name" ng-model="user.name" placeholder="Enter name of user" required>
  <div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
    <div ng-message="required">Please enter user name.</div>
  </div>

  <input type="text" name="address" ng-model="user.address" placeholder="Enter Address" required ng-maxlength="30">
  <div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
    <div ng-message="required">Please enter user address.</div>
    <div ng-message="maxlength">Should be less than 30 chars</div>
  </div>

  <button type="submit">
    Create user
  </button>
</form>

$.browser is undefined error

The .browser call has been removed in jquery 1.9 have a look at http://jquery.com/upgrade-guide/1.9/ for more details.

Using an image caption in Markdown Jekyll

<p align="center">
  <img alt="img-name" src="/path/image-name.png" width="300">
  <br>
    <em>caption</em>
</p>

That is the basic caption use. Not necessary to use an extra plugin.

How to see JavaDoc in IntelliJ IDEA?

For me, it wasn't just getting the javadoc window to open, but also getting the complete javadoc to present. You may still get a sparse javadoc that is based solely on the method signature if you are importing libraries from a Maven repository and do not tell Idea to include the javadocs in the download. Be sure to tick the "JavaDocs" option in the "Download Library From Maven Repository" dialog, which can be found under Project Structure -> Projtect Settings -> Libraries.

How can I select all children of an element except the last child?

Nick Craver's solution gave me what I needed but to make it explicit for those using CSS-in-JS:

const styles = {
  yourClass: {
    /* Styles for all elements with this class */
    '&:not(:last-child)': {
      /* Styles for all EXCEPT the last element with this class */
    },
  },
};

Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted

in windows by xampp i just changed:

;memory_limit=512M 

in php.ini to:

memory_limit =-1

then restart the Apache by xampp

this is the result:

; Maximum amount of memory a script may consume
; http://php.net/memory-limit
memory_limit =-1
;memory_limit=512M

Get absolute path of initially run script

dirname(__FILE__) 

will give the absolute route of the current file from which you are demanding the route, the route of your server directory.

example files :

www/http/html/index.php ; if you place this code inside your index.php it will return:

<?php echo dirname(__FILE__); // this will return: www/http/html/

www/http/html/class/myclass.php ; if you place this code inside your myclass.php it will return:

<?php echo dirname(__FILE__); // this will return: www/http/html/class/

SQL Query - Change date format in query to DD/MM/YYYY

If I understood your question, try something like this

declare @dd varchar(50)='Jan 30 2013 12:00:00:000AM'

Select convert(varchar,(CONVERT(date,@dd,103)),103)

Update

SELECT
PREFIX_TableName.ColumnName1 AS Name,
PREFIX_TableName.ColumnName2 AS E-Mail,
convert(varchar,(CONVERT(date,PREFIX_TableName.ColumnName3,103)),103) AS TransactionDate,
PREFIX_TableName.ColumnName4 AS OrderNumber

Socket.IO handling disconnect event

Ok, instead of identifying players by name track with sockets through which they have connected. You can have a implementation like

Server

var allClients = [];
io.sockets.on('connection', function(socket) {
   allClients.push(socket);

   socket.on('disconnect', function() {
      console.log('Got disconnect!');

      var i = allClients.indexOf(socket);
      allClients.splice(i, 1);
   });
});

Hope this will help you to think in another way

Reset all the items in a form

    function setToggleInputsinPnl(pnlName) {
    var domCount = pnlName.length;
    for (var i = 0; i < domCount; i++) {
        if (pnlName[i].type == 'text') {
            pnlName[i].value = '';
        } else if (pnlName[i].type == 'select-one') {
               pnlName[i].value = '';
        }
    }
}

How to hide a div after some time period?

_x000D_
_x000D_
$().ready(function(){_x000D_
_x000D_
  $('div.alert').delay(1500);_x000D_
   $('div.alert').hide(1000);_x000D_
});
_x000D_
div.alert{_x000D_
color: green;_x000D_
background-color: rgb(50,200,50, .5);_x000D_
padding: 10px;_x000D_
text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="alert"><p>Inserted Successfully . . .</p></div>
_x000D_
_x000D_
_x000D_

Trigger a Travis-CI rebuild without pushing a commit?

If you have new project on GitHub which has .travis.yml, but was never tested, you can run tests without commit this way:

  1. enable testing in Travis CI setings
  2. open project page on GitHub
  3. open settings -> webhooks and services
  4. find Travis CI in services and press edit button
  5. press "Test service"

ERROR 1148: The used command is not allowed with this MySQL version

Refer to MySQL 8.0 Reference Manual -- 6.1.6 Security Issues with LOAD DATA LOCAL

On the server side, run

mysql.server start --local-infile

On the client side, run

mysql --local-infile database_name -u username -p

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

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

Building on pradeek's example:

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

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

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

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

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

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

    e.preventDefault();
});

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

Java: Convert a String (representing an IP) to InetAddress

Simply call InetAddress.getByName(String host) passing in your textual IP address.

From the javadoc: The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address.

InetAddress javadoc

Parse JSON from HttpURLConnection object

You can get raw data using below method. BTW, this pattern is for Java 6. If you are using Java 7 or newer, please consider try-with-resources pattern.

public String getJSON(String url, int timeout) {
    HttpURLConnection c = null;
    try {
        URL u = new URL(url);
        c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.setRequestProperty("Content-length", "0");
        c.setUseCaches(false);
        c.setAllowUserInteraction(false);
        c.setConnectTimeout(timeout);
        c.setReadTimeout(timeout);
        c.connect();
        int status = c.getResponseCode();

        switch (status) {
            case 200:
            case 201:
                BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line+"\n");
                }
                br.close();
                return sb.toString();
        }

    } catch (MalformedURLException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
    } finally {
       if (c != null) {
          try {
              c.disconnect();
          } catch (Exception ex) {
             Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
          }
       }
    }
    return null;
}

And then you can use returned string with Google Gson to map JSON to object of specified class, like this:

String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);
System.out.println(msg);

There is a sample of AuthMsg class:

public class AuthMsg {
    private int code;
    private String message;

    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}

JSON returned by http://localhost/authmanager.php must look like this:

{"code":1,"message":"Logged in"}

Regards

A simple scenario using wait() and notify() in java

Have you taken a look at this Java Tutorial?

Further, I'd advise you to stay the heck away from playing with this kind of stuff in real software. It's good to play with it so you know what it is, but concurrency has pitfalls all over the place. It's better to use higher level abstractions and synchronized collections or JMS queues if you are building software for other people.

That is at least what I do. I'm not a concurrency expert so I stay away from handling threads by hand wherever possible.

How to solve PHP error 'Notice: Array to string conversion in...'

You are using <input name='C[]' in your HTML. This creates an array in PHP when the form is sent.

You are using echo $_POST['C']; to echo that array - this will not work, but instead emit that notice and the word "Array".

Depending on what you did with the rest of the code, you should probably use echo $_POST['C'][0];

Why am I getting "IndentationError: expected an indented block"?

in python intended block mean there is every thing must be written in manner in my case I written it this way

 def btnClick(numbers):
 global operator
 operator = operator + str(numbers)
 text_input.set(operator)

Note.its give me error,until I written it in this way such that "giving spaces " then its giving me a block as I am trying to show you in function below code

def btnClick(numbers):
___________________________
|global operator
|operator = operator + str(numbers)
|text_input.set(operator)

SessionTimeout: web.xml vs session.maxInactiveInterval()

Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.

This is wrong. It will just kill the session when the associated client (webbrowser) has not accessed the website for more than 15 minutes. The activity certainly counts, exactly as you initially expected, seeing your attempt to solve this.

The HttpSession#setMaxInactiveInterval() doesn't change much here by the way. It does exactly the same as <session-timeout> in web.xml, with the only difference that you can change/set it programmatically during runtime. The change by the way only affects the current session instance, not globally (else it would have been a static method).


To play around and experience this yourself, try to set <session-timeout> to 1 minute and create a HttpSessionListener like follows:

@WebListener
public class HttpSessionChecker implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent event) {
        System.out.printf("Session ID %s created at %s%n", event.getSession().getId(), new Date());
    }

    public void sessionDestroyed(HttpSessionEvent event) {
        System.out.printf("Session ID %s destroyed at %s%n", event.getSession().getId(), new Date());
    }

}

(if you're not on Servlet 3.0 yet and thus can't use @WebListener, then register in web.xml as follows):

<listener>
    <listener-class>com.example.HttpSessionChecker</listener-class>
</listener>

Note that the servletcontainer won't immediately destroy sessions after exactly the timeout value. It's a background job which runs at certain intervals (e.g. 5~15 minutes depending on load and the servletcontainer make/type). So don't be surprised when you don't see destroyed line in the console immediately after exactly one minute of inactivity. However, when you fire a HTTP request on a timed-out-but-not-destroyed-yet session, it will be destroyed immediately.

See also:

How do I make a WinForms app go Full Screen

I recently made an Mediaplayer application and I used API-calls to make sure the taskbar was hidden when the program was running fullscreen and then restored the taskbar when the program was not in fullscreen or not had focus or was exited.

Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Integer
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" (ByVal hWnd1 As Integer, ByVal hWnd2 As Integer, ByVal lpsz1 As String, ByVal lpsz2 As String) As Integer
Private Declare Function ShowWindow Lib "user32" (ByVal hwnd As Integer, ByVal nCmdShow As Integer) As Integer

Sub HideTrayBar()
    Try


        Dim tWnd As Integer = 0
        Dim bWnd As Integer = 0
        tWnd = FindWindow("Shell_TrayWnd", vbNullString)
        bWnd = FindWindowEx(tWnd, bWnd, "BUTTON", vbNullString)
        ShowWindow(tWnd, 0)
        ShowWindow(bWnd, 0)
    Catch ex As Exception
        'Error hiding the taskbar, do what you want here..
    End Try
End Sub
Sub ShowTraybar()
    Try
        Dim tWnd As Integer = 0
        Dim bWnd As Integer = 0
        tWnd = FindWindow("Shell_TrayWnd", vbNullString)
        bWnd = FindWindowEx(tWnd, bWnd, "BUTTON", vbNullString)
        ShowWindow(bWnd, 1)
        ShowWindow(tWnd, 1)
    Catch ex As Exception
    'Error showing the taskbar, do what you want here..     
               End Try


End Sub

Error: getaddrinfo ENOTFOUND in nodejs for get call

Check host file which like this

##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1   localhost
255.255.255.255 broadcasthost

How to extract numbers from a string in Python?

# extract numbers from garbage string:
s = '12//n,_@#$%3.14kjlw0xdadfackvj1.6e-19&*ghn334'
newstr = ''.join((ch if ch in '0123456789.-e' else ' ') for ch in s)
listOfNumbers = [float(i) for i in newstr.split()]
print(listOfNumbers)
[12.0, 3.14, 0.0, 1.6e-19, 334.0]

How to disable Home and other system buttons in Android?

I followed the shaobin0604's answer and I finally managed to lock the HOME button, by adding:

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

to AndroidManifest.xml All you have to do is to copy HomeKeyLocker.java from shaobin's lib to your project and implement it like in shaobin's example. BTW: My AVD's Android version is Android 4.0.3.

What is the difference between "Rollback..." and "Back Out Submitted Changelist #####" in Perforce P4V

Rollback... will prompt you to select a folder to rollback, ie, it will work on specific folders, and you can rollback to labels or changlists or dates. Back out works on the files in specific changelists.

c# write text on bitmap

Bitmap bmp = new Bitmap("filename.bmp");

RectangleF rectf = new RectangleF(70, 90, 90, 50);

Graphics g = Graphics.FromImage(bmp);

g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.DrawString("yourText", new Font("Tahoma",8), Brushes.Black, rectf);

g.Flush();

image.Image=bmp;

How do you hide the Address bar in Google Chrome for Chrome Apps?

Uncheck Always Show Toolbar in Full Screen in View menu:

enter image description here

and go to fullscreen then:

Alt+Cmd+F - on Mac

F11 - on Windows

Switching to a TabBar tab view programmatically?

import UIKit

class TabbarViewController: UITabBarController,UITabBarControllerDelegate {

//MARK:- View Life Cycle

override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

//Tabbar delegate method
override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
    let yourView = self.viewControllers![self.selectedIndex] as! UINavigationController
    yourView.popToRootViewController(animated:false)
}



}

html vertical align the text inside input type button

I was having a similar issue with my button. I included line-height: 0; and it appears to have worked. Also mentioned by @anddero.

button[type=submit] {
  background-color: #4056A1;
  border-radius: 12px;
  border: 1px solid #4056A1;
  color: white;
  padding: 16px 32px;
  text-decoration: none;
  margin: 2px 1px;
  cursor: pointer;
  display: inline-block;
  font-size: 16px;
  height: 20px;
  line-height: 0;
}

Testing if a list of integer is odd or even

--simple codes--

        #region odd / even numbers  order by desc

        //declaration of integer
        int TotalCount = 50;
        int loop;

        Console.WriteLine("\n---------Odd Numbers -------\n");

        for (loop = TotalCount; loop >= 0; loop--)
        {
            if (loop % 2 == 0)
            {
                Console.WriteLine("Even numbers : #{0}", loop);
            }
        }

        Console.WriteLine("\n---------Even Numbers -------\n");

        for (loop = TotalCount; loop >= 0; loop--)
        {
            if (loop % 2 != 0)
            {
                Console.WriteLine("odd numbers : #{0}", loop);
            }
        }

        Console.ReadLine();

        #endregion

How do I protect javascript files?

The only thing you can do is obfuscate your code to make it more difficult to read. No matter what you do, if you want the javascript to execute in their browser they'll have to have the code.

Where can I find php.ini?

Best way to find this is: create a php file and add the following code:

<?php phpinfo(); ?>

and open it in browser, it will show the file which is actually being read!

Updates by OP:

  1. The previously accepted answer is likely to be faster and more convenient for you, but it is not always correct. See comments on that answer.
  2. Please also note the more convenient alternative <?php echo php_ini_loaded_file(); ?> mentioned in this answer.

How to create a file in Ruby

Use:

File.open("out.txt", [your-option-string]) {|f| f.write("write your stuff here") }

where your options are:

  • r - Read only. The file must exist.
  • w - Create an empty file for writing.
  • a - Append to a file.The file is created if it does not exist.
  • r+ - Open a file for update both reading and writing. The file must exist.
  • w+ - Create an empty file for both reading and writing.
  • a+ - Open a file for reading and appending. The file is created if it does not exist.

In your case, 'w' is preferable.

OR you could have:

out_file = File.new("out.txt", "w")
#...
out_file.puts("write your stuff here")
#...
out_file.close

frequent issues arising in android view, Error parsing XML: unbound prefix

This error usually occurs if you have not included the xmlns:mm properly, it occurs usually in the first line of code.

for me it was..

xmlns:mm="http://millennialmedia.com/android/schema"

that i missed in first line of the code

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mm="http://millennialmedia.com/android/schema"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginTop="50dp"
android:layout_marginBottom="50dp"
android:background="@android:color/transparent" >

Comparing two hashmaps for equal values and same key sets?

if you have two maps lets say map1 and map2 then using java8 Streams,we can compare maps using code below.But it is recommended to use equals rather then != or ==

boolean b = map1.entrySet().stream().filter(value -> 
            map2.entrySet().stream().anyMatch(value1 -> 
            (value1.getKey().equals(value.getKey()) && 
  value1.getValue().equals(value.getValue())))).findAny().isPresent();   


System.out.println("comparison  "+b);

Empty or Null value display in SSRS text boxes

Try this

=IIF(IsNothing(Fields!MyField.Value)=TRUE,"NA",Fields!MyFields.Value)

Extract a page from a pdf as a jpeg

Here is a function that does the conversion of a PDF file with one or multiple pages to a single merged JPEG image.

import os
import tempfile
from pdf2image import convert_from_path
from PIL import Image

def convert_pdf_to_image(file_path, output_path):
    # save temp image files in temp dir, delete them after we are finished
    with tempfile.TemporaryDirectory() as temp_dir:
        # convert pdf to multiple image
        images = convert_from_path(file_path, output_folder=temp_dir)
        # save images to temporary directory
        temp_images = []
        for i in range(len(images)):
            image_path = f'{temp_dir}/{i}.jpg'
            images[i].save(image_path, 'JPEG')
            temp_images.append(image_path)
        # read images into pillow.Image
        imgs = list(map(Image.open, temp_images))
    # find minimum width of images
    min_img_width = min(i.width for i in imgs)
    # find total height of all images
    total_height = 0
    for i, img in enumerate(imgs):
        total_height += imgs[i].height
    # create new image object with width and total height
    merged_image = Image.new(imgs[0].mode, (min_img_width, total_height))
    # paste images together one by one
    y = 0
    for img in imgs:
        merged_image.paste(img, (0, y))
        y += img.height
    # save merged image
    merged_image.save(output_path)
    return output_path

Example usage: -

convert_pdf_to_image("path_to_Pdf/1.pdf", "output_path/output.jpeg")

Http Basic Authentication in Java using HttpClient?

Thanks for all answers above, but for me, I can not find Base64Encoder class, so I sort out my way anyway.

public static void main(String[] args) {
    try {
        DefaultHttpClient Client = new DefaultHttpClient();

        HttpGet httpGet = new HttpGet("https://httpbin.org/basic-auth/user/passwd");
        String encoding = DatatypeConverter.printBase64Binary("user:passwd".getBytes("UTF-8"));
        httpGet.setHeader("Authorization", "Basic " + encoding);

        HttpResponse response = Client.execute(httpGet);

        System.out.println("response = " + response);

        BufferedReader breader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuilder responseString = new StringBuilder();
        String line = "";
        while ((line = breader.readLine()) != null) {
            responseString.append(line);
        }
        breader.close();
        String repsonseStr = responseString.toString();

        System.out.println("repsonseStr = " + repsonseStr);

    } catch (IOException e) {
        e.printStackTrace();
    }

}

One more thing, I also tried

Base64.encodeBase64String("user:passwd".getBytes());

It does NOT work due to it return a string almost same with

DatatypeConverter.printBase64Binary()

but end with "\r\n", then server will return "bad request".

Also following code is working as well, actually I sort out this first, but for some reason, it does NOT work in some cloud environment (sae.sina.com.cn if you want to know, it is a chinese cloud service). so have to use the http header instead of HttpClient credentials.

public static void main(String[] args) {
    try {
        DefaultHttpClient Client = new DefaultHttpClient();
        Client.getCredentialsProvider().setCredentials(
                AuthScope.ANY,
                new UsernamePasswordCredentials("user", "passwd")
        );

        HttpGet httpGet = new HttpGet("https://httpbin.org/basic-auth/user/passwd");
        HttpResponse response = Client.execute(httpGet);

        System.out.println("response = " + response);

        BufferedReader breader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuilder responseString = new StringBuilder();
        String line = "";
        while ((line = breader.readLine()) != null) {
            responseString.append(line);
        }
        breader.close();
        String responseStr = responseString.toString();
        System.out.println("responseStr = " + responseStr);

    } catch (IOException e) {
        e.printStackTrace();
    }
}

How to upgrade OpenSSL in CentOS 6.5 / Linux / Unix from source?

I agree that in 95% of cases, all you need is sudo yum update openssl

However, if you need a specific version of openssl or specific functionality, which is not in CentOS repository, you probably need to compile from source. The other answers here were incomplete. Below is what worked (CentOS 6.9), although this may introduce incompatibilities with installed software, and will not auto-update the openssl.


Choose openssl version from https://www.openssl.org/source/

Log-in as root:

cd /usr/local/src/

# OPTIONALLY CHANGE openssl-1.1.0f.tar.gz to the version which you want
wget https://www.openssl.org/source/openssl-1.1.0f.tar.gz

sha256sum openssl-1.1.0f.tar.gz  #confirm this matches the published hash

tar -zxf openssl-1.1.0f.tar.gz

cd /usr/local/src/openssl-1.1.0f

./config --prefix=/usr/local --openssldir=/usr/local/openssl
make
make test
make install

export LD_LIBRARY_PATH=/usr/local/lib64

#make export permanent
echo "export LD_LIBRARY_PATH=/usr/local/lib64" > /etc/profile.d/ld_library_path.sh
chmod ugo+x /etc/profile.d/ld_library_path.sh

openssl version  #confirm it works

#recommended reboot here

openssl version  #confirm it works after reboot

Conversion hex string into ascii in bash command line

The echo -e must have been failing for you because of wrong escaping. The following code works fine for me on a similar output from your_program with arguments:

echo -e $(your_program with arguments | sed -e 's/0x\(..\)\.\?/\\x\1/g')

Please note however that your original hexstring consists of non-printable characters.

How do I programmatically force an onchange event on an input?

if you're using jQuery you would have:

$('#elementId').change(function() { alert('Do Stuff'); });

or MS AJAX:

$addHandler($get('elementId'), 'change', function(){ alert('Do Stuff'); });

Or in the raw HTML of the element:

<input type="text" onchange="alert('Do Stuff');" id="myElement" />

After re-reading the question I think I miss-read what was to be done. I've never found a way to update a DOM element in a manner which will force a change event, what you're best doing is having a separate event handler method, like this:

$addHandler($get('elementId'), 'change', elementChanged);
function elementChanged(){
  alert('Do Stuff!');
}
function editElement(){
  var el = $get('elementId');
  el.value = 'something new';
  elementChanged();
}

Since you're already writing a JavaScript method which will do the changing it's only 1 additional line to call.

Or, if you are using the Microsoft AJAX framework you can access all the event handlers via:

$get('elementId')._events

It'd allow you to do some reflection-style workings to find the right event handler(s) to fire.

VERR_VMX_MSR_VMXON_DISABLED when starting an image from Oracle virtual box

When I try to set Base Memory around 4000MB (my pc have 8GB) I get the same error 'VT-x is disabled in the BIOS'. But when I reduce Base Memory to 2500MB it works and error is solved.

if statement in ng-click

From http://php.quicoto.com/inline-ifelse-statement-ngclick-angularjs/, this is how you do it, if you really have to:

ng-click="variable = (condition=='X' ? 'Y' : 'X')"

iFrame Height Auto (CSS)

I had this same issue but found the following that works great:

The key to creating a responsive YouTube embed is with padding and a container element, which allows you to give it a fixed aspect ratio. You can also use this technique with most other iframe-based embeds, such as slideshows.

Here is what a typical YouTube embed code looks like, with fixed width and height:

 <iframe width="560" height="315" src="//www.youtube.com/embed/yCOY82UdFrw" 
 frameborder="0" allowfullscreen></iframe>

It would be nice if we could just give it a 100% width, but it won't work as the height remains fixed. What you need to do is wrap it in a container like so (note the class names and removal of the width and height):

 <div class="container">
 <iframe src="//www.youtube.com/embed/yCOY82UdFrw" 
 frameborder="0" allowfullscreen class="video"></iframe>
 </div>

And use the following CSS:

 .container {
    position: relative;
     width: 100%;
     height: 0;
     padding-bottom: 56.25%;
 }
 .video {
     position: absolute;
     top: 0;
     left: 0;
     width: 100%;
     height: 100%;
 }

Here is the page I found the solution on:

https://www.h3xed.com/web-development/how-to-make-a-responsive-100-width-youtube-iframe-embed

Depending on your aspect ratio, you will probably need to adjust the padding-bottom: 56.25%; to get the height right.

Can't connect to localhost on SQL Server Express 2012 / 2016

After doing the steps which were mentioned by @Ravindra Bagale, Try this step. Server name: localhost\{Instance name you were gave}

enter image description here

How to create table using select query in SQL Server?

select <column list> into <table name> from <source> where <whereclause>

Variable might not have been initialized error

because of your a and b variable is not have been initialized. You must initialized this variables for excample if you declare this variable like this int a=0; int b=0; than your code run without error.

How can I create and style a div using JavaScript?

_x000D_
_x000D_
var div = document.createElement("div");_x000D_
div.style.width = "100px";_x000D_
div.style.height = "100px";_x000D_
div.style.background = "red";_x000D_
div.style.color = "white";_x000D_
div.innerHTML = "Hello";_x000D_
_x000D_
document.getElementById("main").appendChild(div);
_x000D_
<body>_x000D_
<div id="main"></div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.color = "white";
div.innerHTML = "Hello";

document.getElementById("main").appendChild(div);
OR
document.body.appendChild(div);

Use parent reference instead of document.body.

Draw text in OpenGL ES

The Android SDK doesn't come with any easy way to draw text on OpenGL views. Leaving you with the following options.

  1. Place a TextView over your SurfaceView. This is slow and bad, but the most direct approach.
  2. Render common strings to textures, and simply draw those textures. This is by far the simplest and fastest, but the least flexible.
  3. Roll-your-own text rendering code based on a sprite. Probably second best choice if 2 isn't an option. A good way to get your feet wet but note that while it seems simple (and basic features are), it get's harder and more challenging as you add more features (texture-alignment, dealing with line-breaks, variable-width fonts etc.) - if you take this route, make it as simple as you can get away with!
  4. Use an off-the-shelf/open-source library. There are a few around if you hunt on Google, the tricky bit is getting them integrated and running. But at least, once you do that, you'll have all the flexibility and maturity they provide.

Handling onchange event in HTML.DropDownList Razor MVC

Description

You can use another overload of the DropDownList method. Pick the one you need and pass in a object with your html attributes.

Sample

@Html.DropDownList("CategoryID", null, new { @onchange="location = this.value;" })

More Information

Error starting Tomcat from NetBeans - '127.0.0.1*' is not recognized as an internal or external command

I didnt try Sumama Waheed's answer but what worked for me was replacing the bin/catalina.jar with a working jar (I disposed of an older tomcat) and after adding in NetBeans, I put the original catalina.jar again.

Stretch and scale CSS background

Add a background-attachment line:

#background {
    background-attachment:fixed;
    width: 100%; 
    height: 100%; 
    position: absolute; 
    margin-left: 0px; 
    margin-top: 0px; 
    z-index: 0;
}

.stretch {
    width:100%;
    height:auto;
}

Command line .cmd/.bat script, how to get directory of running script

This is equivalent to the path of the script:

%~dp0

This uses the batch parameter extension syntax. Parameter 0 is always the script itself.

If your script is stored at C:\example\script.bat, then %~dp0 evaluates to C:\example\.

ss64.com has more information about the parameter extension syntax. Here is the relevant excerpt:

You can get the value of any parameter using a % followed by it's numerical position on the command line.

[...]

When a parameter is used to supply a filename then the following extended syntax can be applied:

[...]

%~d1 Expand %1 to a Drive letter only - C:

[...]

%~p1 Expand %1 to a Path only e.g. \utils\ this includes a trailing \ which may be interpreted as an escape character by some commands.

[...]

The modifiers above can be combined:

%~dp1 Expand %1 to a drive letter and path only

[...]

You can get the pathname of the batch script itself with %0, parameter extensions can be applied to this so %~dp0 will return the Drive and Path to the batch script e.g. W:\scripts\

new Date() is working in Chrome but not Firefox

Simple Solution, This works with All Browsers,

var StringDate = "24-11-2017"   
var DateVar = StringDate.split("-");
var DateVal = new Date(DateVar[1] + "/" + DateVar[0] + "/" + DateVar[2]);
alert(DateVal);

in iPhone App How to detect the screen resolution of the device

For iOS 8 we can just use this [UIScreen mainScreen].nativeBounds , like that:

- (NSInteger)resolutionX
{
    return CGRectGetWidth([UIScreen mainScreen].nativeBounds);
}

- (NSInteger)resolutionY
{
    return CGRectGetHeight([UIScreen mainScreen].nativeBounds);
}

List<Object> and List<?>

package com.test;

import java.util.ArrayList;
import java.util.List;

public class TEst {

    public static void main(String[] args) {

        List<Integer> ls=new ArrayList<>();
        ls.add(1);
        ls.add(2);
        List<Integer> ls1=new ArrayList<>();
        ls1.add(3);
        ls1.add(4);
        List<List<Integer>> ls2=new ArrayList<>();
        ls2.add(ls);
        ls2.add(ls1);

        List<List<List<Integer>>> ls3=new ArrayList<>();
        ls3.add(ls2);


        m1(ls3);
    }

    private static void m1(List ls3) {
        for(Object ls4:ls3)
        {
             if(ls4 instanceof List)    
             {
                m1((List)ls4);
             }else {
                 System.out.print(ls4);
             }

        }
    }

}

Reading and writing binary file

It can be done with simple commands in the following snippet.

Copies the whole file of any size. No size constraint!

Just use this. Tested And Working!!

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
  ifstream infile;
  infile.open("source.pdf",ios::binary|ios::in);

  ofstream outfile;
  outfile.open("temppdf.pdf",ios::binary|ios::out);

  int buffer[2];
  while(infile.read((char *)&buffer,sizeof(buffer)))
  {
      outfile.write((char *)&buffer,sizeof(buffer));
  }

  infile.close();
  outfile.close();
  return 0;
}

Having a smaller buffer size would be helpful in copying tiny files. Even "char buffer[2]" would do the job.

How to change language of app when user selects language?

all the above @Uday's code is perfect but only one thing is missing(default config in build.gradle)

public void setLocale(String lang) { 
Locale myLocale = new Locale(lang); 
Resources res = getResources(); 
DisplayMetrics dm = res.getDisplayMetrics(); 
Configuration conf = res.getConfiguration(); 
conf.locale = myLocale; 
res.updateConfiguration(conf, dm); 
Intent refresh = new Intent(this, AndroidLocalize.class); 
finish();
startActivity(refresh); 

}

Mine was not working just because the languages were not mentioned in the config file(build.gradle)

 defaultConfig {
    resConfigs "en", "hi", "kn"
}

after that, all languages started running

`React/RCTBridgeModule.h` file not found

anhdevit's suggestion in https://github.com/facebook/react-native/issues/24363#issuecomment-488547280 worked for me:

In your terminal, run: defaults delete com.apple.dt.Xcode

display: inline-block extra margin

Can you post a link to the HTML in question?

Ultimately you should be able to do:

div {
    margin:0;
    padding: 0;
}

to remove the spacing. Is this just in one particular browser or all of them?

Find Process Name by its Process ID

Using only "native" Windows utilities, try the following, where "516" is the process ID that you want the image name for:

for /f "delims=," %a in ( 'tasklist /fi "PID eq 516" /nh /fo:csv' ) do ( echo %~a )
for /f %a in ( 'tasklist /fi "PID eq 516" ^| findstr "516"' ) do ( echo %a )

Or you could use wmic (the Windows Management Instrumentation Command-line tool) and get the full path to the executable:

wmic process where processId=516 get name
wmic process where processId=516 get ExecutablePath

Or you could download Microsoft PsTools, or specifically download just the pslist utility, and use PsList:

for /f %a in ( 'pslist 516 ^| findstr "516"' ) do ( echo %a )

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

When you use recv in connection with select if the socket is ready to be read from but there is no data to read that means the client has closed the connection.

Here is some code that handles this, also note the exception that is thrown when recv is called a second time in the while loop. If there is nothing left to read this exception will be thrown it doesn't mean the client has closed the connection :

def listenToSockets(self):

    while True:

        changed_sockets = self.currentSockets

        ready_to_read, ready_to_write, in_error = select.select(changed_sockets, [], [], 0.1)

        for s in ready_to_read:

            if s == self.serverSocket:
                self.acceptNewConnection(s)
            else:
                self.readDataFromSocket(s)

And the function that receives the data :

def readDataFromSocket(self, socket):

    data = ''
    buffer = ''
    try:

        while True:
            data = socket.recv(4096)

            if not data: 
                break

            buffer += data

    except error, (errorCode,message): 
        # error 10035 is no data available, it is non-fatal
        if errorCode != 10035:
            print 'socket.error - ('+str(errorCode)+') ' + message


    if data:
        print 'received '+ buffer
    else:
        print 'disconnected'

How do I subscribe to all topics of a MQTT broker

You can use mosquitto_sub (which is part of the mosquitto-clients package) and subscribe to the wildcard topic #:

mosquitto_sub -v -h broker_ip -p 1883 -t '#'

How can I get a side-by-side diff when I do "git diff"?

This may be a somewhat limited solution, but does the job using the system's diff command without external tools:

diff -y  <(git show from-rev:the/file/path) <(git show to-rev:the/file/path)
  • filter just the change lines use --suppress-common-lines (if your diff supports the option).
  • no colors in this case, just the usual diff markers
  • can tweak the column width --width=term-width; in Bash can get the width as $COLUMNS or tput cols.

This can be wrapped into a helper git-script too for more convenience, for example, usage like this:

git diffy the/file/path --from rev1 --to rev2

Java Code for calculating Leap Year

As wikipedia states algorithm for the leap year should be

(((year%4 == 0) && (year%100 !=0)) || (year%400==0))  

Here is a sample program how to check for leap year.

How to search for an element in a golang slice

With a simple for loop:

for _, v := range myconfig {
    if v.Key == "key1" {
        // Found!
    }
}

Note that since element type of the slice is a struct (not a pointer), this may be inefficient if the struct type is "big" as the loop will copy each visited element into the loop variable.

It would be faster to use a range loop just on the index, this avoids copying the elements:

for i := range myconfig {
    if myconfig[i].Key == "key1" {
        // Found!
    }
}

Notes:

It depends on your case whether multiple configs may exist with the same key, but if not, you should break out of the loop if a match is found (to avoid searching for others).

for i := range myconfig {
    if myconfig[i].Key == "key1" {
        // Found!
        break
    }
}

Also if this is a frequent operation, you should consider building a map from it which you can simply index, e.g.

// Build a config map:
confMap := map[string]string{}
for _, v := range myconfig {
    confMap[v.Key] = v.Value
}

// And then to find values by key:
if v, ok := confMap["key1"]; ok {
    // Found
}

HTML5 Video autoplay on iPhone

iOs 10+ allow video autoplay inline. but you have to turn off "Low power mode" on your iPhone.

I want to compare two lists in different worksheets in Excel to locate any duplicates

Without VBA...

If you can use a helper column, you can use the MATCH function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match

To simply identify duplicates, use a helper column

Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:

=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")

Drag/copy this forumla down, and it should identify the duplicates.

To highlight cells, use conditional formatting:

With some tinkering, you can use this MATCH function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.

Something like:

=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))

Conditional formatting for Excel 2010

For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:

=B1="Duplicate"

This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.

Conditional formatting using helper column for rule

Android Design Support Library expandable Floating Action Button(FAB) menu

When I tried to create something simillar to inbox floating action button i thought about creating own custom component.

It would be simple frame layout with fixed height (to contain expanded menu) containing FAB button and 3 more placed under the FAB. when you click on FAB you just simply animate other buttons to translate up from under the FAB.

There are some libraries which do that (for example https://github.com/futuresimple/android-floating-action-button), but it's always more fun if you create it by yourself :)

"column not allowed here" error in INSERT statement

INSERT INTO LOCATION VALUES(PQ95VM,'HAPPY_STREET','FRANCE');

the above mentioned code is not correct because your first parameter POSTCODE is of type VARCHAR(10). you should have used ' '.

try INSERT INTO LOCATION VALUES('PQ95VM','HAPPY_STREET','FRANCE');

CSS selector for a checked radio button's label

You could use a bit of jQuery:

$('input:radio').click(function(){
    $('label#' + $(this).attr('id')).toggleClass('checkedClass'); // checkedClass is defined in your CSS
});

You'd need to make sure your checked radio buttons have the correct class on page load as well.

Dynamically set value of a file input

I am working on an angular js app, andhavecome across a similar issue. What i did was display the image from the db, then created a button to remove or keep the current image. If the user decided to keep the current image, i changed the ng-submit attribute to another function whihc doesnt require image validation, and updated the record in the db without touching the original image path name. The remove image function also changed the ng-submit attribute value back to a function that submits the form and includes image validation and upload. Also a bit of javascript to slide the into view to upload a new image.

What is aria-label and how should I use it?

The title attribute displays a tooltip when the mouse is hovering the element. While this is a great addition, it doesn't help people who cannot use the mouse (due to mobility disabilities) or people who can't see this tooltip (e.g.: people with visual disabilities or people who use a screen reader).

As such, the mindful approach here would be to serve all users. I would add both title and aria-label attributes (serving different types of users and different types of usage of the web).

Here's a good article that explains aria-label in depth

Using routes in Express-js

So, after I created my question, I got this related list on the right with a similar issue: Organize routes in Node.js.

The answer in that post linked to the Express repo on GitHub and suggests to look at the 'route-separation' example.

This helped me change my code, and I now have it working. - Thanks for your comments.

My implementation ended up looking like this;

I require my routes in the app.js:

var express = require('express')
  , site = require('./site')
  , wiki = require('./wiki');

And I add my routes like this:

app.get('/', site.index);
app.get('/wiki/:id', wiki.show);
app.get('/wiki/:id/edit', wiki.edit);

I have two files called wiki.js and site.js in the root of my app, containing this:

exports.edit = function(req, res) {

    var wiki_entry = req.params.id;

    res.render('wiki/edit', {
        title: 'Editing Wiki',
        wiki: wiki_entry
    })
}

FFT in a single C-file

Your best bet is KissFFT - as its name implies it's simple, but it's still quite respectably fast, and a lot more lightweight than FFTW. It's also free, wheras FFTW requires a hefty licence fee if you want to include it in a commercial product.

Javascript return number of days,hours,minutes,seconds between two dates

Here's in javascript: (For example, the future date is New Year's Day)

DEMO (updates every second)

var dateFuture = new Date(new Date().getFullYear() +1, 0, 1);
var dateNow = new Date();

var seconds = Math.floor((dateFuture - (dateNow))/1000);
var minutes = Math.floor(seconds/60);
var hours = Math.floor(minutes/60);
var days = Math.floor(hours/24);

hours = hours-(days*24);
minutes = minutes-(days*24*60)-(hours*60);
seconds = seconds-(days*24*60*60)-(hours*60*60)-(minutes*60);

How can I set the opacity or transparency of a Panel in WinForms?

Based on information found at http://www.windows-tech.info/3/53ee08e46d9cb138.php, I was able to achieve a translucent panel control using the following code.

public class TransparentPanel : Panel
{
    protected override CreateParams CreateParams
    {
        get
        {
            var cp = base.CreateParams;
            cp.ExStyle |= 0x00000020; // WS_EX_TRANSPARENT

            return cp;
        }
    }

    protected override void OnPaint(PaintEventArgs e) =>
        e.Graphics.FillRectangle(new SolidBrush(this.BackColor), this.ClientRectangle);
}

The caveat is that any controls that are added to the panel have an opaque background. Nonetheless, the translucent panel was useful for me to block off parts of my WinForms application so that users focus was shifted to the appropriate area of the application.

How to make MySQL table primary key auto increment with some prefix

Here is PostgreSQL example without trigger if someone need it on PostgreSQL:

CREATE SEQUENCE messages_seq;

 CREATE TABLE IF NOT EXISTS messages (
    id CHAR(20) NOT NULL DEFAULT ('message_' || nextval('messages_seq')),
    name CHAR(30) NOT NULL,
);

ALTER SEQUENCE messages_seq OWNED BY messages.id;

Checkout one file from Subversion

An update in case what you really need can be covered by having the file included in a checkout of another folder.

Since SVN 1.6 you can make file externals, a kind of svn links. It means that you can have another versioned folder that includes a single file. Committing changes to the file in a checkout of this folder is also possible.

It's very simple, checkout the folder you want to include the file, and simply add a property to the folder

svn propedit svn:externals .

with content like this:

file.txt /repos/path/to/file.txt

After you commit this, the file will appear in future checkouts of the folder. Basically it works, but there are some limitations as described in the documentation linked above.

Clang vs GCC - which produces faster binaries?

Phoronix did some benchmarks about this, but it is about a snapshot version of Clang/LLVM from a few months back. The results being that things were more-or-less a push; neither GCC nor Clang is definitively better in all cases.

Since you'd use the latest Clang, it's maybe a little less relevant. Then again, GCC 4.6 is slated to have some major optimizations for Core 2 and i7, apparently.

I figure Clang's faster compilation speed will be nicer for original developers, and then when you push the code out into the world, Linux distro/BSD/etc. end-users will use GCC for the faster binaries.

iPhone: How to get current milliseconds?

// Timestamp after converting to milliseconds.

NSString * timeInMS = [NSString stringWithFormat:@"%lld", [@(floor([date timeIntervalSince1970] * 1000)) longLongValue]];

browser.msie error after update to jQuery 1.9.1

For simple IE detection I tend to use:

(/msie|trident/i).test(navigator.userAgent)

Visit the Microsoft Developer Network to learn about the IE useragent: http://msdn.microsoft.com/library/ms537503.aspx

Responsive width Facebook Page Plugin

Facebook's new "Page Plugin" width ranges from 180px to 500px as per the documentation.

  • If configured below 180px it would enforce a minimum width of 180px
  • If configured above 500px it would enforce a maximum width of 500px

With Adaptive Width checked, ex:

enter image description here

Unlike like-box, this plugin enforces its limits by sticking to the boundary values if mis-configured.

For small screens / Responsive behaviors

  • When rendering on smaller screens, enforce desiered width on the plugin container and plugin would try to fit in.

  • The plugin renders at a smaller width (to fit in smaller screens) automatically, if the container is of slimmer than the configured width.

  • You can scale down the container on mobile and the plugin will fit in as long as it gets the minimum of 180px to fit in.

Without Adaptive Width

enter image description here

  • The plugin will render at the width specified, irrespective of the container width

Which encoding opens CSV files correctly with Excel on both Mac and Windows?

It seems to my case that Excel 2011 for Mac OS is not using Encoding.GetEncoding("10000") as i thought and wasted 2 days with but the same iso as on Microsoft OS. The best proof for this is to make a file in Excel 2011 for MAC with special chars, save it as CSV and then open it in MAC text editor and the chars are scrambled.

For me this approach worked - meaning that csv export on Excel 2011 on MAC OS has special western europeean chars inside:

Encoding isoMacOS = Encoding.GetEncoding("iso-8859-1");
Encoding defaultEncoding = Encoding.Default; 

// Convert the string into a byte array.
byte[] defaultEncodingBytes = defaultEncoding.GetBytes(exportText);

// Perform the conversion from one encoding to the other.
byte[] ansiBytes = Encoding.Convert(defaultEncoding, isoMacOS, defaultEncodingBytes);

decodedString = isoMacOS.GetString(ansiBytes);

Iterating through directories with Python

The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple print statement you can see that each file is found:

import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print os.path.join(subdir, file)

If you still get errors when running the above, please provide the error message.


Updated for Python3

import os
rootdir = 'C:/Users/sid/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print(os.path.join(subdir, file))

What's the best way to add a drop shadow to my UIView

You can set shadow to your view from storyboard also

enter image description here

Difference between $(this) and event.target?

There are cross browser issues here.

A typical non-jQuery event handler would be something like this :

function doSomething(evt) {
    evt = evt || window.event;
    var target = evt.target || evt.srcElement;
    if (target.nodeType == 3) // defeat Safari bug
        target = target.parentNode;
    //do stuff here
}

jQuery normalises evt and makes the target available as this in event handlers, so a typical jQuery event handler would be something like this :

function doSomething(evt) {
    var $target = $(this);
    //do stuff here
}

A hybrid event handler which uses jQuery's normalised evt and a POJS target would be something like this :

function doSomething(evt) {
    var target = evt.target || evt.srcElement;
    if (target.nodeType == 3) // defeat Safari bug
        target = target.parentNode;
    //do stuff here
}

JUNIT testing void methods

You can learn something called "mocking". You can use this, for example, to check if: - a function was called - a function was called x times - a function was called at least x times - a function was called with a specific set of parameters. In your case, for example, you can use mocking to check that method3 was called once with whatever you pass as arg1 and arg2.

Have a look at these: https://code.google.com/p/mockito/ https://code.google.com/p/powermock/

Deploying Java webapp to Tomcat 8 running in Docker container

There's a oneliner for this one.

You can simply run,

docker run -v /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war:/usr/local/tomcat/webapps/myapp.war -it -p 8080:8080 tomcat

This will copy the war file to webapps directory and get your app running in no time.

Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar

You can find the source images by extracting them from Other.artwork in UIKit ${SDKROOT}/System/Library/Frameworks/UIKit.framework/Other.artwork. The modding community has some tools for extracting them, here. Once you extract the image you can write some code to recolor it as necessary and set it as the button image. Whether or not you can actually ship such a thing (since you are embedding derived artwork) might be a little dicey, so maybe you want to talk to a lawyer.

Setting attribute disabled on a SPAN element does not prevent click events

The disabled attribute is not global and is only allowed on form controls. What you could do is set a custom data attribute (perhaps data-disabled) and check for that attribute when you handle the click event.

Python 3 string.join() equivalent?

str.join() works fine in Python 3, you just need to get the order of the arguments correct

>>> str.join('.', ('a', 'b', 'c'))
'a.b.c'

Get GMT Time in Java

I wonder why no one does this:

Calendar time = Calendar.getInstance();
time.add(Calendar.MILLISECOND, -time.getTimeZone().getOffset(time.getTimeInMillis()));
Date date = time.getTime();

Update: Since Java 8,9,10 and more, there should be better alternatives supported by Java. Thanks for your comment @humanity

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

Just spent a hour or so doing this and with the help of Brad's advice and a few additional changes it all worked.

I've done this using the following: 10.7.3, Xcode 4.3.2, iOS 5.1 btw.

1) Right click on your myapp.xcodeproj and select package contents

2) open project.pbxproj with a text editor (don't recommend textedit as it may screw up the formatting)

3) Scroll all the way down until you find /* Begin XCBuildConfiguration section */

4) Notice that you have a debug and release sections

5) In the release section take a look at CODE_SIGN_IDENTITY & "CODE_SIGN_IDENTITY[sdk=iphoneos*]" it should look something like this:

CODE_SIGN_IDENTITY = "iPhone Distribution: MyCompany LLC";
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Distribution: MyCompany LLC";

6) Take a look at PROVISIONING_PROFILE and "PROVISIONING_PROFILE[sdk=iphoneos*]" they should look like this:

PROVISIONING_PROFILE = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";
"PROVISIONING_PROFILE[sdk=iphoneos*]" = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";

This should match your provisioning profile in Xcode. To see if they match open Xcode > Window > Organizer > Devices > Provisioning Profiles > Right click on the profile > Reveal in Finder > The filename of the .mobileprovision is your profile id.

7) Scroll down in the project.pbxproj and find a second instance of the release section. The second instance of the release section should end with a comment saying /* End XCBuildConfiguration section */

8) make sure that the second section matches the first section so that CODE_SIGN_IDENTITY, "CODE_SIGN_IDENTITY[sdk=iphoneos*], and PROVISIONING_PROFILE are all filled in.

How to prevent a double-click using jQuery?

jQuery's one() will fire the attached event handler once for each element bound, and then remove the event handler.

If for some reason that doesn't fulfill the requirements, one could also disable the button entirely after it has been clicked.

$(document).ready(function () {
     $("#submit").one('click', function (event) {  
           event.preventDefault();
           //do something
           $(this).prop('disabled', true);
     });
});

It should be noted that using the ID submit can cause issues, as it overwrites the form.submit function with a reference to that element.

CSS "color" vs. "font-color"

The same way Boston came up with its street plan. They followed the cow paths already there, and built houses where the streets weren't, and after a while it was too much trouble to change.

How to turn a String into a JavaScript function call?

This took me a while to figure out, as the conventional window['someFunctionName']() did not work for me at first. The names of my functions were being pulled as an AJAX response from a database. Also, for whatever reason, my functions were declared outside of the scope of the window, so in order to fix this I had to rewrite the functions I was calling from

function someFunctionName() {}

to

window.someFunctionName = function() {}

and from there I could call window['someFunctionName']() with ease. I hope this helps someone!

How do I get elapsed time in milliseconds in Ruby?

I think the answer is incorrectly chosen, that method gives seconds, not milliseconds.

t = Time.now.t­o_f
=> 1382471965.146

Here I suppose the floating value are the milliseconds

Modal width (increase)

Set max-width:80%; as an inline stylesheet

<div class="modal-dialog modal-lg" role="document" style="max-width: 80%;">

How to calculate the number of days between two dates?

Here's what I use. If you just subtract the dates, it won't work across the Daylight Savings Time Boundary (eg April 1 to April 30 or Oct 1 to Oct 31). This drops all the hours to make sure you get a day and eliminates any DST problem by using UTC.

var nDays = (    Date.UTC(EndDate.getFullYear(), EndDate.getMonth(), EndDate.getDate()) -
                 Date.UTC(StartDate.getFullYear(), StartDate.getMonth(), StartDate.getDate())) / 86400000;

as a function:

function DaysBetween(StartDate, EndDate) {
  // The number of milliseconds in all UTC days (no DST)
  const oneDay = 1000 * 60 * 60 * 24;

  // A day in UTC always lasts 24 hours (unlike in other time formats)
  const start = Date.UTC(EndDate.getFullYear(), EndDate.getMonth(), EndDate.getDate());
  const end = Date.UTC(StartDate.getFullYear(), StartDate.getMonth(), StartDate.getDate());

  // so it's safe to divide by 24 hours
  return (start - end) / oneDay;
}

how do you insert null values into sql server

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

How to determine whether a year is a leap year?

As a one-liner function:

def is_leap_year(year):
    """Determine whether a year is a leap year."""

    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

It's similar to the Mark's answer, but short circuits at the first test (note the parenthesis).

Alternatively, you can use the standard library's calendar.isleap, which has exactly the same implementation:

from calendar import isleap
print(isleap(1900))

NGINX - No input file specified. - php Fast/CGI

Same problem.

Cause : My root wasn't specified in open_basedir.
Fix : Adding my site root directory in :

/etc/php5/fpm/pool.d/mysite.conf<br>

by adding this directive :

php_value[open_basedir] = /my/root/site/dir:/other/directory/allowed

Clear terminal in Python

This will clear 25 new lines:

def clear():
    print(' \n' * 25)

clear()

I use eclipse with pydev. I like the newline solution better than the for num in range . The for loop throws warnings, while the print newline doesn't. If you want to specify the number of newlines in the clear statement try this variation.

def clear(j):
    print(' \n' * j)

clear(25)

Remove all child nodes from a parent?

You can use .empty(), like this:

$("#foo").empty();

From the docs:

Remove all child nodes of the set of matched elements from the DOM.