Programs & Examples On #Development mode

How to enable production mode?

You enable it by importing and executing the function (before calling bootstrap):

import {enableProdMode} from '@angular/core';

enableProdMode();
bootstrap(....);

But this error is indicator that something is wrong with your bindings, so you shouldn't just dismiss it, but try to figure out why it's happening.

Auto-loading lib files in Rails 4

This might help someone like me that finds this answer when searching for solutions to how Rails handles the class loading ... I found that I had to define a module whose name matched my filename appropriately, rather than just defining a class:

In file lib/development_mail_interceptor.rb (Yes, I'm using code from a Railscast :))

module DevelopmentMailInterceptor
  class DevelopmentMailInterceptor
    def self.delivering_email(message)
      message.subject = "intercepted for: #{message.to} #{message.subject}"
      message.to = "[email protected]"
    end
  end
end

works, but it doesn't load if I hadn't put the class inside a module.

How to find out if an installed Eclipse is 32 or 64 bit version?

Open eclipse.ini in the installation directory, and observe the line with text:

plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.0.200.v20090519 then it is 64 bit.

If it would be plugins/org.eclipse.equinox.launcher.win32.win32.x86_32_1.0.200.v20090519 then it is 32 bit.

Specify JDK for Maven to use

You could also set the JDK for Maven in a file in your home directory ~/.mavenrc:

JAVA_HOME='/Library/Java/JavaVirtualMachines/jdk-11.0.5.jdk/Contents/Home'

This environment variable will be checked by the mvn script and used when present:

  if [ -f "$HOME/.mavenrc" ] ; then
    . "$HOME/.mavenrc"
  fi

https://github.com/CodeFX-org/mvn-java-9/tree/master/mavenrc

Select a Column in SQL not in Group By

Thing I like to do is to wrap addition columns in aggregate function, like max(). It works very good when you don't expect duplicate values.

Select MAX(cpe.createdon) As MaxDate, cpe.fmgcms_cpeclaimid, MAX(cpe.fmgcms_claimid) As fmgcms_claimid 
from Filteredfmgcms_claimpaymentestimate cpe
where cpe.createdon < 'reportstartdate'
group by cpe.fmgcms_cpeclaimid

JOIN two SELECT statement results

SELECT t1.ks, t1.[# Tasks], COALESCE(t2.[# Late], 0) AS [# Late]
FROM 
    (SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks) t1
LEFT JOIN
    (SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks) t2
ON (t1.ks = t2.ks);

Ruby: How to turn a hash into HTTP parameters?

For basic, non-nested hashes, Rails/ActiveSupport has Object#to_query.

>> {:a => "a", :b => ["c", "d", "e"]}.to_query
=> "a=a&b%5B%5D=c&b%5B%5D=d&b%5B%5D=e"
>> CGI.unescape({:a => "a", :b => ["c", "d", "e"]}.to_query)
=> "a=a&b[]=c&b[]=d&b[]=e"

http://api.rubyonrails.org/classes/Object.html#method-i-to_query

OpenSSL Command to check if a server is presenting a certificate

I was debugging an SSL issue today which resulted in the same write:errno=104 error. Eventually I found out that the reason for this behaviour was that the server required SNI (servername TLS extensions) to work correctly. Supplying the -servername option to openssl made it connect successfully:

openssl s_client -connect domain.tld:443 -servername domain.tld

Hope this helps.

SHA-256 or MD5 for file integrity

Both SHA256 and MDA5 are hashing algorithms. They take your input data, in this case your file, and output a 256/128-bit number. This number is a checksum. There is no encryption taking place because an infinite number of inputs can result in the same hash value, although in reality collisions are rare.

SHA256 takes somewhat more time to calculate than MD5, according to this answer.

Offhand, I'd say that MD5 would be probably be suitable for what you need.

Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?

I'm not sure how efficient this is but you can use range() to slice in both axis

 x=np.arange(16).reshape((4,4))
 x[range(1,3), :][:,range(1,3)] 

IOS: verify if a point is inside a rect

It is so simple,you can use following method to do this kind of work:-

-(BOOL)isPoint:(CGPoint)point insideOfRect:(CGRect)rect
{
    if ( CGRectContainsPoint(rect,point))
        return  YES;// inside
    else
        return  NO;// outside
}

In your case,you can pass imagView.center as point and another imagView.frame as rect in about method.

You can also use this method in bellow UITouch Method :

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
}

How to validate an email address using a regular expression?

I found a regular expression that is compliant to RFC 2822. The preceding standard to RFC 5322. This regular expression appears to perform fairly well and will cover most cases, however with RFC 5322 becoming the standard there may be some holes that ought to be plugged.

^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$

The documentation says you shouldn't use the above regular expression, but instead favour this flavour, which is a bit more manageable.

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

I noticed this is case-sensitive, so I actually made an alteration to this landing.

^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$

Twitter Bootstrap inline input with dropdown

Search for the "datalist" tag.

<input list="texto_pronto" name="input_normal">
<datalist id="texto_pronto">
    <option value="texto A">
    <option value="texto B">
</datalist>

No 'Access-Control-Allow-Origin' header is present on the requested resource - Resteasy

After facing a similar issue, below is what I did :

  • Created a class extending javax.ws.rs.core.Application and added a Cors Filter to it.

To the CORS filter, I added corsFilter.getAllowedOrigins().add("http://localhost:4200");.

Basically, you should add the URL which you want to allow Cross-Origin Resource Sharing. Ans you can also use "*" instead of any specific URL to allow any URL.

public class RestApplication
    extends Application
{
    private Set<Object> singletons = new HashSet<Object>();

    public MessageApplication()
    {
        singletons.add(new CalculatorService()); //CalculatorService is your specific service you want to add/use.
        CorsFilter corsFilter = new CorsFilter();
        // To allow all origins for CORS add following, otherwise add only specific urls.
        // corsFilter.getAllowedOrigins().add("*");
        System.out.println("To only allow restrcited urls ");
        corsFilter.getAllowedOrigins().add("http://localhost:4200");
        singletons = new LinkedHashSet<Object>();
        singletons.add(corsFilter);
    }

    @Override
    public Set<Object> getSingletons()
    {
        return singletons;
    }
}
  • And here is my web.xml:
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>Restful Web Application</display-name>

    <!-- Auto scan rest service -->
    <context-param>
        <param-name>resteasy.scan</param-name>
        <param-value>true</param-value>
    </context-param>

    <context-param>
        <param-name>resteasy.servlet.mapping.prefix</param-name>
        <param-value>/rest</param-value>
    </context-param>

    <listener>
        <listener-class>
            org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
        </listener-class>
    </listener>

    <servlet>
        <servlet-name>resteasy-servlet</servlet-name>
        <servlet-class>
            org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
        </servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.app.RestApplication</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>resteasy-servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>

The most important code which I was missing when I was getting this issue was, I was not adding my class extending javax.ws.rs.Application i.e RestApplication to the init-param of <servlet-name>resteasy-servlet</servlet-name>

   <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>com.app.RestApplication</param-value>
    </init-param>

And therefore my Filter was not able to execute and thus the application was not allowing CORS from the URL specified.

Python Pandas Error tokenizing data

I believe the solutions,

,engine='python'
, error_bad_lines = False

will be good if it is dummy columns and you want to delete it. In my case, the second row really had more columns and I wanted those columns to be integrated and to have the number of columns = MAX(columns).

Please refer to the solution below that I could not read anywhere:

try:
    df_data = pd.read_csv(PATH, header = bl_header, sep = str_sep)
except pd.errors.ParserError as err:
    str_find = 'saw '
    int_position = int(str(err).find(str_find)) + len(str_find)
    str_nbCol = str(err)[int_position:]
    l_col = range(int(str_nbCol))
    df_data = pd.read_csv(PATH, header = bl_header, sep = str_sep, names = l_col)

combining two string variables

you need to take out the quotes:

soda = a + b

(You want to refer to the variables a and b, not the strings "a" and "b")

how to determine size of tablespace oracle 11g

One of the way is Using below sql queries

--Size of All Table Space

--1. Used Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "USED SPACE(IN GB)" FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME
--2. Free Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "FREE SPACE(IN GB)" FROM   USER_FREE_SPACE GROUP BY TABLESPACE_NAME

--3. Both Free & Used
SELECT USED.TABLESPACE_NAME, USED.USED_BYTES AS "USED SPACE(IN GB)",  FREE.FREE_BYTES AS "FREE SPACE(IN GB)"
FROM
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS USED_BYTES FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME) USED
INNER JOIN
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS FREE_BYTES FROM  USER_FREE_SPACE GROUP BY TABLESPACE_NAME) FREE
ON (USED.TABLESPACE_NAME = FREE.TABLESPACE_NAME);

Set default value of javascript object attributes

This sure sounds like the typical use of protoype-based objects:

// define a new type of object
var foo = function() {};  

// define a default attribute and value that all objects of this type will have
foo.prototype.attribute1 = "defaultValue1";  

// create a new object of my type
var emptyObj = new foo();
console.log(emptyObj.attribute1);       // outputs defaultValue1

Inserting Image Into BLOB Oracle 10g

You should do something like this:

1) create directory object what would point to server-side accessible folder

CREATE DIRECTORY image_files AS '/data/images'
/

2) Place your file into OS folder directory object points to

3) Give required access privileges to Oracle schema what will load data from file into table:

GRANT READ ON DIRECTORY image_files TO scott
/

4) Use BFILENAME, EMPTY_BLOB functions and DBMS_LOB package (example NOT tested - be care) like in below:

DECLARE
  l_blob BLOB; 
  v_src_loc  BFILE := BFILENAME('IMAGE_FILES', 'myimage.png');
  v_amount   INTEGER;
BEGIN
  INSERT INTO esignatures  
  VALUES (100, 'BOB', empty_blob()) RETURN iblob INTO l_blob; 
  DBMS_LOB.OPEN(v_src_loc, DBMS_LOB.LOB_READONLY);
  v_amount := DBMS_LOB.GETLENGTH(v_src_loc);
  DBMS_LOB.LOADFROMFILE(l_blob, v_src_loc, v_amount);
  DBMS_LOB.CLOSE(v_src_loc);
  COMMIT;
END;
/

After this you get the content of your file in BLOB column and can get it back using Java for example.

edit: One letter left missing: it should be LOADFROMFILE.

Difference between setUp() and setUpBeforeClass()

Think of "BeforeClass" as a static initializer for your test case - use it for initializing static data - things that do not change across your test cases. You definitely want to be careful about static resources that are not thread safe.

Finally, use the "AfterClass" annotated method to clean up any setup you did in the "BeforeClass" annotated method (unless their self destruction is good enough).

"Before" & "After" are for unit test specific initialization. I typically use these methods to initialize / re-initialize the mocks of my dependencies. Obviously, this initialization is not specific to a unit test, but general to all unit tests.

Most efficient way to concatenate strings?

From Chinh Do - StringBuilder is not always faster:

Rules of Thumb

  • When concatenating three dynamic string values or less, use traditional string concatenation.

  • When concatenating more than three dynamic string values, use StringBuilder.

  • When building a big string from several string literals, use either the @ string literal or the inline + operator.

Most of the time StringBuilder is your best bet, but there are cases as shown in that post that you should at least think about each situation.

HashMap - getting First Key value

Improving whoami's answer. Since findFirst() returns an Optional, it is a good practice to check if there is a value.

 var optional = pair.keySet().stream().findFirst();

 if (!optional.isPresent()) {
    return;
 }

 var key = optional.get();

Also, some commented that finding first key of a HashSet is unreliable. But sometimes we have HashMap pairs; i.e. in each map we have one key and one value. In such cases finding the first key of such a pair quickly is convenient.

Getting the base url of the website and globally passing it to twig in Symfony 2

Base url is defined inside Symfony\Component\Routing\RequestContext.

It can be fetched from controller like this:

$this->container->get('router')->getContext()->getBaseUrl()

Active Directory LDAP Query by sAMAccountName and Domain

I have written a C# class incorporating

  • the algorithm from Dscoduc,
  • the query optimization from sorin,
  • a cache for the domain to server mapping, and
  • a method to search for an account name in DOMAIN\sAMAccountName format.

However, it is not Site-aware.

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

public static class ADUserFinder
{
    private static Dictionary<string, string> _dictDomain2LDAPPath;

    private static Dictionary<string, string> DictDomain2LDAPPath
    {
        get
        {
            if (null == _dictDomain2LDAPPath)
            {
                string configContainer;
                using (DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE"))
                    configContainer = rootDSE.Properties["ConfigurationNamingContext"].Value.ToString();

                using (DirectoryEntry partitionsContainer = new DirectoryEntry("LDAP://CN=Partitions," + configContainer))
                using (DirectorySearcher dsPartitions = new DirectorySearcher(
                        partitionsContainer,
                        "(&(objectcategory=crossRef)(systemFlags=3))",
                        new string[] { "name", "nCName", "dnsRoot" },
                        SearchScope.OneLevel
                    ))
                using (SearchResultCollection srcPartitions = dsPartitions.FindAll())
                {
                    _dictDomain2LDAPPath = srcPartitions.OfType<SearchResult>()
                        .ToDictionary(
                        result => result.Properties["name"][0].ToString(), // the DOMAIN part
                        result => $"LDAP://{result.Properties["dnsRoot"][0]}/{result.Properties["nCName"][0]}"
                    );
                }
            }

            return _dictDomain2LDAPPath;
        }
    }

    private static DirectoryEntry FindRootEntry(string domainPart)
    {
        if (DictDomain2LDAPPath.ContainsKey(domainPart))
            return new DirectoryEntry(DictDomain2LDAPPath[domainPart]);
        else
            throw new ArgumentException($"Domain \"{domainPart}\" is unknown in Active Directory");
    }

    public static DirectoryEntry FindUser(string domain, string sAMAccountName)
    {
        using (DirectoryEntry rootEntryForDomain = FindRootEntry(domain))
        using (DirectorySearcher dsUser = new DirectorySearcher(
                rootEntryForDomain,
                $"(&(sAMAccountType=805306368)(sAMAccountName={EscapeLdapSearchFilter(sAMAccountName)}))" // magic number 805306368 means "user objects", it's more efficient than (objectClass=user)
            ))
            return dsUser.FindOne().GetDirectoryEntry();
    }

    public static DirectoryEntry FindUser(string domainBackslashSAMAccountName)
    {
        string[] domainAndsAMAccountName = domainBackslashSAMAccountName.Split('\\');
        if (domainAndsAMAccountName.Length != 2)
            throw new ArgumentException($"User name \"{domainBackslashSAMAccountName}\" is not in correct format DOMAIN\\SAMACCOUNTNAME", "DomainBackslashSAMAccountName");

        string domain = domainAndsAMAccountName[0];
        string sAMAccountName = domainAndsAMAccountName[1];

        return FindUser(domain, sAMAccountName);
    }

    /// <summary>
    /// Escapes the LDAP search filter to prevent LDAP injection attacks.
    /// Copied from https://stackoverflow.com/questions/649149/how-to-escape-a-string-in-c-for-use-in-an-ldap-query
    /// </summary>
    /// <param name="searchFilter">The search filter.</param>
    /// <see cref="https://blogs.oracle.com/shankar/entry/what_is_ldap_injection" />
    /// <see cref="http://msdn.microsoft.com/en-us/library/aa746475.aspx" />
    /// <returns>The escaped search filter.</returns>
    private static string EscapeLdapSearchFilter(string searchFilter)
    {
        StringBuilder escape = new StringBuilder();
        for (int i = 0; i < searchFilter.Length; ++i)
        {
            char current = searchFilter[i];
            switch (current)
            {
                case '\\':
                    escape.Append(@"\5c");
                    break;
                case '*':
                    escape.Append(@"\2a");
                    break;
                case '(':
                    escape.Append(@"\28");
                    break;
                case ')':
                    escape.Append(@"\29");
                    break;
                case '\u0000':
                    escape.Append(@"\00");
                    break;
                case '/':
                    escape.Append(@"\2f");
                    break;
                default:
                    escape.Append(current);
                    break;
            }
        }

        return escape.ToString();
    }
}

Python decorators in classes

I have a Implementation of Decorators that Might Help

    import functools
    import datetime


    class Decorator(object):

        def __init__(self):
            pass


        def execution_time(func):

            @functools.wraps(func)
            def wrap(self, *args, **kwargs):

                """ Wrapper Function """

                start = datetime.datetime.now()
                Tem = func(self, *args, **kwargs)
                end = datetime.datetime.now()
                print("Exection Time:{}".format(end-start))
                return Tem

            return wrap


    class Test(Decorator):

        def __init__(self):
            self._MethodName = Test.funca.__name__

        @Decorator.execution_time
        def funca(self):
            print("Running Function : {}".format(self._MethodName))
            return True


    if __name__ == "__main__":
        obj = Test()
        data = obj.funca()
        print(data)

Float a DIV on top of another DIV

What about:

.close-image{
    display:block;
    cursor:pointer;
    z-index:3;
    position:absolute;
    top:0;
    right:0;
}

Is that the desired result?

In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors?

Try doing a rebuild. I've found that the red x's don't always disappear until a rebuild is done.

UTF-8 problems while reading CSV file with fgetcsv

Try this:

<?php
$handle = fopen ("specialchars.csv","r");
echo '<table border="1"><tr><td>First name</td><td>Last name</td></tr><tr>';
while ($data = fgetcsv ($handle, 1000, ";")) {
        $data = array_map("utf8_encode", $data); //added
        $num = count ($data);
        for ($c=0; $c < $num; $c++) {
            // output data
            echo "<td>$data[$c]</td>";
        }
        echo "</tr><tr>";
}
?>

"string could not resolved" error in Eclipse for C++ (Eclipse can't resolve standard library)

I had the same problem. Adding include path does work for all except std::string.

I noticed in the mingw-Toolchain many system header files *.tcc

I added filetype *.tcc as "C++ Header File" in Preferences > C/C++/ File Types. Now std::string can be resolved from the internal index and Code Analyzer. Perhaps this is added to Eclipse CDT by default in feature.

I hope this helps to someone...

PS: I'm using Eclipse Mars, mingw gcc 4.8.1, Own Makefile, no Eclipse Makefilebuilder.

How do you POST to a page using the PHP header() function?

The answer to this is very needed today because not everyone wants to use cURL to consume web services. Also PHP does allow for this using the following code

function get_info()
{
    $post_data = array(
        'test' => 'foobar',
        'okay' => 'yes',
        'number' => 2
    );

    // Send a request to example.com
    $result = $this->post_request('http://www.example.com/', $post_data);

    if ($result['status'] == 'ok'){

        // Print headers
        echo $result['header'];

        echo '<hr />';

        // print the result of the whole request:
        echo $result['content'];

    }
    else {
        echo 'A error occured: ' . $result['error'];
    }

}

function post_request($url, $data, $referer='') {

    // Convert the data array into URL Parameters like a=b&foo=bar etc.
    $data = http_build_query($data);

    // parse the given URL
    $url = parse_url($url);

    if ($url['scheme'] != 'http') {
        die('Error: Only HTTP request are supported !');
    }

    // extract host and path:
    $host = $url['host'];
    $path = $url['path'];

    // open a socket connection on port 80 - timeout: 30 sec
    $fp = fsockopen($host, 80, $errno, $errstr, 30);

    if ($fp){

        // send the request headers:
        fputs($fp, "POST $path HTTP/1.1\r\n");
        fputs($fp, "Host: $host\r\n");

        if ($referer != '')
            fputs($fp, "Referer: $referer\r\n");

        fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
        fputs($fp, "Content-length: ". strlen($data) ."\r\n");
        fputs($fp, "Connection: close\r\n\r\n");
        fputs($fp, $data);

        $result = '';
        while(!feof($fp)) {
            // receive the results of the request
            $result .= fgets($fp, 128);
        }
    }
    else {
        return array(
            'status' => 'err',
            'error' => "$errstr ($errno)"
        );
    }

    // close the socket connection:
    fclose($fp);

    // split the result header from the content
    $result = explode("\r\n\r\n", $result, 2);

    $header = isset($result[0]) ? $result[0] : '';
    $content = isset($result[1]) ? $result[1] : '';

    // return as structured array:
    return array(
        'status' => 'ok',
        'header' => $header,
        'content' => $content);

}

Read file from resources folder in Spring Boot

Below is my working code.

List<sampleObject> list = new ArrayList<>();
File file = new ClassPathResource("json/test.json").getFile();
ObjectMapper objectMapper = new ObjectMapper();
sampleObject = Arrays.asList(objectMapper.readValue(file, sampleObject[].class));

Hope it helps one!

Create empty data frame with column names by assigning a string vector?

How about:

df <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("name", "age", "gender")
colnames(df) <- x

To do all these operations in one-liner:

setNames(data.frame(matrix(ncol = 3, nrow = 0)), c("name", "age", "gender"))

#[1] name   age    gender
#<0 rows> (or 0-length row.names)

Or

data.frame(matrix(ncol=3,nrow=0, dimnames=list(NULL, c("name", "age", "gender"))))

Is there functionality to generate a random character in Java?

   Random randomGenerator = new Random();

   int i = randomGenerator.nextInt(256);
   System.out.println((char)i);

Should take care of what you want, assuming you consider '0,'1','2'.. as characters.

Reloading the page gives wrong GET request with AngularJS HTML5 mode

From the angular docs

Server side
Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)

The reason for this is that when you first visit the page (/about), e.g. after a refresh, the browser has no way of knowing that this isn't a real URL, so it goes ahead and loads it. However if you have loaded up the root page first, and all the javascript code, then when you navigate to /about Angular can get in there before the browser tries to hit the server and handle it accordingly

How to sort an array of objects with jquery or javascript

var array = [[1, "grape", 42], [2, "fruit", 9]];

array.sort(function(a, b)
{
    // a and b will here be two objects from the array
    // thus a[1] and b[1] will equal the names

    // if they are equal, return 0 (no sorting)
    if (a[1] == b[1]) { return 0; }
    if (a[1] > b[1])
    {
        // if a should come after b, return 1
        return 1;
    }
    else
    {
        // if b should come after a, return -1
        return -1;
    }
});

The sort function takes an additional argument, a function that takes two arguments. This function should return -1, 0 or 1 depending on which of the two arguments should come first in the sorting. More info.

I also fixed a syntax error in your multidimensional array.

Centering controls within a form in .NET (Winforms)?

You could achieve this with the use of anchors. Or more precisely the non use of them.

Controls are anchored by default to the top left of the form which means when the form size will be changed, their distance from the top left side of the form will remain constant. If you change the control anchor to bottom left, then the control will keep the same distance from the bottom and left sides of the form when the form if resized.

Turning off the anchor in a direction will keep the control centered in that direction when resizing.

NOTE: Turning off anchoring via the properties window in VS2015 may require entering None, None (instead of default Top,Left)

How to send a correct authorization header for basic authentication

You can include the user and password as part of the URL:

http://user:[email protected]/index.html

see this URL, for more

HTTP Basic Authentication credentials passed in URL and encryption

of course, you'll need the username password, it's not 'Basic hashstring.

hope this helps...

Go to Matching Brace in Visual Studio?

On a German keyboard it's ctrl+shift+^.

Changing navigation title programmatically

If you have a NavigationController embedded inside of a TabBarController see below:

super.tabBarController?.title = "foobar"

enter image description here

You can debug issues like this with debugger scripts. Try Chisel's pvc command to print every visible / hidden view on the hierarchy.

Increase distance between text and title on the y-axis

Based on this forum post: https://groups.google.com/forum/#!topic/ggplot2/mK9DR3dKIBU

Sounds like the easiest thing to do is to add a line break (\n) before your x axis, and after your y axis labels. Seems a lot easier (although dumber) than the solutions posted above.

ggplot(mpg, aes(cty, hwy)) + 
    geom_point() + 
    xlab("\nYour_x_Label") + ylab("Your_y_Label\n")

Hope that helps!

java.net.URLEncoder.encode(String) is deprecated, what should I use instead?

Use the other encode method in URLEncoder:

URLEncoder.encode(String, String)

The first parameter is the text to encode; the second is the name of the character encoding to use (e.g., UTF-8). For example:

System.out.println(
  URLEncoder.encode(
    "urlParameterString",
    java.nio.charset.StandardCharsets.UTF_8.toString()
  )
);

Context.startForegroundService() did not then call Service.startForeground()

Please don't call any StartForgroundServices inside onCreate() method, you have to call StartForground services in onStartCommand() after make the worker thread otherwise you will get ANR always , so please don't write complex login in main thread of onStartCommand();

public class Services extends Service {

    private static final String ANDROID_CHANNEL_ID = "com.xxxx.Location.Channel";
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Notification.Builder builder = new Notification.Builder(this, ANDROID_CHANNEL_ID)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText("SmartTracker Running")
                    .setAutoCancel(true);
            Notification notification = builder.build();
            startForeground(0, notification);
            Log.e("home_button","home button");
        } else {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText("SmartTracker is Running...")
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    .setAutoCancel(true);
            Notification notification = builder.build();
            startForeground(0, notification);
            Log.e("home_button_value","home_button_value");

        }
        return super.onStartCommand(intent, flags, startId);

    }
}

EDIT: Caution! startForeground function can't take 0 as first argument, it will raise an exception! this example contains wrong function call, change 0 to your own const which couldnt be 0 or be greater than Max(Int32)

Does Google Chrome work with Selenium IDE (as Firefox does)?

No, Google Chrome does not work with Selenium IDE. As Selenium IDE is a Firefox plugin it works only with FF.

According to your last portion of question: Or is there any alternative tool which can work with Chrome? The possible answer is as follows:

You can use Sahi with Chrome. Sahi Test Automation tool supports Chrome, Firefox and IE. You can visit for details:

http://sahi.co.in/

High-precision clock in Python

The standard time.time() function provides sub-second precision, though that precision varies by platform. For Linux and Mac precision is +- 1 microsecond or 0.001 milliseconds. Python on Windows uses +- 16 milliseconds precision due to clock implementation problems due to process interrupts. The timeit module can provide higher resolution if you're measuring execution time.

>>> import time
>>> time.time()        #return seconds from epoch
1261367718.971009      

Python 3.7 introduces new functions to the time module that provide higher resolution:

>>> import time
>>> time.time_ns()
1530228533161016309
>>> time.time_ns() / (10 ** 9) # convert to floating-point seconds
1530228544.0792289

How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

Do you have access to the command prompt ?

Method 1 : Command Prompt

The specifics of the Java installed on the system can be determined by executing the following command java -version

Method 2 : Folder Structure

In case you do not have access to command prompt then determining the folder where Java.

32 Bit : C:\Program Files (x86)\Java\jdk1.6.0_30

64 Bit : C:\Program Files\Java\jdk1.6.0_25

However during the installation it is possible that the user might change the installation folder.

Method 3 : Registry

You can also see the version installed in registry editor.

  1. Go to registry editor

  2. Edit -> Find

  3. Search for Java. You will get the registry entries for Java.

  4. In the entry with name : DisplayName & DisplayVersion, the installed java version is displayed

How do I read / convert an InputStream into a String in Java?

Raghu K Nair Was the only one using a scanner. The code I use is a little different:

String convertToString(InputStream in){
    Scanner scanner = new Scanner(in)
    scanner.useDelimiter("\\A");

    boolean hasInput = scanner.hasNext();
    if (hasInput) {
        return scanner.next();
    } else {
        return null;
    }

}

About Delimiters: How do I use a delimiter in Java Scanner?

How do I merge dictionaries together in Python?

In Python2,

d1={'a':1,'b':2}
d2={'a':10,'c':3}

d1 overrides d2:

dict(d2,**d1)
# {'a': 1, 'c': 3, 'b': 2}

d2 overrides d1:

dict(d1,**d2)
# {'a': 10, 'c': 3, 'b': 2}

This behavior is not just a fluke of implementation; it is guaranteed in the documentation:

If a key is specified both in the positional argument and as a keyword argument, the value associated with the keyword is retained in the dictionary.

Failed to execute 'atob' on 'Window'

here's an updated fiddle where the user's input is saved in local storage automatically. each time the fiddle is re-run or the page is refreshed the previous state is restored. this way you do not need to prompt users to save, it just saves on it's own.

http://jsfiddle.net/tZPg4/9397/

stack overflow requires I include some code with a jsFiddle link so please ignore snippet:

localStorage.setItem(...)

Best way to "push" into C# array

I don't understand what you are doing with the for loop. You are merely iterating over every element and assigning to the first element you encounter. If you're trying to push to a list go with the above answer that states there is no such thing as pushing to a list. That really is getting the data structures mixed up. Javascript might not be setting the best example, because a javascript list is really also a queue and a stack at the same time.

Assign pandas dataframe column dtypes

Since 0.17, you have to use the explicit conversions:

pd.to_datetime, pd.to_timedelta and pd.to_numeric

(As mentioned below, no more "magic", convert_objects has been deprecated in 0.17)

df = pd.DataFrame({'x': {0: 'a', 1: 'b'}, 'y': {0: '1', 1: '2'}, 'z': {0: '2018-05-01', 1: '2018-05-02'}})

df.dtypes

x    object
y    object
z    object
dtype: object

df

   x  y           z
0  a  1  2018-05-01
1  b  2  2018-05-02

You can apply these to each column you want to convert:

df["y"] = pd.to_numeric(df["y"])
df["z"] = pd.to_datetime(df["z"])    
df

   x  y          z
0  a  1 2018-05-01
1  b  2 2018-05-02

df.dtypes

x            object
y             int64
z    datetime64[ns]
dtype: object

and confirm the dtype is updated.


OLD/DEPRECATED ANSWER for pandas 0.12 - 0.16: You can use convert_objects to infer better dtypes:

In [21]: df
Out[21]: 
   x  y
0  a  1
1  b  2

In [22]: df.dtypes
Out[22]: 
x    object
y    object
dtype: object

In [23]: df.convert_objects(convert_numeric=True)
Out[23]: 
   x  y
0  a  1
1  b  2

In [24]: df.convert_objects(convert_numeric=True).dtypes
Out[24]: 
x    object
y     int64
dtype: object

Magic! (Sad to see it deprecated.)

How to work on UAC when installing XAMPP

You can press OK and install xampp to C:\xampp and not into program files

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

This function worked perfectly for me. It detects Edge as well.

Originally from this Codepen:

https://codepen.io/gapcode/pen/vEJNZN

/**
 * detect IE
 * returns version of IE or false, if browser is not Internet Explorer
 */
function detectIE() {
  var ua = window.navigator.userAgent;

  // Test values; Uncomment to check result …

  // IE 10
  // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';

  // IE 11
  // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';

  // Edge 12 (Spartan)
  // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';

  // Edge 13
  // ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586';

  var msie = ua.indexOf('MSIE ');
  if (msie > 0) {
    // IE 10 or older => return version number
    return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  }

  var trident = ua.indexOf('Trident/');
  if (trident > 0) {
    // IE 11 => return version number
    var rv = ua.indexOf('rv:');
    return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  }

  var edge = ua.indexOf('Edge/');
  if (edge > 0) {
    // Edge (IE 12+) => return version number
    return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  }

  // other browser
  return false;
}

Then you can use if (detectIE()) { /* do IE stuff */ } in your code.

Select2 doesn't work when embedded in a bootstrap modal

i had this problem before , i am using yii2 and i solved it this way

$.fn.modal.Constructor.prototype.enforceFocus = $.noop;

How do I prevent CSS inheritance?

You could use something like jQuery to "disable" this behaviour, though I hardly think it's a good solution as you get display logic in css & javascript. Still, depending upon your requirements you might find jQuery's css utils make life easier for you than trying hacky css, especially if you're trying to make it work for IE6

Format a Go string without printing?

1. Simple strings

For "simple" strings (typically what fits into a line) the simplest solution is using fmt.Sprintf() and friends (fmt.Sprint(), fmt.Sprintln()). These are analogous to the functions without the starter S letter, but these Sxxx() variants return the result as a string instead of printing them to the standard output.

For example:

s := fmt.Sprintf("Hi, my name is %s and I'm %d years old.", "Bob", 23)

The variable s will be initialized with the value:

Hi, my name is Bob and I'm 23 years old.

Tip: If you just want to concatenate values of different types, you may not automatically need to use Sprintf() (which requires a format string) as Sprint() does exactly this. See this example:

i := 23
s := fmt.Sprint("[age:", i, "]") // s will be "[age:23]"

For concatenating only strings, you may also use strings.Join() where you can specify a custom separator string (to be placed between the strings to join).

Try these on the Go Playground.

2. Complex strings (documents)

If the string you're trying to create is more complex (e.g. a multi-line email message), fmt.Sprintf() becomes less readable and less efficient (especially if you have to do this many times).

For this the standard library provides the packages text/template and html/template. These packages implement data-driven templates for generating textual output. html/template is for generating HTML output safe against code injection. It provides the same interface as package text/template and should be used instead of text/template whenever the output is HTML.

Using the template packages basically requires you to provide a static template in the form of a string value (which may be originating from a file in which case you only provide the file name) which may contain static text, and actions which are processed and executed when the engine processes the template and generates the output.

You may provide parameters which are included/substituted in the static template and which may control the output generation process. Typical form of such parameters are structs and map values which may be nested.

Example:

For example let's say you want to generate email messages that look like this:

Hi [name]!

Your account is ready, your user name is: [user-name]

You have the following roles assigned:
[role#1], [role#2], ... [role#n]

To generate email message bodies like this, you could use the following static template:

const emailTmpl = `Hi {{.Name}}!

Your account is ready, your user name is: {{.UserName}}

You have the following roles assigned:
{{range $i, $r := .Roles}}{{if $i}}, {{end}}{{.}}{{end}}
`

And provide data like this for executing it:

data := map[string]interface{}{
    "Name":     "Bob",
    "UserName": "bob92",
    "Roles":    []string{"dbteam", "uiteam", "tester"},
}

Normally output of templates are written to an io.Writer, so if you want the result as a string, create and write to a bytes.Buffer (which implements io.Writer). Executing the template and getting the result as string:

t := template.Must(template.New("email").Parse(emailTmpl))
buf := &bytes.Buffer{}
if err := t.Execute(buf, data); err != nil {
    panic(err)
}
s := buf.String()

This will result in the expected output:

Hi Bob!

Your account is ready, your user name is: bob92

You have the following roles assigned:
dbteam, uiteam, tester

Try it on the Go Playground.

Also note that since Go 1.10, a newer, faster, more specialized alternative is available to bytes.Buffer which is: strings.Builder. Usage is very similar:

builder := &strings.Builder{}
if err := t.Execute(builder, data); err != nil {
    panic(err)
}
s := builder.String()

Try this one on the Go Playground.

Note: you may also display the result of a template execution if you provide os.Stdout as the target (which also implements io.Writer):

t := template.Must(template.New("email").Parse(emailTmpl))
if err := t.Execute(os.Stdout, data); err != nil {
    panic(err)
}

This will write the result directly to os.Stdout. Try this on the Go Playground.

Installing Apple's Network Link Conditioner Tool

For Xcode 8 you gotta download a package named Additional Tools for Xcode 8

For other versions (8.1, 8.2) get the package here

Double click and open the dmg and go to Hardware directory. Double click on Network Link Conditioner.prefPane.

enter image description here

Click on install

enter image description here

Now Network Link Conditioner will be available in System Preferences.

For versions older than Xcode 8, the package to be downloaded is called Hardware IO Tools for Xcode. Get it from this page

How to reset the state of a Redux store?

for me what worked the best is to set the initialState instead of state:

  const reducer = createReducer(initialState,
  on(proofActions.cleanAdditionalInsuredState, (state, action) => ({
    ...initialState
  })),

Get a particular cell value from HTML table using JavaScript

You can also use the DOM way to obtain the cell value: Cells[0].firstChild.data

Read more on that in my post at http://js-code.blogspot.com/2009/03/how-to-change-html-table-cell-value.html

ng if with angular for string contains

All javascript methods are applicable with angularjs because angularjs itself is a javascript framework so you can use indexOf() inside angular directives

<li ng-repeat="select in Items">   
         <foo ng-repeat="newin select.values">
<span ng-if="newin.label.indexOf(x) !== -1">{{newin.label}}</span></foo>
</li>
//where x is your character to be found

How to highlight a selected row in ngRepeat?

Each row has an ID. All you have to do is to send this ID to the function setSelected(), store it (in $scope.idSelectedVote for instance), and then check for each row if the selected ID is the same as the current one. Here is a solution (see the documentation for ngClass, if needed):

$scope.idSelectedVote = null;
$scope.setSelected = function (idSelectedVote) {
   $scope.idSelectedVote = idSelectedVote;
};
<ul ng-repeat="vote in votes" ng-click="setSelected(vote.id)" ng-class="{selected: vote.id === idSelectedVote}">
    ...
</ul>

Plunker

In SSRS, why do I get the error "item with same key has already been added" , when I'm making a new report?

If you are using SPs and if the sps have multiple Select statements (within if conditions) all those selects needs to be handled with unique field names.

How to add shortcut keys for java code in eclipse

Type syso and ctrl + space for System.out.println()

How to select a div element in the code-behind page?

You have make div as server control using following code,

<div class="tab-pane active" id="portlet_tab1" runat="server">

then this div will be accessible in code behind.

std::string length() and size() member functions

Ruby's just the same, btw, offering both #length and #size as synonyms for the number of items in arrays and hashes (C++ only does it for strings).

Minimalists and people who believe "there ought to be one, and ideally only one, obvious way to do it" (as the Zen of Python recites) will, I guess, mostly agree with your doubts, @Naveen, while fans of Perl's "There's more than one way to do it" (or SQL's syntax with a bazillion optional "noise words" giving umpteen identically equivalent syntactic forms to express one concept) will no doubt be complaining that Ruby, and especially C++, just don't go far enough in offering such synonymical redundancy;-).

How do I 'overwrite', rather than 'merge', a branch on another branch in Git?

WARNING: This deletes all commits on the email branch. It's like deleting the email branch and creating it anew at the head of the staging branch.

The easiest way to do it:

//the branch you want to overwrite
git checkout email 

//reset to the new branch
git reset --hard origin/staging

// push to remote
git push -f

Now the email branch and the staging are the same.

Check if string ends with certain pattern

This is really simple, the String object has an endsWith method.

From your question it seems like you want either /, , or . as the delimiter set.

So:

String str = "This.is.a.great.place.to.work.";

if (str.endsWith(".work.") || str.endsWith("/work/") || str.endsWith(",work,"))
     // ... 

You can also do this with the matches method and a fairly simple regex:

if (str.matches(".*([.,/])work\\1$"))

Using the character class [.,/] specifying either a period, a slash, or a comma, and a backreference, \1 that matches whichever of the alternates were found, if any.

How to make a simple image upload using Javascript/HTML

<li class="list-group-item active"><h5>Feaured Image</h5></li>
            <li class="list-group-item">
                <div class="input-group mb-3">
                    <div class="custom-file ">
                        <input type="file"  class="custom-file-input" name="thumbnail" id="thumbnail">
                        <label class="custom-file-label" for="thumbnail">Choose file</label>
                    </div>
                </div>
                <div class="img-thumbnail  text-center">
                    <img src="@if(isset($product)) {{asset('storage/'.$product->thumbnail)}} @else {{asset('images/no-thumbnail.jpeg')}} @endif" id="imgthumbnail" class="img-fluid" alt="">
                </div>
            </li>
<script>
$(function(){
$('#thumbnail').on('change', function() {
    var file = $(this).get(0).files;
    var reader = new FileReader();
    reader.readAsDataURL(file[0]);
    reader.addEventListener("load", function(e) {
    var image = e.target.result;
$("#imgthumbnail").attr('src', image);
});
});
}
</script>

PHP filesize MB/KB conversion

I think this is a better approach. Simple and straight forward.

public function sizeFilter( $bytes )
{
    $label = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB' );
    for( $i = 0; $bytes >= 1024 && $i < ( count( $label ) -1 ); $bytes /= 1024, $i++ );
    return( round( $bytes, 2 ) . " " . $label[$i] );
}

Pip error: Microsoft Visual C++ 14.0 is required

I landed on this question after searching for "Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools". I got this error in Azure DevOps when trying to run pip install to build my own Python package from a source distribution that had C++ extensions. In the end all I had to do was upgrade setuptools before calling pip install:

pip install --upgrade setuptools

So the advice here about updating setuptools when installing from source archives is right after all:). That advice is given here too.

Scrollview can host only one direct child

Wrap all the children inside of another LinearLayout with wrap_content for both the width and the height as well as the vertical orientation.

How to hide image broken Icon using only CSS/HTML?

If you need to still have the image container visible due to it being filled in later on and don't want to bother with showing and hiding it you can stick a 1x1 transparent image inside of the src:

<img id="active-image" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"/>

I used this for this exact purpose. I had an image container that was going to have an image loaded into it via Ajax. Because the image was large and took a bit to load, it required setting a background-image in CSS of a Gif loading bar.

However, because the src of the was empty, the broken image icon still appeared in browsers that use it.

Setting the transparent 1x1 Gif fixes this problem simply and effectively with no code additions through CSS or JavaScript.

How do I show/hide a UIBarButtonItem?

Here's a simple approach:

hide:  barbuttonItem.width = 0.01;
show:  barbuttonItem.width = 0; //(0 defaults to normal button width, which is the width of the text)

I just ran it on my retina iPad, and .01 is small enough for it to not show up.

explode string in jquery

The split function separates each part of text with the separator you provide, and you provided "|". So the result would be an array containing "Shimla", "1" and "http://vinspro.org/travel/ind/". You could manipulate that to get the third one, "http://vinspro.org/travel/ind/", and here's an example:

var str="Shimla|1|http://vinspro.org/travel/ind/";
var n = str.split('|');
alert(n[2]); 

As mentioned in other answers, this code would differ depending on if it was a string ($(str).split('|');), a textbox input ($(str).val().split('|');), or a DOM element ($(str).text().split('|');).

You could also just use plain JavaScript to get all the stuff after 9 characters, which would be "http://vinspro.org/travel/ind/". Here's an example:

var str="Shimla|1|http://vinspro.org/travel/ind/";
var n=str.substr(9);
alert(n);

How organize uploaded media in WP?

Currently, media organisation is possible.

The "problem" with the media library in wordpress is always interesting. Check the following plugin to solve this: WordPress Real Media Library. WP RML creates a virtual folder structure based on an own taxonomy.

Drag & Drop your files

It allows you to organize your wordpress media library in a nice way with folders. It is easy to use, just drag&drop your files and move it to a specific folder. Filter when inserting media or create a gallery from a folder.

Turn your WordPress media library to the next level with folders / categories. Get organized with thousands of images.

RML (Real Media Library) is one of the most wanted media wordpress plugins. It is easy to use and it allows you to organize your thousands of images in folders. It is similar to wordpress categories like in the posts.

Use your mouse (or touch) to drag and drop your files. Create, rename, delete or reorder your folders If you want to select a image from the “Select a image”-dialog (e. g. featured image) you can filter when inserting media. Just install this plugin and it works fine with all your image and media files. It also supports multisite.

If you buy, you get: Forever FREE updates and high quality and fast support.

From the product description i can quote. If you want to try the plugin, there is also a demo on the plugin page.

Update #1 (2017-01-27): Manage your uploads physically

A long time ago I started to open this thread and now there is a usable extension plugin for Real Media Library which allows you to physically manage your uploads folder.

enter image description here

Check out this plugin: https://wordpress.org/plugins/physical-custom-upload-folder/

Do you know the wp-content/uploads folder? There, the files are stored in year/month based folders. This can be a very complicated and mass process, especially when you are working with a FTP client like FileZilla.

Moving already uploaded files: This plugin does not allow to move the files physically when you move a file in the Real Media Library because WordPress uses the URL's in different places. It is very hard to maintain such a process. So this only works for new uploads.

Physical organisation on server?

(Please read on if you are developer) I as developer thought about a solution about this. Does it make sense to organize the uploads on server, too? Yes, i think. Many people ask to organize it physically. I think also that the process of moving files on server and updating the image references is very hard to develop. There are many plugins out now, which are saving the URLs in their own-created database-tables.

Please check this thread where i explained the problem: https://wordpress.stackexchange.com/questions/226675/physical-organization-of-wordpress-media-library-real-media-library-plugin

How to get first character of string?

var str="stack overflow";

firstChar  = str.charAt(0);

secondChar = str.charAt(1);

Tested in IE6+, FF, Chrome, safari.

How do I raise the same Exception with a custom message in Python?

This only works with Python 3. You can modify the exception's original arguments and add your own arguments.

An exception remembers the args it was created with. I presume this is so that you can modify the exception.

In the function reraise we prepend the exception's original arguments with any new arguments that we want (like a message). Finally we re-raise the exception while preserving the trace-back history.

def reraise(e, *args):
  '''re-raise an exception with extra arguments
  :param e: The exception to reraise
  :param args: Extra args to add to the exception
  '''

  # e.args is a tuple of arguments that the exception with instantiated with.
  #
  e.args = args + e.args

  # Recreate the expection and preserve the traceback info so thta we can see 
  # where this exception originated.
  #
  raise e.with_traceback(e.__traceback__)   


def bad():
  raise ValueError('bad')

def very():
  try:
    bad()
  except Exception as e:
    reraise(e, 'very')

def very_very():
  try:
    very()
  except Exception as e:
    reraise(e, 'very')

very_very()

output

Traceback (most recent call last):
  File "main.py", line 35, in <module>
    very_very()
  File "main.py", line 30, in very_very
    reraise(e, 'very')
  File "main.py", line 15, in reraise
    raise e.with_traceback(e.__traceback__)
  File "main.py", line 28, in very_very
    very()
  File "main.py", line 24, in very
    reraise(e, 'very')
  File "main.py", line 15, in reraise
    raise e.with_traceback(e.__traceback__)
  File "main.py", line 22, in very
    bad()
  File "main.py", line 18, in bad
    raise ValueError('bad')
ValueError: ('very', 'very', 'bad')

How to POST request using RestSharp

My RestSharp POST method:

var client = new RestClient(ServiceUrl);

var request = new RestRequest("/resource/", Method.POST);

// Json to post.
string jsonToSend = JsonHelper.ToJson(json);

request.AddParameter("application/json; charset=utf-8", jsonToSend, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;

try
{
    client.ExecuteAsync(request, response =>
    {
        if (response.StatusCode == HttpStatusCode.OK)
        {
            // OK
        }
        else
        {
            // NOK
        }
    });
}
catch (Exception error)
{
    // Log
}

Increase max execution time for php

PHP file (for example, my_lengthy_script.php)

ini_set('max_execution_time', 300); //300 seconds = 5 minutes

.htaccess file

<IfModule mod_php5.c>
php_value max_execution_time 300
</IfModule>

More configuration options

<IfModule mod_php5.c>
php_value post_max_size 5M
php_value upload_max_filesize 5M
php_value memory_limit 128M
php_value max_execution_time 300
php_value max_input_time 300
php_value session.gc_maxlifetime 1200
</IfModule>

If wordpress, set this in the config.php file,

define('WP_MEMORY_LIMIT', '128M');

If drupal, sites/default/settings.php

ini_set('memory_limit', '128M');

If you are using other frameworks,

ini_set('memory_limit', '128M');

You can increase memory as gigabyte.

ini_set('memory_limit', '3G'); // 3 Gigabytes

259200 means:-

( 259200/(60x60 minutes) ) / 24 hours ===> 3 Days

More details on my blog

MySQL timezone change?

issue the command:

SET time_zone = 'America/New_York';

(Or whatever time zone GMT+1 is.: http://www.php.net/manual/en/timezones.php)

This is the command to set the MySQL timezone for an individual client, assuming that your clients are spread accross multiple time zones.

This command should be executed before every SQL command involving dates. If your queries go thru a class, then this is easy to implement.

Is it possible to reference one CSS rule within another?

Just add the classes to your html

<div class="someDiv radius opacity"></div>

How to change the port of Tomcat from 8080 to 80?

I tried changing the port from 8080 to 80 in the server.xml but it didn't work for me. Then I found alternative, update the iptables which i'm sure there is an impact on performance.

I use the following commands:

sudo /sbin/iptables -t nat -I PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
sudo /sbin/service iptables save

http://www.excelsior-usa.com/articles/tomcat-amazon-ec2-advanced.html#port80

How to use session in JSP pages to get information?

You can directly use (String)session.getAttribute("username"); inside scriptlet tag ie <% %>.

Extracting first n columns of a numpy matrix

I know this is quite an old question -

A = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

Let's say, you want to extract the first 2 rows and first 3 columns

A_NEW = A[0:2, 0:3]
A_NEW = [[1, 2, 3],
         [4, 5, 6]]

Understanding the syntax

A_NEW = A[start_index_row : stop_index_row, 
          start_index_column : stop_index_column)]

If one wants row 2 and column 2 and 3

A_NEW = A[1:2, 1:3]

Reference the numpy indexing and slicing article - Indexing & Slicing

How to remove text from a string?

Performance

Today 2021.01.14 I perform tests on MacOs HighSierra 10.13.6 on Chrome v87, Safari v13.1.2 and Firefox v84 for chosen solutions.

Results

For all browsers

  • solutions Ba, Cb, and Db are fast/fastest for long strings
  • solutions Ca, Da are fast/fastest for short strings
  • solutions Ab and E are slow for long strings
  • solutions Ba, Bb and F are slow for short strings

enter image description here

Details

I perform 2 tests cases:

  • short string - 10 chars - you can run it HERE
  • long string - 1 000 000 chars - you can run it HERE

Below snippet presents solutions Aa Ab Ba Bb Ca Cb Da Db E F

_x000D_
_x000D_
// https://stackoverflow.com/questions/10398931/how-to-strToRemove-text-from-a-string

// https://stackoverflow.com/a/10398941/860099
function Aa(str,strToRemove) {
  return str.replace(strToRemove,'');
}

// https://stackoverflow.com/a/63362111/860099
function Ab(str,strToRemove) {
  return str.replaceAll(strToRemove,'');
}

// https://stackoverflow.com/a/23539019/860099
function Ba(str,strToRemove) {
  let re = strToRemove.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // regexp escape char
  return str.replace(new RegExp(re),'');
}

// https://stackoverflow.com/a/63362111/860099
function Bb(str,strToRemove) {
  let re = strToRemove.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // regexp escape char
  return str.replaceAll(new RegExp(re,'g'),'');
}

// https://stackoverflow.com/a/27098801/860099
function Ca(str,strToRemove) {
  let start = str.indexOf(strToRemove);
  return str.slice(0,start) + str.slice(start+strToRemove.length, str.length);
}

// https://stackoverflow.com/a/27098801/860099
function Cb(str,strToRemove) {
  let start = str.search(strToRemove);
  return str.slice(0,start) + str.slice(start+strToRemove.length, str.length);
}

// https://stackoverflow.com/a/23181792/860099
function Da(str,strToRemove) {
  let start = str.indexOf(strToRemove);
  return str.substr(0, start) + str.substr(start + strToRemove.length);
}

// https://stackoverflow.com/a/23181792/860099
function Db(str,strToRemove) {
  let start = str.search(strToRemove);
  return str.substr(0, start) + str.substr(start + strToRemove.length);
}

// https://stackoverflow.com/a/49857431/860099
function E(str,strToRemove) {
  return str.split(strToRemove).join('');
}

// https://stackoverflow.com/a/45406624/860099
function F(str,strToRemove) {
    var n = str.search(strToRemove);
    while (str.search(strToRemove) > -1) {
        n = str.search(strToRemove);
        str = str.substring(0, n) + str.substring(n + strToRemove.length, str.length);
    }
    return str;
}


let str = "data-123";
let strToRemove = "data-";

[Aa,Ab,Ba,Bb,Ca,Cb,Da,Db,E,F].map( f=> console.log(`${f.name.padEnd(2,' ')} ${f(str,strToRemove)}`));
_x000D_
This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
_x000D_
_x000D_

And here are example results for chrome

enter image description here

Configure Log4Net in web application

1: Add the following line into the AssemblyInfo class

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

2: Make sure you don't use .Net Framework 4 Client Profile as Target Framework (I think this is OK on your side because otherwise it even wouldn't compile)

3: Make sure you log very early in your program. Otherwise, in some scenarios, it will not be initialized properly (read more on log4net FAQ).

So log something during application startup in the Global.asax

public class Global : System.Web.HttpApplication
{
    private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(Global));
    protected void Application_Start(object sender, EventArgs e)
    {
        Log.Info("Startup application.");
    }
}

4: Make sure you have permission to create files and folders on the given path (if the folder itself also doesn't exist)

5: The rest of your given information looks ok

React Native Change Default iOS Simulator Device

change line code of /node_modules/react-native/local-cli/runIOS/findMatchingSimulator.js

line 55

  if (
    simulator.availability !== '(available)' &&
    simulator.isAvailable !== true
  ) {
    continue;
  }

replace which:

   if (
                simulator.availability !== '(available)' &&
                simulator.isAvailable !== true
              ) {
                continue;
     }

Does PHP have threading?

There is a Threading extension being activley developed based on PThreads that looks very promising at https://github.com/krakjoe/pthreads

Difference between agile and iterative and incremental development

Agile is mostly used technique in project development.In agile technology peoples are switches from one technology to other ..Main purpose is to remove dependancy. Like Peoples shifted from production to development,and development to testing. Thats why dependancy will remove on a single team or person..

How can I kill whatever process is using port 8080 so that I can vagrant up?

Use the following command:

lsof -n -i4TCP:8080 | awk '{print$2}' | xargs kill -9

The process id of port 8080 will be picked and killed forcefully using kill -9.

Linux shell sort file according to the second column?

If this is UNIX:

sort -k 2 file.txt

You can use multiple -k flags to sort on more than one column. For example, to sort by family name then first name as a tie breaker:

sort -k 2,2 -k 1,1 file.txt

Relevant options from "man sort":

-k, --key=POS1[,POS2]

start a key at POS1, end it at POS2 (origin 1)

POS is F[.C][OPTS], where F is the field number and C the character position in the field. OPTS is one or more single-letter ordering options, which override global ordering options for that key. If no key is given, use the entire line as the key.

-t, --field-separator=SEP

use SEP instead of non-blank to blank transition

Selecting the last value of a column

I looked at the previous answers and they seem like they're working too hard. Maybe scripting support has simply improved. I think the function is expressed like this:

function lastValue(myRange) {
    lastRow = myRange.length;
    for (; myRange[lastRow - 1] == "" && lastRow > 0; lastRow--)
    { /*nothing to do*/ }
    return myRange[lastRow - 1];
}

In my spreadsheet I then use:

= lastValue(E17:E999)

In the function, I get an array of values with one per referenced cell and this just iterates from the end of the array backwards until it finds a non-empty value or runs out of elements. Sheet references should be interpreted before the data is passed to the function. Not fancy enough to handle multi-dimensions, either. The question did ask for the last cell in a single column, so it seems to fit. It will probably die on if you run out of data, too.

Your mileage may vary, but this works for me.

Why are there no ++ and --? operators in Python?

I believe it stems from the Python creed that "explicit is better than implicit".

Tensorflow r1.0 : could not a find a version that satisfies the requirement tensorflow

From your python version output, looks like that you are using Anaconda python, in that case, there is a simple way to install tensorflow.

conda install -c conda-forge tensorflow

This command will take care of all dependencies like upgrade/downgrade etc.

Android: How to turn screen on and off programmatically?

As per Android API 28 and above you need to do the following to turn on the screen

setShowWhenLocked(true); 
setTurnScreenOn(true); 
KeyguardManager keyguardManager = (KeyguardManager)
getSystemService(Context.KEYGUARD_SERVICE);
keyguardManager.requestDismissKeyguard(this, null);

Enabling SSL with XAMPP

You can also configure your SSL in xampp/apache/conf/extra/httpd-vhost.conf like this:

<VirtualHost *:443>
    DocumentRoot C:/xampp/htdocs/yourProject
    ServerName yourProject.whatever
    SSLEngine on
    SSLCertificateFile "conf/ssl.crt/server.crt"
    SSLCertificateKeyFile "conf/ssl.key/server.key"
</VirtualHost>

I guess, it's better not change it in the httpd-ssl.conf if you have more than one project and you need SSL on more than one of them

mysql SELECT IF statement with OR

IF(compliment IN('set','Y',1), 'Y', 'N') AS customer_compliment

Will do the job as Buttle Butkus suggested.

What is HTML5 ARIA?

What is ARIA?

ARIA emerged as a way to address the accessibility problem of using a markup language intended for documents, HTML, to build user interfaces (UI). HTML includes a great many features to deal with documents (P, h3,UL,TABLE) but only basic UI elements such as A, INPUT and BUTTON. Windows and other operating systems support APIs that allow (Assistive Technology) AT to access the functionality of UI controls. Internet Explorer and other browsers map the native HTML elements to the accessibility API, but the html controls are not as rich as the controls common on desktop operating systems, and are not enough for modern web applications Custom controls can extend html elements to provide the rich UI needed for modern web applications. Before ARIA, the browser had no way to expose this extra richness to the accessibility API or AT. The classic example of this issue is adding a click handler to an image. It creates what appears to be a clickable button to a mouse user, but is still just an image to a keyboard or AT user.

The solution was to create a set of attributes that allow developers to extend HTML with UI semantics. The ARIA term for a group of HTML elements that have custom functionality and use ARIA attributes to map these functions to accessibility APIs is a “Widget. ARIA also provides a means for authors to document the role of content itself, which in turn, allows AT to construct alternate navigation mechanisms for the content that are much easier to use than reading the full text or only iterating over a list of the links.

It is important to remember that in simple cases, it is much preferred to use native HTML controls and style them rather than using ARIA. That is don’t reinvent wheels, or checkboxes, if you don’t have to.

Fortunately, ARIA markup can be added to existing sites without changing the behavior for mainstream users. This greatly reduces the cost of modifying and testing the website or application.

What is the usefulness of PUT and DELETE HTTP request methods?

Safe Methods : Get Resource/No modification in resource
Idempotent : No change in resource status if requested many times
Unsafe Methods : Create or Update Resource/Modification in resource
Non-Idempotent : Change in resource status if requested many times

According to your requirement :

1) For safe and idempotent operation (Fetch Resource) use --------- GET METHOD
2) For unsafe and non-idempotent operation (Insert Resource) use--------- POST METHOD
3) For unsafe and idempotent operation (Update Resource) use--------- PUT METHOD
3) For unsafe and idempotent operation (Delete Resource) use--------- DELETE METHOD

Java String new line

Example

System.out.printf("I %n am %n a %n boy");

Output

I 
 am 
 a 
 boy

Explanation

It's better to use %n as an OS independent new-line character instead of \n and it's easier than using System.lineSeparator()

Why to use %n, because on each OS, new line refers to a different set of character(s);

Unix and modern Mac's   :   LF     (\n)
Windows                 :   CR LF  (\r\n)
Older Macintosh Systems :   CR     (\r)

LF is the acronym of Line Feed and CR is the acronym of Carriage Return. The escape characters are written inside the parenthesis. So on each OS, new line stands for something specific to the system. %n is OS agnostic, it is portable. It stands for \n on Unix systems or \r\n on Windows systems and so on. Thus, Do not use \n, instead use %n.

MySQL LEFT JOIN 3 tables

Select Persons.Name, Persons.SS, Fears.Fear
From Persons
LEFT JOIN Persons_Fear
ON Persons.PersonID = Person_Fear.PersonID
LEFT JOIN Fears
ON Person_Fear.FearID = Fears.FearID;

Can an Option in a Select tag carry multiple values?

I did this by using data attributes. Is a lot cleaner than other methods attempting to explode etc.

HTML

<select class="example">
    <option value="1" data-value="A">One</option>
    <option value="2" data-value="B">Two</option>
    <option value="3" data-value="C">Three</option>
    <option value="4" data-value="D">Four</option>
</select>

JS

$('select.example').change(function() {

    var other_val = $('select.example option[value="' + $(this).val() + '"]').data('value');

    console.log(other_val);

});

How to create a multi line body in C# System.Net.Mail.MailMessage

Try this

IsBodyHtml = false,
BodyEncoding = Encoding.UTF8,
BodyTransferEncoding = System.Net.Mime.TransferEncoding.EightBit

If you wish to stick to using \r\n

I managed to get mine working after trying for one whole day!

Updating PartialView mvc 4

Controller :

public ActionResult Refresh(string ID)
    {
        DetailsViewModel vm = new DetailsViewModel();  // Model
        vm.productDetails = _product.GetproductDetails(ID); 
        /* "productDetails " is a property in "DetailsViewModel"
        "GetProductDetails" is a method in "Product" class
        "_product" is an interface of "Product" class */

        return PartialView("_Details", vm); // Details is a partial view
    }

In yore index page you should to have refresh link :

     <a href="#" id="refreshItem">Refresh</a>

This Script should be also in your index page:

<script type="text/javascript">

    $(function () {
    $('a[id=refreshItem]:last').click(function (e) {
        e.preventDefault();

        var url = MVC.Url.action('Refresh', 'MyController', { itemId: '@(Model.itemProp.itemId )' }); // Refresh is an Action in controller, MyController is a controller name

        $.ajax({
            type: 'GET',
            url: url,
            cache: false,
            success: function (grid) {
                $('#tabItemDetails').html(grid);
                clientBehaviors.applyPlugins($("#tabProductDetails")); // "tabProductDetails" is an id of div in your "Details partial view"
            }
        });
    });
});

How do I change the font-size of an <option> element within <select>?

One solution could be to wrap the options inside optgroup:

_x000D_
_x000D_
optgroup { font-size:40px; }
_x000D_
<select>
  <optgroup>
    <option selected="selected" class="service-small">Service area?</option>
    <option class="service-small">Volunteering</option>
    <option class="service-small">Partnership &amp; Support</option>
    <option class="service-small">Business Services</option>
  </optgroup>
</select>
_x000D_
_x000D_
_x000D_

Location of GlassFish Server Logs

Locate the installation path of GlassFish. Then move to domains/domain-dir/logs/ and you'll find there the log files. If you have created the domain with NetBeans, the domain-dir is most probably called domain1.

See this link for the official GlassFish documentation about logging.

In php, is 0 treated as empty?

empty should mean empty .. whatever deceze says.

When I do

$var = '';    
$var = '0';

I expect that var_dump(empty($var)); will return false.

if you are checking things in an array you always have to do isset($var) first.

Reading all files in a directory, store them in objects, and send the object

Another version with Promise's modern method. It's shorter that the others responses based on Promise :

const readFiles = (dirname) => {

  const readDirPr = new Promise( (resolve, reject) => {
    fs.readdir(dirname, 
      (err, filenames) => (err) ? reject(err) : resolve(filenames))
  });

  return readDirPr.then( filenames => Promise.all(filenames.map((filename) => {
      return new Promise ( (resolve, reject) => {
        fs.readFile(dirname + filename, 'utf-8',
          (err, content) => (err) ? reject(err) : resolve(content));
      })
    })).catch( error => Promise.reject(error)))
};

readFiles(sourceFolder)
  .then( allContents => {

    // handle success treatment

  }, error => console.log(error));

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

I'd just like to add that @JoinColumn does not always have to be related to the physical information location as this answer suggests. You can combine @JoinColumn with @OneToMany even if the parent table has no table data pointing to the child table.

How to define unidirectional OneToMany relationship in JPA

Unidirectional OneToMany, No Inverse ManyToOne, No Join Table

It seems to only be available in JPA 2.x+ though. It's useful for situations where you want the child class to just contain the ID of the parent, not a full on reference.

How to make ConstraintLayout work with percentage values?

Simply, just replace , in your guideline tag

app:layout_constraintGuide_begin="291dp"

with

app:layout_constraintGuide_percent="0.7"

where 0.7 means 70%.

Also if you now try to drag guidelines, the dragged value will now show up in %age.

Getting the application's directory from a WPF application

You can also use the first argument of the command line arguments:

String exePath = System.Environment.GetCommandLineArgs()[0]

How can I run multiple curl requests processed sequentially?

I think this uses more native capabilities

//printing the links to a file
$ echo "https://stackoverflow.com/questions/3110444/
https://stackoverflow.com/questions/8445445/
https://stackoverflow.com/questions/4875446/" > links_file.txt


$ xargs curl < links_file.txt

Enjoy!

Passing variable from Form to Module in VBA

Don't declare the variable in the userform. Declare it as Public in the module.

Public pass As String

In the Userform

Private Sub CommandButton1_Click()
    pass = UserForm1.TextBox1
    Unload UserForm1
End Sub

In the Module

Public pass As String

Public Sub Login()
    '
    '~~> Rest of the code
    '
    UserForm1.Show
    driver.findElementByName("PASSWORD").SendKeys pass
    '
    '~~> Rest of the code
    '
End Sub

You might want to also add an additional check just before calling the driver.find... line?

If Len(Trim(pass)) <> 0 Then

This will ensure that a blank string is not passed.

How to lose margin/padding in UITextView?

I would definitely avoid any answers involving hard-coded values, as the actual margins may change with user font-size settings, etc.

Here is @user1687195's answer, written without modifying the textContainer.lineFragmentPadding (because the docs state this is not the intended usage).

This works great for iOS 7 and later.

self.textView.textContainerInset = UIEdgeInsetsMake(
                                      0, 
                                      -self.textView.textContainer.lineFragmentPadding, 
                                      0, 
                                      -self.textView.textContainer.lineFragmentPadding);

This is effectively the same outcome, just a bit cleaner in that it doesn't misuse the lineFragmentPadding property.

What does `set -x` do?

-u: disabled by default. When activated, an error message is displayed when using an unconfigured variable.

-v: inactive by default. After activation, the original content of the information will be displayed (without variable resolution) before the information is output.

-x: inactive by default. If activated, the command content will be displayed before the command is run (after variable resolution, there is a ++ symbol).

Compare the following differences:

/ # set -v && echo $HOME
/root
/ # set +v && echo $HOME
set +v && echo $HOME
/root

/ # set -x && echo $HOME
+ echo /root
/root
/ # set +x && echo $HOME
+ set +x
/root

/ # set -u && echo $NOSET
/bin/sh: NOSET: parameter not set
/ # set +u && echo $NOSET

Send text to specific contact programmatically (whatsapp)

Bitmap bmp = null;
            bmp = ((BitmapDrawable) tmpimg.getDrawable()).getBitmap();
            Uri bmpUri = null;
            try {
                File file = new File(getBaseContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".jpg");
                FileOutputStream out = new FileOutputStream(file);
                bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
                out.close();
                bmpUri = Uri.fromFile(file);

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

            String toNumber = "+919999999999"; 
            toNumber = toNumber.replace("+", "").replace(" ", "");
            Intent shareIntent =new Intent("android.intent.action.MAIN");
            shareIntent.setAction(Intent.ACTION_SEND);
            String ExtraText;
            ExtraText =  "Share Text";
            shareIntent.putExtra(Intent.EXTRA_TEXT, ExtraText);
            shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
            shareIntent.setType("image/jpg");
            shareIntent.setPackage("com.whatsapp");
            shareIntent.putExtra("jid", toNumber + "@s.whatsapp.net");
            shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            try {

                startActivity(shareIntent);
            } catch (android.content.ActivityNotFoundException ex) {
                Toast.makeText(getBaseContext(), "Sharing tools have not been installed.", Toast.LENGTH_SHORT).show();
            }

        }

What is a .pid file and what does it contain?

To understand pid files, refer this DOC

Some times there are certain applications that require additional support of extra plugins and utilities. So it keeps track of these utilities and plugin process running ids using this pid file for reference.

That is why whenever you restart an application all necessary plugins and dependant apps must be restarted since the pid file will become stale.

Escaping Strings in JavaScript

http://locutus.io/php/strings/addslashes/

function addslashes( str ) {
    return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}

Change the Blank Cells to "NA"

Call dplyr package by installing from cran in r

library(dplyr)

(file)$(colname)<-sub("-",NA,file$colname) 

It will convert all the blank cell in a particular column as NA

If the column contains "-", "", 0 like this change it in code according to the type of blank cell

E.g. if I get a blank cell like "" instead of "-", then use this code:

(file)$(colname)<-sub("", NA, file$colname)

Java Calendar, getting current month value, clarification needed

import java.util.*;

class GetCurrentmonth
{
    public static void main(String args[])
    {
        int month;
        GregorianCalendar date = new GregorianCalendar();      
        month = date.get(Calendar.MONTH);
        month = month+1;
        System.out.println("Current month is  " + month);
    }
}

Cannot create a connection to data source Error (rsErrorOpeningConnection) in SSRS

The issue is because your data source is not setup properly, to do that please verify your data source connection, in order to do that first navigate to Report Service Configuration Manager through

clicking on the start -> Start All -> Microsoft SQL Server ->Configuration Tool -> “Report Service Configuration Manager”

The open Report Manager URL and then navigate to the Data Source folder, see in the picture below

Then Create a Data Source or configure the one that is already there by right click on your database source and select "Manage" as is shown below

Now on the properties tab, on your left menu, fill out the data source with your connection string and username and password, after that click on test connection, and if the connection was successful, then click "Apply"

Navigate to the folder that contains your report in this case "SurveyLevelReport"

And Finally set your Report to the Data Source that you set up previously, and click Apply

When to encode space to plus (+) or %20?

Its better to always encode spaces as %20, not as "+".

It was RFC-1866 (HTML 2.0 specification), which specified that space characters should be encoded as "+" in "application/x-www-form-urlencoded" content-type key-value pairs. (see paragraph 8.2.1. subparagraph 1.). This way of encoding form data is also given in later HTML specifications, look for relevant paragraphs about application/x-www-form-urlencoded.

Here is an example of such a string in URL where RFC-1866 allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses, according to RFC-1866. In other cases, spaces should be encoded to %20. But since it's hard to determine the context, it's the best practice to never encode spaces as "+".

I would recommend to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3

unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"

How to time Java program execution speed

Using AOP/AspectJ and @Loggable annotation from jcabi-aspects you can do it easy and compact:

@Loggable(Loggable.DEBUG)
public String getSomeResult() {
  // return some value
}

Every call to this method will be sent to SLF4J logging facility with DEBUG logging level. And every log message will include execution time.

Select distinct values from a large DataTable column

Try this:

var idColumn="id";
var list = dt.DefaultView
    .ToTable(true, idColumn)
    .Rows
    .Cast<DataRow>()
    .Select(row => row[idColumn])
    .ToList();

Can I hide the HTML5 number input’s spin box?

This CSS effectively hides the spin-button for webkit browsers (have tested it in Chrome 7.0.517.44 and Safari Version 5.0.2 (6533.18.5)):

_x000D_
_x000D_
input::-webkit-outer-spin-button,_x000D_
input::-webkit-inner-spin-button {_x000D_
    /* display: none; <- Crashes Chrome on hover */_x000D_
    -webkit-appearance: none;_x000D_
    margin: 0; /* <-- Apparently some margin are still there even though it's hidden */_x000D_
}_x000D_
_x000D_
input[type=number] {_x000D_
    -moz-appearance:textfield; /* Firefox */_x000D_
}
_x000D_
<input type="number" step="0.01" />
_x000D_
_x000D_
_x000D_

You can always use the inspector (webkit, possibly Firebug for Firefox) to look for matched CSS properties for the elements you are interested in, look for Pseudo elements. This image shows results for an input element type="number":

Inspector for input type=number (Chrome)

Why does Java's hashCode() in String use 31 as a multiplier?

I'm not sure, but I would guess they tested some sample of prime numbers and found that 31 gave the best distribution over some sample of possible Strings.

How to programmatically determine the current checked out Git branch

I found two really simple ways to do that:

$ git status | head -1 | cut -d ' ' -f 4

and

$ git branch | grep "*" | cut -d ' ' -f 2

When is the @JsonProperty property used and what is it used for?

As you know, this is all about serialize and desalinize an object. Suppose there is an object:

public class Parameter {
  public String _name;
  public String _value; 
}

The serialization of this object is:

{
  "_name": "...",
  "_value": "..."
}

The name of variable is directly used to serialize data. If you are about to remove system api from system implementation, in some cases, you have to rename variable in serialization/deserialization. @JsonProperty is a meta data to tell serializer how to serial object. It is used to:

  • variable name
  • access (READ, WRITE)
  • default value
  • required/optional

from example:

public class Parameter {
  @JsonProperty(
        value="Name",
        required=true,
        defaultValue="No name",
        access= Access.READ_WRITE)
  public String _name;
  @JsonProperty(
        value="Value",
        required=true,
        defaultValue="Empty",
        access= Access.READ_WRITE)
  public String _value; 
}

Format numbers in django templates

Based on muhuk answer I did this simple tag encapsulating python string.format method.

  • Create a templatetags at your's application folder.
  • Create a format.py file on it.
  • Add this to it:

    from django import template
    
    register = template.Library()
    
    @register.filter(name='format')
    def format(value, fmt):
        return fmt.format(value)
    
  • Load it in your template {% load format %}
  • Use it. {{ some_value|format:"{:0.2f}" }}

node.js vs. meteor.js what's the difference?

Meteor is a framework built ontop of node.js. It uses node.js to deploy but has several differences.

The key being it uses its own packaging system instead of node's module based system. It makes it easy to make web applications using Node. Node can be used for a variety of things and on its own is terrible at serving up dynamic web content. Meteor's libraries make all of this easy.

MSIE and addEventListener Problem in Javascript?

The problem is that IE does not have the standard addEventListener method. IE uses its own attachEvent which does pretty much the same.

Good explanation of the differences, and also about the 3rd parameter can be found at quirksmode.

How Should I Set Default Python Version In Windows?

Nothing above worked, this is what worked for me:

ftype Python.File=C:\Path\to\python.exe "%1" %*

This command should be run in Command prompt launched as administrator

Warning: even if the path in this command is set to python35, if you have python36 installed it's going to set the default to python36. To prevent this, you can temporarily change the folder name from Python36 to xxPython36, run the command and then remove the change to the Python 36 folder.

C program to check little vs. big endian

The following will do.

unsigned int x = 1;
printf ("%d", (int) (((char *)&x)[0]));

And setting &x to char * will enable you to access the individual bytes of the integer, and the ordering of bytes will depend on the endianness of the system.

Run a command shell in jenkins

I was running a job which ran a shell script in Jenkins on a Windows machine. The job was failing due to the error given below. I was able to fix the error thanks to clues in Andrejz's answer.

Error :

Started by user james
Running as SYSTEM
Building in workspace C:\Users\jamespc\.jenkins\workspace\myfolder\my-job
[my-job] $ sh -xe C:\Users\jamespc\AppData\Local\Temp\jenkins933823447809390219.sh
The system cannot find the file specified
FATAL: command execution failed
java.io.IOException: CreateProcess error=2, The system cannot find the file specified
    at java.base/java.lang.ProcessImpl.create(Native Method)
    at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:478)
    at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:154)
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
Caused: java.io.IOException: Cannot run program "sh" (in directory "C:\Users\jamespc\.jenkins\workspace\myfolder\my-job"): CreateProcess error=2, The system cannot find the file specified
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
    at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
    at hudson.Proc$LocalProc.<init>(Proc.java:250)
    at hudson.Proc$LocalProc.<init>(Proc.java:219)
    at hudson.Launcher$LocalLauncher.launch(Launcher.java:937)
    at hudson.Launcher$ProcStarter.start(Launcher.java:455)
    at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:109)
    at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:66)
    at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:741)
    at hudson.model.Build$BuildExecution.build(Build.java:206)
    at hudson.model.Build$BuildExecution.doRun(Build.java:163)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:504)
    at hudson.model.Run.execute(Run.java:1853)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:97)
    at hudson.model.Executor.run(Executor.java:427)
Build step 'Execute shell' marked build as failure
Finished: FAILURE

Solution :

1 - Install Cygwin and note the directory where it gets installed.

It was C:\cygwin64 in my case. The sh.exe which is needed to run shell scripts is in the "bin" sub-directory, i.e. C:\cygwin64\bin.

2 - Tell Jenkins where sh.exe is located.

Jenkins web console > Manage Jenkins > Configure System > Under shell, set the "Shell executable" = C:\cygwin64\bin\sh.exe > Click apply & also click save.

That's all I did to make my job pass. I was running Jenkins from a war file and I did not need to restart it to make this work.

nginx upload client_max_body_size issue

Does your upload die at the very end? 99% before crashing? Client body and buffers are key because nginx must buffer incoming data. The body configs (data of the request body) specify how nginx handles the bulk flow of binary data from multi-part-form clients into your app's logic.

The clean setting frees up memory and consumption limits by instructing nginx to store incoming buffer in a file and then clean this file later from disk by deleting it.

Set body_in_file_only to clean and adjust buffers for the client_max_body_size. The original question's config already had sendfile on, increase timeouts too. I use the settings below to fix this, appropriate across your local config, server, & http contexts.

client_body_in_file_only clean;
client_body_buffer_size 32K;

client_max_body_size 300M;

sendfile on;
send_timeout 300s;

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

Defining a `required` field in Bootstrap

Form validation can be enabled in markup via the data-api or via JavaScript. Automatically enable form validation by adding data-toggle="validator" to your form element.

<form role="form" data-toggle="validator">
   ...
</form>

Or activate validation via JavaScript:

$('#myForm').validator()

and you need to use required flag in input field

For more details Click Here

R: Comment out block of code

Wrap it in an unused function:

.f = function() {

## unwanted code here:

}

Java 6 Unsupported major.minor version 51.0

According to maven website, the last version to support Java 6 is 3.2.5, and 3.3 and up use Java 7. My hunch is that you're using Maven 3.3 or higher, and should either upgrade to Java 7 (and set proper source/target attributes in your pom) or downgrade maven.

PostgreSQL Crosstab Query

Solution with JSON aggregation:

CREATE TEMP TABLE t (
  section   text
, status    text
, ct        integer  -- don't use "count" as column name.
);

INSERT INTO t VALUES 
  ('A', 'Active', 1), ('A', 'Inactive', 2)
, ('B', 'Active', 4), ('B', 'Inactive', 5)
                   , ('C', 'Inactive', 7); 


SELECT section,
       (obj ->> 'Active')::int AS active,
       (obj ->> 'Inactive')::int AS inactive
FROM (SELECT section, json_object_agg(status,ct) AS obj
      FROM t
      GROUP BY section
     )X

How do I rename a MySQL schema?

If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE

Edit: On the model overview it's under Physical Schemata

Screenshot:

enter image description here

How to compile and run a C/C++ program on the Android system

You can compile your C programs with an ARM cross-compiler:

arm-linux-gnueabi-gcc -static -march=armv7-a test.c -o test

Then you can push your compiled binary file to somewhere (don't push it in to the SD card):

adb push test /data/local/tmp/test

What is the difference between int, Int16, Int32 and Int64?

Int=Int32 --> Original long type

Int16 --> Original int

Int64 --> New data type become available after 64 bit systems

"int" is only available for backward compatibility. We should be really using new int types to make our programs more precise.

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

One more thing I noticed along the way is there is no class named Int similar to Int16, Int32 and Int64. All the helpful functions like TryParse for integer come from Int32.TryParse.

How to set xampp open localhost:8080 instead of just localhost

Steps using XAMPP GUI:

Step-1: Click on Config button

enter image description here

Step-2: Click on Service and Port Settings button

enter image description here

Final step: Change your port and Save

enter image description here

How to pass parameters using ui-sref in ui-router to controller

You simply misspelled $stateParam, it should be $stateParams (with an s). That's why you get undefined ;)

What does "while True" mean in Python?

Formally, True is a Python built-in constant of bool type.

You can use Boolean operations on bool types (at the interactive python prompt for example) and convert numbers into bool types:

>>> print not True
False
>>> print not False
True
>>> print True or False
True
>>> print True and False
False
>>> a=bool(9)
>>> print a
True
>>> b=bool(0)
>>> print b
False
>>> b=bool(0.000000000000000000000000000000000001)
>>> print b
True

And there are "gotcha's" potentially with what you see and what the Python compiler sees:

>>> n=0
>>> print bool(n)
False
>>> n='0'
>>> print bool(n)
True
>>> n=0.0
>>> print bool(n)
False
>>> n="0.0"
>>> print bool(n)
True

As a hint of how Python stores bool types internally, you can cast bool types to integers and True will come out to be 1 and False 0:

>>> print True+0
1
>>> print True+1
2
>>> print False+0
0
>>> print False+1
1

In fact, Python bool type is a subclass of Python's int type:

>>> type(True)
<type 'bool'>
>>> isinstance(True, int)
True

The more important part of your question is "What is while True?" is 'what is True', and an important corollary: What is false?

First, for every language you are learning, learn what the language considers 'truthy' and 'falsey'. Python considers Truth slightly differently than Perl Truth for example. Other languages have slightly different concepts of true / false. Know what your language considers to be True and False for different operations and flow control to avoid many headaches later!

There are many algorithms where you want to process something until you find what you are looking for. Hence the infinite loop or indefinite loop. Each language tend to have its own idiom for these constructs. Here are common C infinite loops, which also work for Perl:

for(;;) { /* loop until break */ }

/* or */

while (1) {
   return if (function(arg) > 3);
}

The while True: form is common in Python for indefinite loops with some way of breaking out of the loop. Learn Python flow control to understand how you break out of while True loops. Unlike most languages, for example, Python can have an else clause on a loop. There is an example in the last link.

Array from dictionary keys in swift

extension Array {
    public func toDictionary<Key: Hashable>(with selectKey: (Element) -> Key) -> [Key:Element] {
        var dict = [Key:Element]()
        for element in self {
            dict[selectKey(element)] = element
        }
        return dict
    }
}

How to clear exisiting dropdownlist items when its content changes?

Just 2 simple steps to solve your issue

First of all check AppendDataBoundItems property and make it assign false

Secondly clear all the items using property .clear()

{
ddl1.Items.Clear();
ddl1.datasource = sql1;
ddl1.DataBind();
}

How to pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array?

This is fairly straightforward. In your JS, all you would do is this or something similar:

var array = ["thing1", "thing2", "thing3"];

var parameters = {
  "array1[]": array,
  ...
};

$.post(
  'your/page.php',
  parameters
)
.done(function(data, statusText) {
    // This block is optional, fires when the ajax call is complete
});

In your php page, the values in array form will be available via $_POST['array1'].

references

Set initial value in datepicker with jquery?

Use it after initialization code to get current date (in datepicker format):

$(".ui-datepicker-today").trigger("click");

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

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

134217728 bytes = 128 MB

Or rewrite the code to consume less memory.

SSRS 2008 R2 - SSRS 2012 - ReportViewer: Reports are blank in Safari and Chrome

I am using Chrome version 21 with SQL 2008 R2 SP1 and none of the above fixes worked for me. Below is the code that did work, as with the other answers I added this bit of code to Append to "C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ReportManager\js\ReportingServices.js" (on the SSRS Server) :

//Fix to allow Chrome to display SSRS Reports
function pageLoad() { 
    var element = document.getElementById("ctl31_ctl09");
    if (element) 
    {
        element.style.overflow = "visible";         
    } 
}

How to apply a function to two columns of Pandas dataframe

Returning a list from apply is a dangerous operation as the resulting object is not guaranteed to be either a Series or a DataFrame. And exceptions might be raised in certain cases. Let's walk through a simple example:

df = pd.DataFrame(data=np.random.randint(0, 5, (5,3)),
                  columns=['a', 'b', 'c'])
df
   a  b  c
0  4  0  0
1  2  0  1
2  2  2  2
3  1  2  2
4  3  0  0

There are three possible outcomes with returning a list from apply

1) If the length of the returned list is not equal to the number of columns, then a Series of lists is returned.

df.apply(lambda x: list(range(2)), axis=1)  # returns a Series
0    [0, 1]
1    [0, 1]
2    [0, 1]
3    [0, 1]
4    [0, 1]
dtype: object

2) When the length of the returned list is equal to the number of columns then a DataFrame is returned and each column gets the corresponding value in the list.

df.apply(lambda x: list(range(3)), axis=1) # returns a DataFrame
   a  b  c
0  0  1  2
1  0  1  2
2  0  1  2
3  0  1  2
4  0  1  2

3) If the length of the returned list equals the number of columns for the first row but has at least one row where the list has a different number of elements than number of columns a ValueError is raised.

i = 0
def f(x):
    global i
    if i == 0:
        i += 1
        return list(range(3))
    return list(range(4))

df.apply(f, axis=1) 
ValueError: Shape of passed values is (5, 4), indices imply (5, 3)

Answering the problem without apply

Using apply with axis=1 is very slow. It is possible to get much better performance (especially on larger datasets) with basic iterative methods.

Create larger dataframe

df1 = df.sample(100000, replace=True).reset_index(drop=True)

Timings

# apply is slow with axis=1
%timeit df1.apply(lambda x: mylist[x['col_1']: x['col_2']+1], axis=1)
2.59 s ± 76.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

# zip - similar to @Thomas
%timeit [mylist[v1:v2+1] for v1, v2 in zip(df1.col_1, df1.col_2)]  
29.5 ms ± 534 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

@Thomas answer

%timeit list(map(get_sublist, df1['col_1'],df1['col_2']))
34 ms ± 459 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

add commas to a number in jQuery

Take a look at Numeral.js. It can format numbers, currency, percentages and has support for localization.

Replace input type=file by an image

The input itself is hidden with CSS visibility:hidden.

Then you can have whatever element you whish - anchor or image.., when the anchor/image is clicked, trigger a click on the hidden input field - the dialog box for selecting a file will appear.

EDIT: Actually it works in Chrome and Safari, I just noticed that is not the case in FF4Beta

Scale iFrame css width 100% like an image

You could use viewport units here instead of %. Like this:

iframe {
    max-width: 100vw;
    max-height: 56.25vw; /* height/width ratio = 315/560 = .5625 */
}

DEMO (Resize to see the effect)

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
}_x000D_
.a {_x000D_
  max-width: 560px;_x000D_
  background: grey;_x000D_
}_x000D_
img {_x000D_
  width: 100%;_x000D_
  height: auto_x000D_
}_x000D_
iframe {_x000D_
  max-width: 100vw;_x000D_
  max-height: 56.25vw;_x000D_
  /* 315/560 = .5625 */_x000D_
}
_x000D_
<div class="a">_x000D_
  <img src="http://lorempixel.com/560/315/" width="560" height="315" />_x000D_
</div>_x000D_
_x000D_
<div class="a">_x000D_
  <iframe width="560" height="315" src="http://www.youtube.com/embed/RksyMaJiD8Y" frameborder="0" allowfullscreen></iframe>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Disable clipboard prompt in Excel VBA on workbook close

I can offer two options

  1. Direct copy

Based on your description I'm guessing you are doing something like

Set wb2 = Application.Workbooks.Open("YourFile.xls")
wb2.Sheets("YourSheet").[<YourRange>].Copy
ThisWorkbook.Sheets("SomeSheet").Paste
wb2.close

If this is the case, you don't need to copy via the clipboard. This method copies from source to destination directly. No data in clipboard = no prompt

Set wb2 = Application.Workbooks.Open("YourFile.xls")
wb2.Sheets("YourSheet").[<YourRange>].Copy ThisWorkbook.Sheets("SomeSheet").Cells(<YourCell")
wb2.close
  1. Suppress prompt

You can prevent all alert pop-ups by setting

Application.DisplayAlerts = False

[Edit]

  1. To copy values only: don't use copy/paste at all

Dim rSrc As Range
Dim rDst As Range
Set rSrc = wb2.Sheets("YourSheet").Range("YourRange")
Set rDst = ThisWorkbook.Sheets("SomeSheet").Cells("YourCell").Resize(rSrc.Rows.Count, rSrc.Columns.Count)
rDst = rSrc.Value

How to add Android Support Repository to Android Studio?

Found a solution.

1) Go to where your SDK is located that android studio/eclipse is using. If you are using Android studio, go to extras\android\m2repository\com\android\support\. If you are using eclipse, go to \extras\android\support\

2) See what folders you have, for me I had gridlayout-v7, support-v4 and support-v13.

3) click into support-v4 and see what number the following folder is, mine was named 13.0

Since you are using "com.android.support:support-v4:18.0.+", change this to reflect what version you have, for example I have support-v4 so first part v4 stays the same. Since the next path is 13.0, change your 18.0 to:

"com.android.support:support-v4:13.0.+"

This worked for me, hope it helps!

Update:

I noticed I had android studio set up with the wrong SDK which is why originally had difficulty updating! The path should be C:\Users\Username\AppData\Local\Android\android-sdk\extras\

Also note, if your SDK is up to date, the code will be:

"com.android.support:support-v4:19.0.+"

Get fragment (value after hash '#') from a URL in php

I found this trick if you insist want the value with PHP. split the anchor (#) value and get it with JavaScript, then store as cookie, after that get the cookie value with PHP

resize font to fit in a div (on one line)

I've make a very little jQuery stuff to adjust the font size of your div. It even works with multiple lines, but will only increase font's size (you can simply set a default font size of 1px if you want). I increases the font size until having a line break, set decreases it 1px. No other fancy stuff, hidden div or so. Simply add the quickfit class to your div.

$(".quickfit").each(function() {
    var jThis=$(this);
    var fontSize=parseInt(jThis.css("font-size"));
    var originalLines=jThis.height()/fontSize;

    for(var i=0;originalLines>=jThis.height()/fontSize && i<30;i++)
    { jThis.css("font-size",""+(++fontSize)+"px"); }
    jThis.css("font-size",""+(fontSize-1)+"px");
});

GoTo Next Iteration in For Loop in java

Try this,

1. If you want to skip a particular iteration, use continue.

2. If you want to break out of the immediate loop use break

3 If there are 2 loop, outer and inner.... and you want to break out of both the loop from the inner loop, use break with label.

eg:

continue

for(int i=0 ; i<5 ; i++){

    if (i==2){

      continue;
    }
 }

eg:

break

for(int i=0 ; i<5 ; i++){

        if (i==2){

          break;
        }
     }

eg:

break with label

lab1: for(int j=0 ; j<5 ; j++){
     for(int i=0 ; i<5 ; i++){

        if (i==2){

          break lab1;
        }
     }
  }

adding onclick event to dynamically added button?

Try
but.addEventListener('click', yourFunction) Note the absence of parantheses () after the function name. This is because you are assigning the function, not calling it.

Font size of TextView in Android application changes on changing font size from native settings

The easiest to do so is simply to use something like the following:

android:textSize="32sp"

If you'd like to know more about the textSize property, you can check the Android developer documentation.

Copy filtered data to another sheet using VBA

Best way of doing it

Below code is to copy the visible data in DBExtract sheet, and paste it into duplicateRecords sheet, with only filtered values. Range selected by me is the maximum range that can be occupied by my data. You can change it as per your need.

  Sub selectVisibleRange()

    Dim DbExtract, DuplicateRecords As Worksheet
    Set DbExtract = ThisWorkbook.Sheets("Export Worksheet")
    Set DuplicateRecords = ThisWorkbook.Sheets("DuplicateRecords")

    DbExtract.Range("A1:BF9999").SpecialCells(xlCellTypeVisible).Copy
    DuplicateRecords.Cells(1, 1).PasteSpecial


    End Sub

Get File Path (ends with folder)

In the VBA Editor's Tools menu, click References... scroll down to "Microsoft Shell Controls And Automation" and choose it.

Sub FolderSelection()
    Dim MyPath As String
    MyPath = SelectFolder("Select Folder", "")
    If Len(MyPath) Then
        MsgBox MyPath
    Else
        MsgBox "Cancel was pressed"
    End If
End Sub

'Both arguements are optional. The first is the dialog caption and
'the second is is to specify the top-most visible folder in the
'hierarchy. The default is "My Computer."

Function SelectFolder(Optional Title As String, Optional TopFolder _
                         As String) As String
    Dim objShell As New Shell32.Shell
    Dim objFolder As Shell32.Folder

'If you use 16384 instead of 1 on the next line,
'files are also displayed
    Set objFolder = objShell.BrowseForFolder _
                            (0, Title, 1, TopFolder)
    If Not objFolder Is Nothing Then
        SelectFolder = objFolder.Items.Item.Path
    End If
End Function

Source Link.

Use css gradient over background image

Ok, I solved it by adding the url for the background image at the end of the line.

Here's my working code:

_x000D_
_x000D_
.css {_x000D_
  background: -moz-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, rgba(0, 0, 0, 0)), color-stop(59%, rgba(0, 0, 0, 0)), color-stop(100%, rgba(0, 0, 0, 0.65))), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: -webkit-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: -o-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: -ms-linear-gradient(top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0) 59%, rgba(0, 0, 0, 0.65) 100%), url('https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a') no-repeat;_x000D_
  height: 200px;_x000D_
_x000D_
}
_x000D_
<div class="css"></div>
_x000D_
_x000D_
_x000D_

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

The exception can also occur because of the class path not being defined.

After hours of research and literally going through hundreds of pages, the problem was that the class path of the library was not defined.

Set the class path as follows in your windows machine

set classpath=path\to\your\jdbc\jar\file;.

nodeJS - How to create and read session with express

I forgot to tell a bug when i use I use req.session.email = req.param('email'), the server error says cannot sett property email of undefined.

The reason of this error is a wrong order of app.use. You must configure express in this order:

app.use(express.cookieParser());
app.use(express.session({ secret: sessionVal }));
app.use(app.route);

Submit a form using jQuery

I recommend a generic solution so you don't have to add the code for every form. Use the jquery form plugin (http://jquery.malsup.com/form/) and add this code.

$(function(){
$('form.ajax_submit').submit(function() {
    $(this).ajaxSubmit();
            //validation and other stuff
        return false; 
});

});

Get content uri from file path in android

UPDATE

Here it is assumed that your media (Image/Video) is already added to content media provider. If not then you will not able to get the content URL as exact what you want. Instead there will be file Uri.

I had same question for my file explorer activity. You should know that the contenturi for file only supports mediastore data like image, audio and video. I am giving you the code for getting image content uri from selecting an image from sdcard. Try this code, maybe it will work for you...

public static Uri getImageContentUri(Context context, File imageFile) {
  String filePath = imageFile.getAbsolutePath();
  Cursor cursor = context.getContentResolver().query(
      MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
      new String[] { MediaStore.Images.Media._ID },
      MediaStore.Images.Media.DATA + "=? ",
      new String[] { filePath }, null);
  if (cursor != null && cursor.moveToFirst()) {
    int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
    cursor.close();
    return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + id);
  } else {
    if (imageFile.exists()) {
      ContentValues values = new ContentValues();
      values.put(MediaStore.Images.Media.DATA, filePath);
      return context.getContentResolver().insert(
          MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    } else {
      return null;
    }
  }
}

For support android Q

public static Uri getImageContentUri(Context context, File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
        new String[]{MediaStore.Images.Media._ID},
        MediaStore.Images.Media.DATA + "=? ",
        new String[]{filePath}, null);
if (cursor != null && cursor.moveToFirst()) {
    int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
    cursor.close();
    return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + id);
} else {
    if (imageFile.exists()) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ContentResolver resolver = context.getContentResolver();
            Uri picCollection = MediaStore.Images.Media
                    .getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
            ContentValues picDetail = new ContentValues();
            picDetail.put(MediaStore.Images.Media.DISPLAY_NAME, imageFile.getName());
            picDetail.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
            picDetail.put(MediaStore.Images.Media.RELATIVE_PATH,"DCIM/" + UUID.randomUUID().toString());
            picDetail.put(MediaStore.Images.Media.IS_PENDING,1);
            Uri finaluri = resolver.insert(picCollection, picDetail);
            picDetail.clear();
            picDetail.put(MediaStore.Images.Media.IS_PENDING, 0);
            resolver.update(picCollection, picDetail, null, null);
            return finaluri;
        }else {
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, filePath);
            return context.getContentResolver().insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        }

    } else {
        return null;
    }
  }
}

How can I reset eclipse to default settings?

Delete the .metadata folder in your workspace.

How to set String's font size, style in Java using the Font class?

Look here http://docs.oracle.com/javase/6/docs/api/java/awt/Font.html#deriveFont%28float%29

JComponent has a setFont() method. You will control the font there, not on the String.

Such as

JButton b = new JButton();
b.setFont(b.getFont().deriveFont(18.0f));

get the value of "onclick" with jQuery?

Could you explain what exactly you try to accomplish? In general you NEVER have to get the onclick attribute from HTML elements. Also you should not specify the onclick on the element itself. Instead set the onclick dynamically using JQuery.

But as far as I understand you, you try to switch between two different onclick functions. What may be better is to implement your onclick function in such a way that it can handle both situations.

$("#google").click(function() {
    if (situation) {
        // ...
    } else {
        // ...
    }
});

Error loading MySQLdb Module 'Did you install mysqlclient or MySQL-python?'

Faced same problem after migrating to python 3. Apparently, MySQL-python is incompatible, so as per official django docs, installed mysqlclient using pip install mysqlclient on Mac. Note that there are some OS specific issues mentioned in docs.

Quoting from docs:

Prerequisites

You may need to install the Python and MySQL development headers and libraries like so:

sudo apt-get install python-dev default-libmysqlclient-dev # Debian / Ubuntu

sudo yum install python-devel mysql-devel # Red Hat / CentOS

brew install mysql-connector-c # macOS (Homebrew) (Currently, it has bug. See below)

On Windows, there are binary wheels you can install without MySQLConnector/C or MSVC.

Note on Python 3 : if you are using python3 then you need to install python3-dev using the following command :

sudo apt-get install python3-dev # debian / Ubuntu

sudo yum install python3-devel # Red Hat / CentOS

Note about bug of MySQL Connector/C on macOS

See also: https://bugs.mysql.com/bug.php?id=86971

Versions of MySQL Connector/C may have incorrect default configuration options that cause compilation errors when mysqlclient-python is installed. (As of November 2017, this is known to be true for homebrew's mysql-connector-c and official package)

Modification of mysql_config resolves these issues as follows.

Change

# on macOS, on or about line 112:
# Create options
libs="-L$pkglibdir"
libs="$libs -l "

to

# Create options
libs="-L$pkglibdir"
libs="$libs -lmysqlclient -lssl -lcrypto"

An improper ssl configuration may also create issues; see, e.g, brew info openssl for details on macOS.

Install from PyPI

pip install mysqlclient

NOTE: Wheels for Windows may be not released with source package. You should pin version in your requirements.txt to avoid trying to install newest source package.

Install from source

  1. Download source by git clone or zipfile.
  2. Customize site.cfg
  3. python setup.py install

Change font color and background in html on mouseover

Either do it with CSS like the other answers did or change the text style color directly via the onMouseOver and onMouseOut event:

onmouseover="this.bgColor='white'; this.style.color='black'"

onmouseout="this.bgColor='black'; this.style.color='white'"

Interview question: Check if one string is a rotation of other string

Whoa, whoa... why is everyone so thrilled with an O(n^2) answer? I'm positive that we can do better here. THE answer above includes an O(n) operation in an O(n) loop (the substring/indexOf call). Even with a more efficient search algorithm; say Boyer-Moore or KMP, the worst-case is still O(n^2) with duplicates.

A O(n) randomized answer is straightforward; take a hash (like a Rabin fingerprint) that supports an O(1) sliding window; hash string 1, then hash string 2, and proceed to move the window for hash 1 around the string and see if the hash functions collide.

If we imagine the worst case being something like "scanning two strands of DNA", then the probability of collisions goes up, and this probably degenerates to something like O(n^(1+e)) or something (just guessing here).

Finally, there's a deterministic O(nlogn) solution that has a very big constant outside. Basically, the idea is to take a convolution of the two strings. The max value of the convolution will be the rotation difference (if they are rotated); an O(n) check confirms. The nice thing is that if there are two equal max values, then they are both also valid solutions. You can do the convolution with two FFT's and a dot product, and an iFFT, so nlogn + nlogn + n + nlogn + n == O(nlogn).

Since you can't pad with zeroes, and you can't guarantee that the strings are of 2^n length, the FFTs won't be the fast ones; they'll be the slow ones, still O(nlogn) but a much bigger constant than the CT algorithm.

All that said, I'm absolutely, 100% positive that there is a deterministic O(n) solution here, but darned if I can find it.

Java: how do I get a class literal from a generic type?

There are no Class literals for parameterized types, however there are Type objects that correctly define these types.

See java.lang.reflect.ParameterizedType - http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/ParameterizedType.html

Google's Gson library defines a TypeToken class that allows to simply generate parameterized types and uses it to spec json objects with complex parameterized types in a generic friendly way. In your example you would use:

Type typeOfListOfFoo = new TypeToken<List<Foo>>(){}.getType()

I intended to post links to the TypeToken and Gson classes javadoc but Stack Overflow won't let me post more than one link since I'm a new user, you can easily find them using Google search

How to check if a folder exists

To check if a directory exists with the new IO:

if (Files.isDirectory(Paths.get("directory"))) {
  ...
}

isDirectory returns true if the file is a directory; false if the file does not exist, is not a directory, or it cannot be determined if the file is a directory or not.

See: documentation.

How to parse a JSON object to a TypeScript Object

let employee = <Employee>JSON.parse(employeeString);

Remember: Strong typings is compile time only since javascript doesn't support it.

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

If you have 32-bit Windows, this method is not working without following settings.

  1. Run prompt cmd.exe (important : Run As Administrator)
  2. type bcdedit.exe and run
  3. Look at the "increaseuserva" params and there is no then write following statement
  4. bcdedit /set increaseuserva 3072
  5. and again step 2 and check params

We added this settings and this block started.

if exist "$(DevEnvDir)..\tools\vsvars32.bat" (
   call "$(DevEnvDir)..\tools\vsvars32.bat"
   editbin /largeaddressaware "$(TargetPath)"
)

More info - command increaseuserva: https://docs.microsoft.com/en-us/windows-hardware/drivers/devtest/bcdedit--set

Disable activity slide-in animation when launching new activity?

I'm on 4.4.2, and calling overridePendingTransition(0, 0) in the launching activity's onCreate() will disable the starting animation (calling overridePendingTransition(0, 0) immediately after startActivity() did NOT work). As noted in another answer, calling overridePendingTransition(0, 0) after finish() disables the closing animation.

Btw, I found that setting the style with "android:windowAnimationStyle">@null (another answer mentioned here) caused a crash when my launching activity tried to set the action bar title. Debugging further, I discovered that somehow this causes window.hasFeature(Window.FEATURE_ACTION_BAR) to fail in the Activity's initActionBar().

how to attach url link to an image?

"How to attach url link to an image?"

You do it like this:

<a href="http://www.google.com"><img src="http://www.google.com/intl/en_ALL/images/logo.gif"/></a>

See it in action.

Settings to Windows Firewall to allow Docker for Windows to share drive

My C drive stopped being shared with Docker after a recent Windows 10 update. I was getting the same problem saying it was blocked by the Windows firewall when attempting to reshare it.

Looking through the above solutions, I found something that worked for me that is simpler than anything else I saw on this page. In Control Panel\All Control Panel Items\Network and Sharing Center, on the vEthernet (DockerNAT) connection, I unchecked the property File and Printer Sharing for Microsoft Networks and saved the setting. Then I checked the property again to reenable it and saved it again.

At this point, I was able to reshare the C drive in Docker settings. I have no idea why this worked but it was not a firewall problem, which already have an entry for DockerSmbMount.

How do I make a Docker container start automatically on system boot?

I have a similar issue running Linux systems. After the system was booted, a container with a restart policy of "unless-stopped" would not restart automatically unless I typed a command that used docker in some way such as "docker ps". I was surprised as I expected that command to just report some status information. Next I tried the command "systemctl status docker". On a system where no docker commands had been run, this command reported the following:

? docker.service - Docker Application Container Engine

   Loaded: loaded (/lib/systemd/system/docker.service; disabled; vendor preset: enabled)

     Active: inactive (dead)    TriggeredBy: ? docker.socket
       Docs: https://docs.docker.com

On a system where "docker ps" had been run with no other Docker commands, I got the following:

? docker.service - Docker Application Container Engine
    Loaded: loaded (/lib/systemd/system/docker.service; disabled; vendor preset: enabled)

    Active: active (running) since Sun 2020-11-22 08:33:23 PST; 1h 25min ago

TriggeredBy: ? docker.socket
       Docs: https://docs.docker.com

   Main PID: 3135 (dockerd)
      Tasks: 13

    Memory: 116.9M
     CGroup: /system.slice/docker.service
             +-3135 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
 ... [various messages not shown ]

The most likely explanation is that Docker waits for some docker command before fully initializing and starting containers. You could presumably run "docker ps" in a systemd unit file at a point after all the services your containers need have been initialized. I've tested this by putting a file named docker-onboot.service in the directory /lib/systemd/system with the following contents:

[Unit]
# This service is provided to force Docker containers
# that should automatically restart to restart when the system
# is booted. While the Docker daemon will start automatically,
# it will not be fully initialized until some Docker command
# is actually run.  This unit merely runs "docker ps": any
# Docker command will result in the Docker daemon completing
# its initialization, at which point all containers that can be
# automatically restarted after booting will be restarted.
#
Description=Docker-Container Startup on Boot
Requires=docker.socket
After=docker.socket network-online.target containerd.service

[Service]
Type=oneshot
ExecStart=/usr/bin/docker ps

[Install]

WantedBy=multi-user.target

So far (one test, with this service enabled), the container started when the computer was booted. I did not try a dependency on docker.service because docker.service won't start until a docker command is run. The next test will be with the docker-onboot disabled (to see if the WantedBy dependency will automatically start it).

How are zlib, gzip and zip related? What do they have in common and how are they different?

The most important difference is that gzip is only capable to compress a single file while zip compresses multiple files one by one and archives them into one single file afterwards. Thus, gzip comes along with tar most of the time (there are other possibilities, though). This comes along with some (dis)advantages.

If you have a big archive and you only need one single file out of it, you have to decompress the whole gzip file to get to that file. This is not required if you have a zip file.

On the other hand, if you compress 10 similiar or even identical files, the zip archive will be much bigger because each file is compressed individually, whereas in gzip in combination with tar a single file is compressed which is much more effective if the files are similiar (equal).

The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

Here's an incredibly generic version that I've built from a combination of the previous suggestions:

public static <T> String buildCommaSeparatedString(Collection<T> values) {
    if (values==null || values.isEmpty()) return "";
    StringBuilder result = new StringBuilder();
    for (T val : values) {
        result.append(val);
        result.append(",");
    }
    return result.substring(0, result.length() - 1);
}

Strip off URL parameter with PHP

parse_str($queryString, $vars);
unset($vars['return']);
$queryString = http_build_query($vars);

parse_str parses a query string, http_build_query creates a query string.

Is there a bash command which counts files?

Here's what I always do:

ls log* | awk 'END{print NR}'

How do I get formatted JSON in .NET using C#?

Oneliner using Newtonsoft.Json.Linq:

string prettyJson = JToken.Parse(uglyJsonString).ToString(Formatting.Indented);

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

No, a List<Dog> is not a List<Animal>. Consider what you can do with a List<Animal> - you can add any animal to it... including a cat. Now, can you logically add a cat to a litter of puppies? Absolutely not.

// Illegal code - because otherwise life would be Bad
List<Dog> dogs = new ArrayList<Dog>(); // ArrayList implements List
List<Animal> animals = dogs; // Awooga awooga
animals.add(new Cat());
Dog dog = dogs.get(0); // This should be safe, right?

Suddenly you have a very confused cat.

Now, you can't add a Cat to a List<? extends Animal> because you don't know it's a List<Cat>. You can retrieve a value and know that it will be an Animal, but you can't add arbitrary animals. The reverse is true for List<? super Animal> - in that case you can add an Animal to it safely, but you don't know anything about what might be retrieved from it, because it could be a List<Object>.

groovy: safely find a key in a map and return its value

In general, this depends what your map contains. If it has null values, things can get tricky and containsKey(key) or get(key, default) should be used to detect of the element really exists. In many cases the code can become simpler you can define a default value:

def mymap = [name:"Gromit", likes:"cheese", id:1234]
def x1 = mymap.get('likes', '[nothing specified]')
println "x value: ${x}" }

Note also that containsKey() or get() are much faster than setting up a closure to check the element mymap.find{ it.key == "likes" }. Using closure only makes sense if you really do something more complex in there. You could e.g. do this:

mymap.find{ // "it" is the default parameter
  if (it.key != "likes") return false
  println "x value: ${it.value}" 
  return true // stop searching
}

Or with explicit parameters:

mymap.find{ key,value ->
  (key != "likes")  return false
  println "x value: ${value}" 
  return true // stop searching
}

MSSQL Select statement with incremental integer column... not from a table

For SQL 2005 and up

SELECT ROW_NUMBER() OVER( ORDER BY SomeColumn ) AS 'rownumber',*
    FROM YourTable

for 2000 you need to do something like this

SELECT IDENTITY(INT, 1,1) AS Rank ,VALUE
INTO #Ranks FROM YourTable WHERE 1=0

INSERT INTO #Ranks
SELECT SomeColumn  FROM YourTable
ORDER BY SomeColumn 

SELECT * FROM #Ranks
Order By Ranks

see also here Row Number

Passing string parameter in JavaScript function

Rename your variable name to myname, bacause name is a generic property of window and is not writable in the same window.

And replace

onclick='myfunction(\''" + name + "'\')'

With

onclick='myfunction(myname)'

Working example:

_x000D_
_x000D_
var myname = "Mathew";_x000D_
document.write('<button id="button" type="button" onclick="myfunction(myname);">click</button>');_x000D_
function myfunction(name) {_x000D_
    alert(name);_x000D_
}
_x000D_
_x000D_
_x000D_

How to get html to print return value of javascript function?

There are some options to do that.

One would be:

document.write(produceMessage())

Other would be appending some element in your document this way:

var span = document.createElement("span");
span.appendChild(document.createTextNode(produceMessage()));
document.body.appendChild(span);

Or just:

document.body.appendChild(document.createTextNode(produceMessage()));

If you're using jQuery, you can do this:

$(document.body).append(produceMessage());

Iterate through the fields of a struct in Go

After you've retrieved the reflect.Value of the field by using Field(i) you can get a interface value from it by calling Interface(). Said interface value then represents the value of the field.

There is no function to convert the value of the field to a concrete type as there are, as you may know, no generics in go. Thus, there is no function with the signature GetValue() T with T being the type of that field (which changes of course, depending on the field).

The closest you can achieve in go is GetValue() interface{} and this is exactly what reflect.Value.Interface() offers.

The following code illustrates how to get the values of each exported field in a struct using reflection (play):

import (
    "fmt"
    "reflect"
)

func main() {
    x := struct{Foo string; Bar int }{"foo", 2}

    v := reflect.ValueOf(x)

    values := make([]interface{}, v.NumField())

    for i := 0; i < v.NumField(); i++ {
        values[i] = v.Field(i).Interface()
    }

    fmt.Println(values)
}

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

convert iso date to milliseconds in javascript

var date = new Date()
console.log(" Date in MS last three digit = "+  date.getMilliseconds())
console.log(" MS = "+ Date.now())

Using this we can get date in milliseconds

How to run an external program, e.g. notepad, using hyperlink?

Sorry this answer sucks, but you can't launch an just any external application via a click, as this would be a serious security issue, this functionality isn't available in HTML or javascript. Think of just launching cmd.exe with args...you want to launch WinMerge with arguments, but you can see the security problems introduced by allowing this for anything.

The only possibly viable exception I can think of would be a protocol handler (since these are explicitly defined handlers), like winmerge://, though the best way to pass 2 file parameters I'm not sure of, if it's an option it's worth looking into, but I'm not sure what you are or are not allowed to do to the client, so this may be a non-starter solution.

To delay JavaScript function call using jQuery

Very easy, just call the function within a specific amount of milliseconds using setTimeout()

setTimeout(myFunction, 2000)

function myFunction() {
    alert('Was called after 2 seconds');
}

Or you can even initiate the function inside the timeout, like so:

setTimeout(function() {
    alert('Was called after 2 seconds');
}, 2000)