Programs & Examples On #Office 2003

Questions about Office 2003 should relate to a specific programming problem. Add the tag for the programming language you are using to target an Office 2003 program, as well as the tag of the specific Office 2003 program.

Call a VBA Function into a Sub Procedure

Procedures in a Module start being useful and generic when you pass in arguments.

For example:

Public Function DoSomethingElse(strMessage As String)  
    MsgBox strMessage
End Function

Can now display any message that is passed in with the string variable called strMessage.

"commence before first target. Stop." error

if you have added a new line, Make sure you have added next line syntax in previous line. typically if "\" is missing in your previous line of changes, you will get this error.

Insert HTML with React Variable Statements (JSX)

import { Fragment } from 'react' // react version > 16.0

var thisIsMyCopy = (
  <Fragment>
    <p>copy copy copy&nbsp;
    <strong>strong copy</strong>
    </p>
  </Fragment>
)

By using '' the sets the value to a string and React has no way of knowing that it is a HTML element. You can do the following to let React know it is a HTML element -

  1. Remove the '' and it would work
  2. Use <Fragment> to return a HTML element.

How to TryParse for Enum value?

Enum.IsDefined will get things done. It may not be as efficient as a TryParse would probably be, but it will work without exception handling.

public static TEnum ToEnum<TEnum>(this string strEnumValue, TEnum defaultValue)
{
    if (!Enum.IsDefined(typeof(TEnum), strEnumValue))
        return defaultValue;

    return (TEnum)Enum.Parse(typeof(TEnum), strEnumValue);
}

Worth noting: a TryParse method was added in .NET 4.0.

Finding all positions of substring in a larger string in C#

I found this example and incorporated it into a function:

    public static int solution1(int A, int B)
    {
        // Check if A and B are in [0...999,999,999]
        if ( (A >= 0 && A <= 999999999) && (B >= 0 && B <= 999999999))
        {
            if (A == 0 && B == 0)
            {
                return 0;
            }
            // Make sure A < B
            if (A < B)
            {                    
                // Convert A and B to strings
                string a = A.ToString();
                string b = B.ToString();
                int index = 0;

                // See if A is a substring of B
                if (b.Contains(a))
                {
                    // Find index where A is
                    if (b.IndexOf(a) != -1)
                    {                            
                        while ((index = b.IndexOf(a, index)) != -1)
                        {
                            Console.WriteLine(A + " found at position " + index);
                            index++;
                        }
                        Console.ReadLine();
                        return b.IndexOf(a);
                    }
                    else
                        return -1;
                }
                else
                {
                    Console.WriteLine(A + " is not in " + B + ".");
                    Console.ReadLine();

                    return -1;
                }
            }
            else
            {
                Console.WriteLine(A + " must be less than " + B + ".");
               // Console.ReadLine();

                return -1;
            }                
        }
        else
        {
            Console.WriteLine("A or B is out of range.");
            //Console.ReadLine();

            return -1;
        }
    }

    static void Main(string[] args)
    {
        int A = 53, B = 1953786;
        int C = 78, D = 195378678;
        int E = 57, F = 153786;

        solution1(A, B);
        solution1(C, D);
        solution1(E, F);

        Console.WriteLine();
    }

Returns:

53 found at position 2

78 found at position 4
78 found at position 7

57 is not in 153786

SimpleDateFormat parse loses timezone

OP's solution to his problem, as he says, has dubious output. That code still shows confusion about representations of time. To clear up this confusion, and make code that won't lead to wrong times, consider this extension of what he did:

public static void _testDateFormatting() {
    SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));
    SimpleDateFormat sdfGMT2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
    sdfGMT2.setTimeZone(TimeZone.getTimeZone("GMT"));

    SimpleDateFormat sdfLocal1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    SimpleDateFormat sdfLocal2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");

    try {
        Date d = new Date();
        String s1 = d.toString();
        String s2 = sdfLocal1.format(d);
        // Store s3 or s4 in database.
        String s3 = sdfGMT1.format(d);
        String s4 = sdfGMT2.format(d);
        // Retrieve s3 or s4 from database, using LOCAL sdf.
        String s5 = sdfLocal1.parse(s3).toString();
        //EXCEPTION String s6 = sdfLocal2.parse(s3).toString();
        String s7 = sdfLocal1.parse(s4).toString();
        String s8 = sdfLocal2.parse(s4).toString();
        // Retrieve s3 from database, using GMT sdf.
        // Note that this is the SAME sdf that created s3.
        Date d2 = sdfGMT1.parse(s3);
        String s9 = d2.toString();
        String s10 = sdfGMT1.format(d2);
        String s11 = sdfLocal2.format(d2);
    } catch (Exception e) {
        e.printStackTrace();
    }       
}

examining values in a debugger:

s1  "Mon Sep 07 06:11:53 EDT 2015" (id=831698113128)    
s2  "2015.09.07 06:11:53" (id=831698114048) 
s3  "2015.09.07 10:11:53" (id=831698114968) 
s4  "2015.09.07 10:11:53 GMT+00:00" (id=831698116112)   
s5  "Mon Sep 07 10:11:53 EDT 2015" (id=831698116944)    
s6  -- omitted, gave parse exception    
s7  "Mon Sep 07 10:11:53 EDT 2015" (id=831698118680)    
s8  "Mon Sep 07 06:11:53 EDT 2015" (id=831698119584)    
s9  "Mon Sep 07 06:11:53 EDT 2015" (id=831698120392)    
s10 "2015.09.07 10:11:53" (id=831698121312) 
s11 "2015.09.07 06:11:53 EDT" (id=831698122256) 

sdf2 and sdfLocal2 include time zone, so we can see what is really going on. s1 & s2 are at 06:11:53 in zone EDT. s3 & s4 are at 10:11:53 in zone GMT -- equivalent to the original EDT time. Imagine we save s3 or s4 in a data base, where we are using GMT for consistency, so we can have times from anywhere in the world, without storing different time zones.

s5 parses the GMT time, but treats it as a local time. So it says "10:11:53" -- the GMT time -- but thinks it is 10:11:53 in local time. Not good.

s7 parses the GMT time, but ignores the GMT in the string, so still treats it as a local time.

s8 works, because now we include GMT in the string, and the local zone parser uses it to convert from one time zone to another.

Now suppose you don't want to store the zone, you want to be able to parse s3, but display it as a local time. The answer is to parse using the same time zone it was stored in -- so use the same sdf as it was created in, sdfGMT1. s9, s10, & s11 are all representations of the original time. They are all "correct". That is, d2 == d1. Then it is only a question of how you want to DISPLAY it. If you want to display what is stored in DB -- GMT time -- then you need to format it using a GMT sdf. Ths is s10.

So here is the final solution, if you don't want to explicitly store with " GMT" in the string, and want to display in GMT format:

public static void _testDateFormatting() {
    SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));

    try {
        Date d = new Date();
        String s3 = sdfGMT1.format(d);
        // Store s3 in DB.
        // ...
        // Retrieve s3 from database, using GMT sdf.
        Date d2 = sdfGMT1.parse(s3);
        String s10 = sdfGMT1.format(d2);
    } catch (Exception e) {
        e.printStackTrace();
    }       
}

What is the iPhone 4 user-agent?

Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7

How to import spring-config.xml of one project into spring-config.xml of another project?

A small variation of Sean's answer:

<import resource="classpath*:spring-config.xml" />

With the asterisk in order to spring search files 'spring-config.xml' anywhere in the classpath.

Another reference: Divide Spring configuration across multiple projects

Spring classpath prefix difference

MySQL SELECT DISTINCT multiple columns

can this help?

select 
(SELECT group_concat(DISTINCT a) FROM my_table) as a,
(SELECT group_concat(DISTINCT b) FROM my_table) as b,
(SELECT group_concat(DISTINCT c) FROM my_table) as c,
(SELECT group_concat(DISTINCT d) FROM my_table) as d

Add one year in current date PYTHON

Look at this:

#!/usr/bin/python

import datetime

def addYears(date, years):
    result = date + datetime.timedelta(366 * years)
    if years > 0:
        while result.year - date.year > years or date.month < result.month or date.day < result.day:
            result += datetime.timedelta(-1)
    elif years < 0:
        while result.year - date.year < years or date.month > result.month or date.day > result.day:
            result += datetime.timedelta(1)
    print "input: %s output: %s" % (date, result)
    return result

Example usage:

addYears(datetime.date(2012,1,1), -1)
addYears(datetime.date(2012,1,1), 0)
addYears(datetime.date(2012,1,1), 1)
addYears(datetime.date(2012,1,1), -10)
addYears(datetime.date(2012,1,1), 0)
addYears(datetime.date(2012,1,1), 10)

And output of this example:

input: 2012-01-01 output: 2011-01-01
input: 2012-01-01 output: 2012-01-01
input: 2012-01-01 output: 2013-01-01
input: 2012-01-01 output: 2002-01-01
input: 2012-01-01 output: 2012-01-01
input: 2012-01-01 output: 2022-01-01

How to create a numpy array of arbitrary length strings?

You could use the object data type:

>>> import numpy
>>> s = numpy.array(['a', 'b', 'dude'], dtype='object')
>>> s[0] += 'bcdef'
>>> s
array([abcdef, b, dude], dtype=object)

Clearing a string buffer/builder after loop

Already good answer there. Just add a benchmark result for StringBuffer and StringBuild performance difference use new instance in loop or use setLength(0) in loop.

The summary is: In a large loop

  • StringBuilder is much faster than StringBuffer
  • Create new StringBuilder instance in loop have no difference with setLength(0). (setLength(0) have very very very tiny advantage than create new instance.)
  • StringBuffer is slower than StringBuilder by create new instance in loop
  • setLength(0) of StringBuffer is extremely slower than create new instance in loop.

Very simple benchmark (I just manually changed the code and do different test ):

public class StringBuilderSpeed {
public static final char ch[] = new char[]{'a','b','c','d','e','f','g','h','i'};

public static void main(String a[]){
    int loopTime = 99999999;
    long startTime = System.currentTimeMillis();
    StringBuilder sb = new StringBuilder();
    for(int i = 0 ; i < loopTime; i++){
        for(char c : ch){
            sb.append(c);
        }
        sb.setLength(0);
    }
    long endTime = System.currentTimeMillis();
    System.out.println("Time cost: " + (endTime - startTime));
}

}

New StringBuilder instance in loop: Time cost: 3693, 3862, 3624, 3742

StringBuilder setLength: Time cost: 3465, 3421, 3557, 3408

New StringBuffer instance in loop: Time cost: 8327, 8324, 8284

StringBuffer setLength Time cost: 22878, 23017, 22894

Again StringBuilder setLength to ensure not my labtop got some issue to use such long for StringBuffer setLength :-) Time cost: 3448

Java 8: Difference between two LocalDateTime in multiple units

It should be simpler!

Duration.between(startLocalDateTime, endLocalDateTime).toMillis();

You can convert millis to whatever unit you like:

String.format("%d minutes %d seconds", 
  TimeUnit.MILLISECONDS.toMinutes(millis),
  TimeUnit.MILLISECONDS.toSeconds(millis) - 
  TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));

Laravel assets url

Besides put all your assets in the public folder, you can use the HTML::image() Method, and only needs an argument which is the path to the image, relative on the public folder, as well:

{{ HTML::image('imgs/picture.jpg') }}

Which generates the follow HTML code:

<img src="http://localhost:8000/imgs/picture.jpg">

The link to other elements of HTML::image() Method: http://laravel-recipes.com/recipes/185/generating-an-html-image-element

Tar a directory, but don't store full absolute paths in the archive

Found tar -cvf site1-$seqNumber.tar -C /var/www/ site1 as more friendlier solution than tar -cvf site1-$seqNumber.tar -C /var/www/site1 . (notice the . in the second solution) for the following reasons

  • Tar file name can be insignificant as the original folder is now an archive entry
  • Tar file name being insignificant to the content can now be used for other purposes like sequence numbers, periodical backup etc.

PHP Create and Save a txt file to root directory

fopen() will open a resource in the same directory as the file executing the command. In other words, if you're just running the file ~/test.php, your script will create ~/myText.txt.

This can get a little confusing if you're using any URL rewriting (such as in an MVC framework) as it will likely create the new file in whatever the directory contains the root index.php file.

Also, you must have correct permissions set and may want to test before writing to the file. The following would help you debug:

$fp = fopen("myText.txt","wb");
if( $fp == false ){
    //do debugging or logging here
}else{
    fwrite($fp,$content);
    fclose($fp);
}

Android Gradle Could not reserve enough space for object heap

in gradle.properties, you can even delete

org.gradle.jvmargs=-Xmx1536m

such lines or comment them out. Let android studio decide for it. When I ran into this same problem, none of above solutions worked for me. Commenting out this line in gradle.properties helped in solving that error.

What is the difference between user and kernel modes in operating systems?

A processor in a computer running Windows has two different modes: user mode and kernel mode. The processor switches between the two modes depending on what type of code is running on the processor. Applications run in user mode, and core operating system components run in kernel mode. While many drivers run in kernel mode, some drivers may run in user mode.

When you start a user-mode application, Windows creates a process for the application. The process provides the application with a private virtual address space and a private handle table. Because an application's virtual address space is private, one application cannot alter data that belongs to another application. Each application runs in isolation, and if an application crashes, the crash is limited to that one application. Other applications and the operating system are not affected by the crash.

In addition to being private, the virtual address space of a user-mode application is limited. A processor running in user mode cannot access virtual addresses that are reserved for the operating system. Limiting the virtual address space of a user-mode application prevents the application from altering, and possibly damaging, critical operating system data.

All code that runs in kernel mode shares a single virtual address space. This means that a kernel-mode driver is not isolated from other drivers and the operating system itself. If a kernel-mode driver accidentally writes to the wrong virtual address, data that belongs to the operating system or another driver could be compromised. If a kernel-mode driver crashes, the entire operating system crashes.

If you are a Windows user once go through this link you will get more.

Communication between user mode and kernel mode

How to check radio button is checked using JQuery?

Radio buttons are,

<input type="radio" id="radio_1" class="radioButtons" name="radioButton" value="1">
<input type="radio" id="radio_2" class="radioButtons" name="radioButton" value="2">

to check on click,

$('.radioButtons').click(function(){
    if($("#radio_1")[0].checked){
       //logic here
    }
});

How to communicate between Docker containers via "hostname"

Edit: After Docker 1.9, the docker network command (see below https://stackoverflow.com/a/35184695/977939) is the recommended way to achieve this.


My solution is to set up a dnsmasq on the host to have DNS record automatically updated: "A" records have the names of containers and point to the IP addresses of the containers automatically (every 10 sec). The automatic updating script is pasted here:

#!/bin/bash

# 10 seconds interval time by default
INTERVAL=${INTERVAL:-10}

# dnsmasq config directory
DNSMASQ_CONFIG=${DNSMASQ_CONFIG:-.}

# commands used in this script
DOCKER=${DOCKER:-docker}
SLEEP=${SLEEP:-sleep}
TAIL=${TAIL:-tail}

declare -A service_map

while true
do
    changed=false
    while read line
    do
        name=${line##* }
        ip=$(${DOCKER} inspect --format '{{.NetworkSettings.IPAddress}}' $name)
        if [ -z ${service_map[$name]} ] || [ ${service_map[$name]} != $ip ] # IP addr changed
        then
            service_map[$name]=$ip
            # write to file
            echo $name has a new IP Address $ip >&2
            echo "host-record=$name,$ip"  > "${DNSMASQ_CONFIG}/docker-$name"
            changed=true
        fi
    done < <(${DOCKER} ps | ${TAIL} -n +2)

    # a change of IP address occured, restart dnsmasq
    if [ $changed = true ]
    then
        systemctl restart dnsmasq
    fi

    ${SLEEP} $INTERVAL
done

Make sure your dnsmasq service is available on docker0. Then, start your container with --dns HOST_ADDRESS to use this mini dns service.

Reference: http://docs.blowb.org/setup-host/dnsmasq.html

Array functions in jQuery

Have a look at https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/Array for documentation on JavaScript Arrays.
jQuery is a library which adds some magic to JavaScript which is a capable and featurefull scripting language. The libraries just fill in the gaps - get to know the core!

How do I get the total number of unique pairs of a set in the database?

TLDR; The formula is n(n-1)/2 where n is the number of items in the set.

Explanation:

To find the number of unique pairs in a set, where the pairs are subject to the commutative property (AB = BA), you can calculate the summation of 1 + 2 + ... + (n-1) where n is the number of items in the set.

The reasoning is as follows, say you have 4 items:

A
B
C
D

The number of items that can be paired with A is 3, or n-1:

AB
AC
AD

It follows that the number of items that can be paired with B is n-2 (because B has already been paired with A):

BC
BD

and so on...

(n-1) + (n-2) + ... + (n-(n-1))

which is the same as

1 + 2 + ... + (n-1)

or

n(n-1)/2

How to use export with Python on Linux

One line solution:

eval `python -c 'import sysconfig;print("python_include_path={0}".format(sysconfig.get_path("include")))'`
echo $python_include_path  # prints /home/<usr>/anaconda3/include/python3.6m" in my case

Breakdown:

Python call

python -c 'import sysconfig;print("python_include_path={0}".format(sysconfig.get_path("include")))'

It's launching a python script that

  1. imports sysconfig
  2. gets the python include path corresponding to this python binary (use "which python" to see which one is being used)
  3. prints the script "python_include_path={0}" with {0} being the path from 2

Eval call

eval `python -c 'import sysconfig;print("python_include_path={0}".format(sysconfig.get_path("include")))'`

It's executing in the current bash instance the output from the python script. In my case, its executing:

python_include_path=/home/<usr>/anaconda3/include/python3.6m

In other words, it's setting the environment variable "python_include_path" with that path for this shell instance.

Inspired by: http://blog.tintoy.io/2017/06/exporting-environment-variables-from-python-to-bash/

Draw a connecting line between two elements

Cytoscape supports this with its Architecture example which supports dragging elements.

For creating connections, there is the edgehandles extension. It does not yet support editing existing connections. Question.

For editing connection shapes, there is the edge-editing extension. Demo.

The edit-editation extension seems promising, however there is no demo yet.

javascript get child by id

This works well:

function test(el){
  el.childNodes.item("child").style.display = "none";
}

If the argument of item() function is an integer, the function will treat it as an index. If the argument is a string, then the function searches for name or ID of element.

How to copy a row and insert in same table with a autoincrement field in MySQL?

insert into MyTable(field1, field2, id_backup)
    select field1, field2, uniqueId from MyTable where uniqueId = @Id;

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

If the other solutions here do not work, make sure you are not in 'offline' mode. If enabled, android will not download the required files and you will get this error.

enter image description here

How to determine whether an object has a given property in JavaScript

Why not simply:

if (typeof myObject.myProperty == "undefined") alert("myProperty is not defined!");

Or if you expect a specific type:

if (typeof myObject.myProperty != "string") alert("myProperty has wrong type or does not exist!");

C++: what regex library should I use?

C++ has a builtin regex library since TR1. AFAIK Boost's regex library is very compatible with it and can be used as a replacement, if your standard library doesn't provide TR1.

SOAP request to WebService with java

When the WSDL is available, it is just two steps you need to follow to invoke that web service.

Step 1: Generate the client side source from a WSDL2Java tool

Step 2: Invoke the operation using:

YourService service = new YourServiceLocator();
Stub stub = service.getYourStub();
stub.operation();

If you look further, you will notice that the Stub class is used to invoke the service deployed at the remote location as a web service. When invoking that, your client actually generates the SOAP request and communicates. Similarly the web service sends the response as a SOAP. With the help of a tool like Wireshark, you can view the SOAP messages exchanged.

However since you have requested more explanation on the basics, I recommend you to refer here and write a web service with it's client to learn it further.

python time + timedelta equivalent

You can change time() to now() for it to work

from datetime import datetime, timedelta
datetime.now() + timedelta(hours=1)

java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

Eclipse failed to connect to SVN https repositories (should also apply to any app using SSL/TLS).

svn: E175002: Connection has been shutdown: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: Certificates does not conform to algorithm constraints

The issue was caused by latest Java 8 OpenJDK update that disabled MD5 related algorithms. As a workaround until new certificates are issued (if ever), change the following keys at java.security file

WARNING
Keep in mind that this could have security implications as disabled algorithms are considered weak. As an alternative, the workaround can be applied on a JVM basis by a command line option to use an external java.security file with this changes, e.g.:
java -Djava.security.properties=/etc/sysconfig/noMD5.java.security
For Eclipse, add a line on eclipse.ini below -vmargs
-Djava.security.properties=/etc/sysconfig/noMD5.java.security

original keys

jdk.certpath.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
jdk.tls.disabledAlgorithms=SSLv3, RC4, MD5withRSA, DH keySize < 768

change to

jdk.certpath.disabledAlgorithms=MD2, RSA keySize < 1024
jdk.tls.disabledAlgorithms=SSLv3, RC4, DH keySize < 768

java.security file is located in linux 64 at /usr/lib64/jvm/java/jre/lib/security/java.security

Calling startActivity() from outside of an Activity?

When you want to open an activity within your app then you can call the startActivity() method with an Intent as parameter. That intent would be the activity that you want to open. First you have to create an object of that intent with first parameter to be the context and second parameter to be the targeted activity class.

Intent intent = new Intent(this, Activity_a.class);
startActivity(intent);

Hope this will help.

What is the difference between "long", "long long", "long int", and "long long int" in C++?

long is equivalent to long int, just as short is equivalent to short int. A long int is a signed integral type that is at least 32 bits, while a long long or long long int is a signed integral type is at least 64 bits.

This doesn't necessarily mean that a long long is wider than a long. Many platforms / ABIs use the LP64 model - where long (and pointers) are 64 bits wide. Win64 uses the LLP64, where long is still 32 bits, and long long (and pointers) are 64 bits wide.

There's a good summary of 64-bit data models here.

long double doesn't guarantee much other than it will be at least as wide as a double.

Check if SQL Connection is Open or Closed

To check the database connection state you can just simple do the following

if(con.State == ConnectionState.Open){}

Find object by id in an array of JavaScript objects

Using native Array.reduce

var array = [ {'id':'73' ,'foo':'bar'} , {'id':'45' ,'foo':'bar'} , ];
var id = 73;
var found = array.reduce(function(a, b){
    return (a.id==id && a) || (b.id == id && b)
});

returns the object element if found, otherwise false

How to hide the keyboard when I press return key in a UITextField?

Try this,

[textField setDelegate: self];

Then, in textField delegate method

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

I had the same problem but from IIS in visual studio, I went to project properties -> Web -> and project url change http to https

Display the current date and time using HTML and Javascript with scrollable effects in hta application

This will help you.

Javascript

debugger;
var today = new Date();
document.getElementById('date').innerHTML = today

Fiddle Demo

Can an AWS Lambda function call another

In java, we can do as follows :

AWSLambdaAsync awsLambdaAsync = AWSLambdaAsyncClientBuilder.standard().withRegion("us-east-1").build();

InvokeRequest invokeRequest = new InvokeRequest();
invokeRequest.withFunctionName("youLambdaFunctionNameToCall").withPayload(payload);

InvokeResult invokeResult = awsLambdaAsync.invoke(invokeRequest); 

Here, payload is your stringified java object which needs to be passed as Json object to another lambda in case you need to pass some information from calling lambda to called lambda.

Getting the parent of a directory in Bash

Just use echo $(cd ../ && pwd) while working in the directory whose parent dir you want to find out. This chain also has the added benefit of not having trailing slashes.

How to use "not" in xpath?

Use boolean function like below:

//a[(contains(@id, 'xx'))=false]

How do I break a string in YAML over multiple lines?

1. Block Notation(plain, flow-style, scalar): Newlines become spaces and extra newlines after the block are removed

---
# Note: It has 1 new line after the string
content:
    Arbitrary free text
    over multiple lines stopping
    after indentation changes...

...

Equivalent JSON

{
 "content": "Arbitrary free text over multiple lines stopping after indentation changes..."
}

2. Literal Block Scalar: A Literal Block Scalar | will include the newlines and any trailing spaces. but removes extra

newlines after the block.

---
# After string we have 2 spaces and 2 new lines
content1: |
 Arbitrary free text
 over "multiple lines" stopping
 after indentation changes...  


...

Equivalent JSON

{
 "content1": "Arbitrary free text\nover \"multiple lines\" stopping\nafter indentation changes...  \n"
}

3. + indicator with Literal Block Scalar: keep extra newlines after block

---
# After string we have 2 new lines
plain: |+
 This unquoted scalar
 spans many lines.


...

Equivalent JSON

{
 "plain": "This unquoted scalar\nspans many lines.\n\n\n"
}

4. – indicator with Literal Block Scalar: means that the newline at the end of the string is removed.

---
# After string we have 2 new lines
plain: |-
 This unquoted scalar
 spans many lines.


...

Equivalent JSON

{
 "plain": "This unquoted scalar\nspans many lines."
}

5. Folded Block Scalar(>):

will fold newlines to spaces and but removes extra newlines after the block.

---
folded_newlines: >
 this is really a
 single line of text
 despite appearances


...

Equivalent JSON

{
 "fold_newlines": "this is really a single line of text despite appearances\n"
}

for more you can visit my Blog

How do I get an apk file from an Android device?

I've seen that many solutions to this problem either you have to root your phone or you have to install an app. Then after much googling I got this solution for non rooted/rooted phones.

To list which apps you got so far.

adb shell pm list packages

Then you may select an app, for instance twitter

adb backup -apk com.twitter.android

An important thing here is to not set up a password for encrypt your backup

This is going to create a file named as backup.ap, but you still can't open it. For this you got to extract it again but using the dd command.

dd if=backup.ab bs=24 skip=1 | openssl zlib -d > backup.tar

After this all you have to do is to extract the tar content and it's done.

Hope it works for you guys

How do you run JavaScript script through the Terminal?

Technically, Node.js isn't proper JavaScript as we know it, since there isn't a Document Object Model (DOM). For instance, JavaScript scripts that run in the browser will not work. At all. The solution would be to run JavaScript with a headless browser. Fortunately there is a project still active: Mozilla Firefox has a headless mode.

https://developer.mozilla.org/en-US/docs/Mozilla/Firefox/Headless_mode

$ /Applications/Firefox.app/Contents/MacOS/firefox -headless index.html
*** You are running in headless mode.

What are the uses of "using" in C#?

Just adding a little something that I was surprised did not come up. The most interesting feature of using (in my opinion) is that no mater how you exit the using block, it will always dispose the object. This includes returns and exceptions.

using (var db = new DbContext())
{
    if(db.State == State.Closed) throw new Exception("Database connection is closed.");
    return db.Something.ToList();
}

It doesn't matter if the exception is thrown or the list is returned. The DbContext object will always be disposed.

Getting Lat/Lng from Google marker

There are a lot of answers to this question, which never worked for me (including suggesting getPosition() which doesn't seem to be a method available for markers objects). The only method that worked for me in maps V3 is (simply) :

var lat = marker.lat();
var long = marker.lng();

How can I get a value from a map?

How can I get the value from the map, which is passed as a reference to a function?

Well, you can pass it as a reference. The standard reference wrapper that is.

typedef std::map<std::string, std::string> MAP;
// create your map reference type
using map_ref_t = std::reference_wrapper<MAP>;

// use it 
void function(map_ref_t map_r)
{
    // get to the map from inside the
    // std::reference_wrapper
    // see the alternatives behind that link
    MAP & the_map = map_r;
    // take the value from the map
    // by reference
    auto & value_r = the_map["key"];
    // change it, "in place"
    value_r = "new!";
}

And the test.

    void test_ref_to_map() {

    MAP valueMap;
    valueMap["key"] = "value";
    // pass it by reference
    function(valueMap);
    // check that the value has changed
    assert( "new!" == valueMap["key"] );
}

I think this is nice and simple. Enjoy ...

How to get featured image of a product in woocommerce

In WC 3.0+ versions the image can get by below code.

$image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $item->get_product_id() ), 'single-post-thumbnail' );
echo $image_url[0]

How to set the part of the text view is clickable

Here is a Kotlin method to make parts of a TextView clickable:

private fun makeTextLink(textView: TextView, str: String, underlined: Boolean, color: Int?, action: (() -> Unit)? = null) {
    val spannableString = SpannableString(textView.text)
    val textColor = color ?: textView.currentTextColor
    val clickableSpan = object : ClickableSpan() {
        override fun onClick(textView: View) {
            action?.invoke()
        }
        override fun updateDrawState(drawState: TextPaint) {
            super.updateDrawState(drawState)
            drawState.isUnderlineText = underlined
            drawState.color = textColor
        }
    }
    val index = spannableString.indexOf(str)
    spannableString.setSpan(clickableSpan, index, index + str.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    textView.text = spannableString
    textView.movementMethod = LinkMovementMethod.getInstance()
    textView.highlightColor = Color.TRANSPARENT
}

It can be called multiple times to create several links within a TextView:

makeTextLink(myTextView, str, false, Color.RED, action = { Log.d("onClick", "link") })
makeTextLink(myTextView, str1, true, null, action = { Log.d("onClick", "link1") })

What is the difference between fastcgi and fpm?

What Anthony says is absolutely correct, but I'd like to add that your experience will likely show a lot better performance and efficiency (due not to fpm-vs-fcgi but more to the implementation of your httpd).

For example, I had a quad-core machine running lighttpd + fcgi humming along nicely. I upgraded to a 16-core machine to cope with growth, and two things exploded: RAM usage, and segfaults. I found myself restarting lighttpd every 30 minutes to keep the website up.

I switched to php-fpm and nginx, and RAM usage dropped from >20GB to 2GB. Segfaults disappeared as well. After doing some research, I learned that lighttpd and fcgi don't get along well on multi-core machines under load, and also have memory leak issues in certain instances.

Is this due to php-fpm being better than fcgi? Not entirely, but how you hook into php-fpm seems to be a whole heckuva lot more efficient than how you serve via fcgi.

Wampserver icon not going green fully, mysql services not starting up?

I had the same problem. Mysql didn't start.

  1. go to services.
  2. right click the wampmysqld go to properties.
  3. startup type select manual.
  4. right click and click start service.

worked for me.

The import javax.persistence cannot be resolved

My solution was to select the maven profiles I had defined in my pom.xml in which I had declared the hibernate dependencies.

CTRL + ALT + P in eclipse.

In my project I was experiencing this problem and many others because in my pom I have different profiles for supporting Glassfish 3, Glassfish 4 and also WildFly so I have differet versions of Hibernate per container as well as different Java compilation targets and so on. Selecting the active maven profiles resolved my issue.

SQL Server convert string to datetime

For instance you can use

update tablename set datetimefield='19980223 14:23:05'
update tablename set datetimefield='02/23/1998 14:23:05'
update tablename set datetimefield='1998-12-23 14:23:05'
update tablename set datetimefield='23 February 1998 14:23:05'
update tablename set datetimefield='1998-02-23T14:23:05'

You need to be careful of day/month order since this will be language dependent when the year is not specified first. If you specify the year first then there is no problem; date order will always be year-month-day.

Getting Data from Android Play Store

There's an unofficial open-source API for the Android Market you may try to use to get the information you need. Hope this helps.

C# importing class into another class doesn't work

I know this is very old question but I had the same requirement and just discovered that after c#6 you can use static in using for classes to import.

I hope this helps someone....

using static yourNameSpace.YourClass;

Count words in a string method?

public static int countWords(String s){

    int wordCount = 0;

    boolean word = false;
    int endOfLine = s.length() - 1;

    for (int i = 0; i < s.length(); i++) {
        // if the char is a letter, word = true.
        if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
            word = true;
            // if char isn't a letter and there have been letters before,
            // counter goes up.
        } else if (!Character.isLetter(s.charAt(i)) && word) {
            wordCount++;
            word = false;
            // last word of String; if it doesn't end with a non letter, it
            // wouldn't count without this.
        } else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
            wordCount++;
        }
    }
    return wordCount;
}

How to view DLL functions?

If a DLL is written in one of the .NET languages and if you only want to view what functions, there is a reference to this DLL in the project.

Then doubleclick the DLL in the references folder and then you will see what functions it has in the OBJECT EXPLORER window

If you would like to view the source code of that DLL file you can use a decompiler application such as .NET reflector. hope this helps you.

Image convert to Base64

_x000D_
_x000D_
// https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL

/* Simple */
function previewImage( image, preview, string )
{

    var preview     = document.querySelector( preview );
    var fileImage   = image.files[0];

    var reader      = new FileReader();

    reader.addEventListener( "load", function() {

        preview.style.height    = "100";
        preview.title           = fileImage.name;

        // convert image file to base64 string
        preview.src             = reader.result;

        /* --- */

        document.querySelector( string ).value = reader.result;                    

    }, false );

    if ( fileImage )
    {
        reader.readAsDataURL( fileImage );
    }

}

document.querySelector( "#imageID" ).addEventListener( "change", function() {

    previewImage( this, "#imagePreviewID", "#imageStringID" );

} )
/* Simple || */
_x000D_
<form>

    File Upload: <input type="file" id="imageID" /><br />
    Preview: <img src="#" id="imagePreviewID" /><br />    
    String base64: <textarea id="imageStringID" rows="10" cols="50"></textarea>

</form>
_x000D_
_x000D_
_x000D_

codesanbox

Recursive directory listing in DOS

I like to use the following to get a nicely sorted listing of the current dir:

> dir . /s /b sortorder:N

Check if MySQL table exists or not

Updated mysqli version:

if ($result = $mysqli->query("SHOW TABLES LIKE '".$table."'")) {
    if($result->num_rows == 1) {
        echo "Table exists";
    }
}
else {
    echo "Table does not exist";
}

Original mysql version:

if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1) 
    echo "Table exists";
else echo "Table does not exist";

Referenced from the PHP docs.

Plotting images side by side using matplotlib

The problem you face is that you try to assign the return of imshow (which is an matplotlib.image.AxesImage to an existing axes object.

The correct way of plotting image data to the different axes in axarr would be

f, axarr = plt.subplots(2,2)
axarr[0,0].imshow(image_datas[0])
axarr[0,1].imshow(image_datas[1])
axarr[1,0].imshow(image_datas[2])
axarr[1,1].imshow(image_datas[3])

The concept is the same for all subplots, and in most cases the axes instance provide the same methods than the pyplot (plt) interface. E.g. if ax is one of your subplot axes, for plotting a normal line plot you'd use ax.plot(..) instead of plt.plot(). This can actually be found exactly in the source from the page you link to.

Making a Windows shortcut start relative to where the folder is?

The method that proposed by 'leoj' does not allow passing parameters with spaces. Us it:

    cmd.exe /v /c %CD:~0,2%"%CD:~2%\bat\bat\run.bat" "Par1-1 Par1-2" Par2

Which will be similar double quote written as in path

    C:"\Program Files\anyProgram.exe" "Par1-1 Par1-2" Par2

Mockito: InvalidUseOfMatchersException

I had the same problem for a long time now, I often needed to mix Matchers and values and I never managed to do that with Mockito.... until recently ! I put the solution here hoping it will help someone even if this post is quite old.

It is clearly not possible to use Matchers AND values together in Mockito, but what if there was a Matcher accepting to compare a variable ? That would solve the problem... and in fact there is : eq

when(recommendedAccessor.searchRecommendedHolidaysProduct(eq(metas), any(List.class), any(HotelsBoardBasisType.class), any(Config.class)))
            .thenReturn(recommendedResults);

In this example 'metas' is an existing list of values

Get source jar files attached to Eclipse for Maven-managed dependencies

I am sure m2eclipse Maven plugin for Eclipse - the other way around - can do that. You can configure it to download both the source files and javadoc automatically for you.

This is achieved by going into Window > Preferences > Maven and checking the "Download Artifact Sources" and "Download Artifact JavaDoc" options.

Screenshot of Maven Preferences

Left align and right align within div in Bootstrap

We can achieve by Bootstrap 4 Flexbox:

<div class="d-flex justify-content-between w-100">
<p>TotalCost</p> <p>$42</p>
</div>

d-flex // Display Flex
justify-content-between // justify-content:space-between
w-100 // width:100%

Example: JSFiddle

Set select option 'selected', by value

Use the change() event after selecting the value. From the docs:

If the field loses focus without the contents having changed, the event is not triggered. To trigger the event manually, apply .change() without arguments:

$("#select_id").val("val2").change();

More information is at .change().

Ansible: create a user with sudo privileges

Sometimes it's knowing what to ask. I didn't know as I am a developer who has taken on some DevOps work.

Apparently 'passwordless' or NOPASSWD login is a thing which you need to put in the /etc/sudoers file.

The answer to my question is at Ansible: best practice for maintaining list of sudoers.

The Ansible playbook code fragment looks like this from my problem:

- name: Make sure we have a 'wheel' group
  group:
    name: wheel
    state: present

- name: Allow 'wheel' group to have passwordless sudo
  lineinfile:
    dest: /etc/sudoers
    state: present
    regexp: '^%wheel'
    line: '%wheel ALL=(ALL) NOPASSWD: ALL'
    validate: 'visudo -cf %s'

- name: Add sudoers users to wheel group
  user:
    name=deployer
    groups=wheel
    append=yes
    state=present
    createhome=yes

- name: Set up authorized keys for the deployer user
  authorized_key: user=deployer key="{{item}}"
  with_file:
    - /home/railsdev/.ssh/id_rsa.pub

And the best part is that the solution is idempotent. It doesn't add the line

%wheel ALL=(ALL) NOPASSWD: ALL

to /etc/sudoers when the playbook is run a subsequent time. And yes...I was able to ssh into the server as "deployer" and run sudo commands without having to give a password.

Angular : Manual redirect to route

Angular routing : Manual navigation

First you need to import the angular router :

import {Router} from "@angular/router"

Then inject it in your component constructor :

constructor(private router: Router) { }

And finally call the .navigate method anywhere you need to "redirect" :

this.router.navigate(['/your-path'])

You can also put some parameters on your route, like user/5 :

this.router.navigate(['/user', 5])

Documentation: Angular official documentaiton

Get started with Latex on Linux

To get started with LaTeX on Linux, you're going to need to install a couple of packages:

  1. You're going to need a LaTeX distribution. This is the collection of programs that comprise the (La)TeX computer typesetting system. The standard LaTeX distribution on Unix systems used to be teTeX, but it has been superceded by TeX Live. Most Linux distributions have installation packages for TeX Live--see, for example, the package database entries for Ubuntu and Fedora.

  2. You will probably want to install a LaTeX editor. Standard Linux text editors will work fine; in particular, Emacs has a nice package of (La)TeX editing macros called AUCTeX. Specialized LaTeX editors also exist; of those, Kile (KDE Integrated LaTeX Environment) is particularly nice.

  3. You will probably want a LaTeX tutorial. The classic tutorial is "A (Not So) Short Introduction to LaTeX2e," but nowadays the LaTeX wikibook might be a better choice.

How do I position one image on top of another in HTML?

@buti-oxa: Not to be pedantic, but your code is invalid. The HTML width and height attributes do not allow for units; you're likely thinking of the CSS width: and height: properties. You should also provide a content-type (text/css; see Espo's code) with the <style> tag.

<style type="text/css"> 
.containerdiv { float: left; position: relative; } 
.cornerimage { position: absolute; top: 0; right: 0; } 
</style>

<div class="containerdiv">
    <img border="0" src="http://www.gravatar.com/avatar/" alt="" width="100" height="100">
    <img class="cornerimage" border="0" src="http://www.gravatar.com/avatar/" alt="" width="40" height="40">
<div>

Leaving px; in the width and height attributes might cause a rendering engine to balk.

Loading and parsing a JSON file with multiple JSON objects

That is ill-formatted. You have one JSON object per line, but they are not contained in a larger data structure (ie an array). You'll either need to reformat it so that it begins with [ and ends with ] with a comma at the end of each line, or parse it line by line as separate dictionaries.

What is the difference between single and double quotes in SQL?

I use this mnemonic:

  • Single quotes are for strings (one thing)
  • Double quotes are for tables names and column names (two things)

This is not 100% correct according to the specs, but this mnemonic helps me (human being).

Hosting a Maven repository on github

Don't use GitHub as a Maven Repository.

Edit: This option gets a lot of down votes, but no comments as to why. This is the correct option regardless of the technical capabilities to actually host on GitHub. Hosting on GitHub is wrong for all the reasons outlined below and without comments I can't improve the answer to clarify your issues.

Best Option - Collaborate with the Original Project

The best option is to convince the original project to include your changes and stick with the original.

Alternative - Maintain your own Fork

Since you have forked an open source library, and your fork is also open source, you can upload your fork to Maven Central (read Guide to uploading artifacts to the Central Repository) by giving it a new groupId and maybe a new artifactId.

Only consider this option if you are willing to maintain this fork until the changes are incorporated into the original project and then you should abandon this one.

Really consider hard whether a fork is the right option. Read the myriad Google results for 'why not to fork'

Reasoning

Bloating your repository with jars increases download size for no benefit

A jar is an output of your project, it can be regenerated at any time from its inputs, and your GitHub repo should contain only inputs.

Don't believe me? Then check Google results for 'dont store binaries in git'.

GitHub's help Working with large files will tell you the same thing. Admittedly jar's aren't large but they are larger than the source code and once a jar has been created by a release they have no reason to be versioned - that is what a new release is for.

Defining multiple repos in your pom.xml slows your build down by Number of Repositories times Number of Artifacts

Stephen Connolly says:

If anyone adds your repo they impact their build performance as they now have another repo to check artifacts against... It's not a big problem if you only have to add one repo... But the problem grows and the next thing you know your maven build is checking 50 repos for every artifact and build time is a dog.

That's right! Maven needs to check every artifact (and its dependencies) defined in your pom.xml against every Repository you have defined, as a newer version might be available in any of those repositories.

Try it out for yourself and you will feel the pain of a slow build.

The best place for artifacts is in Maven Central, as its the central place for jars, and this means your build will only ever check one place.

You can read some more about repositories at Maven's documentation on Introduction to Repositories

calling java methods in javascript code

Java is a server side language, whereas javascript is a client side language. Both cannot communicate. If you have setup some server side script using Java you could use AJAX on the client in order to send an asynchronous request to it and thus invoke any possible Java functions. For example if you use jQuery as js framework you may take a look at the $.ajax() method. Or if you wanted to do it using plain javascript, here's a tutorial.

Call external javascript functions from java code

try {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("JavaScript");
        System.out.println("okay1");
        FileInputStream fileInputStream = new FileInputStream("C:/Users/Kushan/eclipse-workspace/sureson.lk/src/main/webapp/js/back_end_response.js");
        System.out.println("okay2");
        if (fileInputStream != null){
         BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream));
         engine.eval(reader);
         System.out.println("okay3");
        // Invocable javascriptEngine = null;
         System.out.println("okay4");
        Invocable invocableEngine = (Invocable)engine;
         System.out.println("okay5");
         int x=0;
         System.out.println("invocableEngine is : "+invocableEngine);
         Object object = invocableEngine.invokeFunction("backend_message",x);

         System.out.println("okay6");
        }
        }catch(Exception e) {
            System.out.println("erroe when calling js function"+ e);
        }

Show a number to two decimal places

Another more exotic way to solve this issue is to use bcadd() with a dummy value for the $right_operand of 0.

$formatted_number = bcadd($number, 0, 2);

How do I set the time zone of MySQL?

If you're using PDO:

$offset="+10:00";
$db->exec("SET time_zone='".$offset."';");

If you're using MySQLi:

$db->MySQLi->query("SET time_zone='".$offset."';");

More about formatting the offset here: https://www.sitepoint.com/synchronize-php-mysql-timezone-configuration/

JavaScript - Hide a Div at startup (load)

Why not add "display: none;" to the divs style attribute? Thats all JQuery's .hide() function does.

Undefined symbols for architecture armv7

I had a similar issue with that. The class name after _OBJC_CLASS_$_ was actually my class. The reason was I didn't tick "Add to Target" when I drag the source code files into navigation list.

My solution was:

  1. delete the class from the navigation list and choose "remove reference only"

  2. drag the source code files again and make sure the tick box for "add to Target" is ticked. The tick box is just under "Copy if needed" and "Create group".

What is cURL in PHP?

Php curl class (GET,POST,FILES UPLOAD, SESSIONS, SEND POST JSON, FORCE SELFSIGNED SSL/TLS):

<?php
    // Php curl class
    class Curl {

        public $error;

        function __construct() {}

        function Get($url = "http://hostname.x/api.php?q=jabadoo&txt=gin", $forceSsl = false,$cookie = "", $session = true){
            // $url = $url . "?". http_build_query($data);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, false);        
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            if($session){
                curl_setopt($ch, CURLOPT_COOKIESESSION, true );
                curl_setopt($ch , CURLOPT_COOKIEJAR, 'cookies.txt');
                curl_setopt($ch , CURLOPT_COOKIEFILE, 'cookies.txt');
            }
            if($forceSsl){
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 1, 2
            }
            if(!empty($cookie)){            
                curl_setopt($ch, CURLOPT_COOKIE, $cookie); // "token=12345"
            }
            $info = curl_getinfo($ch);
            $res = curl_exec($ch);        
            if (curl_error($ch)) {
                $this->error = curl_error($ch);
                throw new Exception($this->error);
            }else{
                curl_close($ch);
                return $res;
            }        
        }

        function GetArray($url = "http://hostname.x/api.php", $data = array("name" => "Max", "age" => "36"), $forceSsl = false, $cookie = "", $session = true){
            $url = $url . "?". http_build_query($data);
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            if($session){
                curl_setopt($ch, CURLOPT_COOKIESESSION, true );
                curl_setopt($ch , CURLOPT_COOKIEJAR, 'cookies.txt');
                curl_setopt($ch , CURLOPT_COOKIEFILE, 'cookies.txt');
            }
            if($forceSsl){
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 1, 2
            }
            if(!empty($cookie)){
                curl_setopt($ch, CURLOPT_COOKIE, $cookie); // "token=12345"
            }
            $info = curl_getinfo($ch);
            $res = curl_exec($ch);        
            if (curl_error($ch)) {
                $this->error = curl_error($ch);
                throw new Exception($this->error);
            }else{
                curl_close($ch);
                return $res;
            }        
        }

        function PostJson($url = "http://hostname.x/api.php", $data = array("name" => "Max", "age" => "36"), $forceSsl = false, $cookie = "", $session = true){
            $data = json_encode($data);
            $ch = curl_init($url);                                                                      
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);                                                                  
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            if($session){
                curl_setopt($ch, CURLOPT_COOKIESESSION, true );
                curl_setopt($ch , CURLOPT_COOKIEJAR, 'cookies.txt');
                curl_setopt($ch , CURLOPT_COOKIEFILE, 'cookies.txt');
            }
            if($forceSsl){
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 1, 2
            }
            if(!empty($cookie)){
                curl_setopt($ch, CURLOPT_COOKIE, $cookie); // "token=12345"
            }
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Authorization: Bearer helo29dasd8asd6asnav7ffa',                                                      
                'Content-Type: application/json',                                                                                
                'Content-Length: ' . strlen($data))                                                                       
            );        
            $res = curl_exec($ch);
            if (curl_error($ch)) {
                $this->error = curl_error($ch);
                throw new Exception($this->error);
            }else{
                curl_close($ch);
                return $res;
            } 
        }

        function Post($url = "http://hostname.x/api.php", $data = array("name" => "Max", "age" => "36"), $files = array('ads/ads0.jpg', 'ads/ads1.jpg'), $forceSsl = false, $cookie = "", $session = true){
            foreach ($files as $k => $v) {
                $f = realpath($v);
                if(file_exists($f)){
                    $fc = new CurlFile($f, mime_content_type($f), basename($f)); 
                    $data["file[".$k."]"] = $fc;
                }
            }
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");        
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);    
            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); // !!!! required as of PHP 5.6.0 for files !!!
            curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)");
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            if($session){
                curl_setopt($ch, CURLOPT_COOKIESESSION, true );
                curl_setopt($ch , CURLOPT_COOKIEJAR, 'cookies.txt');
                curl_setopt($ch , CURLOPT_COOKIEFILE, 'cookies.txt');
            }
            if($forceSsl){
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 1, 2
            }
            if(!empty($cookie)){
                curl_setopt($ch, CURLOPT_COOKIE, $cookie); // "token=12345"
            }
            $res = curl_exec($ch);
            if (curl_error($ch)) {
                $this->error = curl_error($ch);
                throw new Exception($this->error);
            }else{
                curl_close($ch);
                return $res;
            } 
        }
    }
?>

Example:

<?php
    $urlget = "http://hostname.x/api.php?id=123&user=bax";
    $url = "http://hostname.x/api.php";
    $data = array("name" => "Max", "age" => "36");
    $files = array('ads/ads0.jpg', 'ads/ads1.jpg');

    $curl = new Curl();
    echo $curl->Get($urlget, true, "token=12345");
    echo $curl->GetArray($url, $data, true);
    echo $curl->Post($url, $data, $files, true);
    echo $curl->PostJson($url, $data, true);
?>

Php file: api.php

<?php
    /*
    $Cookie = session_get_cookie_params();
    print_r($Cookie);
    */
    session_set_cookie_params(9000, '/', 'hostname.x', isset($_SERVER["HTTPS"]), true);
    session_start();

    $_SESSION['cnt']++;
    echo "Session count: " . $_SESSION['cnt']. "\r\n";
    echo $json = file_get_contents('php://input');
    $arr = json_decode($json, true);
    echo "<pre>";
    if(!empty($json)){ print_r($arr); }
    if(!empty($_GET)){ print_r($_GET); }
    if(!empty($_POST)){ print_r($_POST); }
    if(!empty($_FILES)){ print_r($_FILES); }
    // request headers
    print_r(getallheaders());
    print_r(apache_response_headers());
    // Fetch a list of headers to be sent.
    // print_r(headers_list());
?>

What is the difference between association, aggregation and composition?

For two objects, Foo and Bar the relationships can be defined

Association - I have a relationship with an object. Foo uses Bar

public class Foo { 
    void Baz(Bar bar) {
    } 
};

Composition - I own an object and I am responsible for its lifetime. When Foo dies, so does Bar

public class Foo {
    private Bar bar = new Bar(); 
}

Aggregation - I have an object which I've borrowed from someone else. When Foo dies, Bar may live on.

public class Foo { 
    private Bar bar; 
    Foo(Bar bar) { 
       this.bar = bar; 
    }
}

./configure : /bin/sh^M : bad interpreter

If you are using TextMate or a similar programme, do save as, and then in encodings choose LF instead of CRLF.

How to auto generate migrations with Sequelize CLI from Sequelize models?

You cannot create migration scripts for existing models.

Resources:

If going the classic way, you'll have to recreate the models via the CLI:

sequelize model:create --name MyUser --attributes first_name:string,last_name:string,bio:text

It will generate these files:

models/myuser.js:

_x000D_
_x000D_
"use strict";_x000D_
module.exports = function(sequelize, DataTypes) {_x000D_
  var MyUser = sequelize.define("MyUser", {_x000D_
    first_name: DataTypes.STRING,_x000D_
    last_name: DataTypes.STRING,_x000D_
    bio: DataTypes.TEXT_x000D_
  }, {_x000D_
    classMethods: {_x000D_
      associate: function(models) {_x000D_
        // associations can be defined here_x000D_
      }_x000D_
    }_x000D_
  });_x000D_
  return MyUser;_x000D_
};
_x000D_
_x000D_
_x000D_

migrations/20150210104840-create-my-user.js:

_x000D_
_x000D_
"use strict";_x000D_
module.exports = {_x000D_
  up: function(migration, DataTypes, done) {_x000D_
    migration.createTable("MyUsers", {_x000D_
      id: {_x000D_
        allowNull: false,_x000D_
        autoIncrement: true,_x000D_
        primaryKey: true,_x000D_
        type: DataTypes.INTEGER_x000D_
      },_x000D_
      first_name: {_x000D_
        type: DataTypes.STRING_x000D_
      },_x000D_
      last_name: {_x000D_
        type: DataTypes.STRING_x000D_
      },_x000D_
      bio: {_x000D_
        type: DataTypes.TEXT_x000D_
      },_x000D_
      createdAt: {_x000D_
        allowNull: false,_x000D_
        type: DataTypes.DATE_x000D_
      },_x000D_
      updatedAt: {_x000D_
        allowNull: false,_x000D_
        type: DataTypes.DATE_x000D_
      }_x000D_
    }).done(done);_x000D_
  },_x000D_
  down: function(migration, DataTypes, done) {_x000D_
    migration.dropTable("MyUsers").done(done);_x000D_
  }_x000D_
};
_x000D_
_x000D_
_x000D_

Possible reason for NGINX 499 error codes

One of the reasons for this behaviour could be you are using http for uwsgi instead of socket. Use the below command if you are using uwsgi directly.

uwsgi --socket :8080 --module app-name.wsgi

Same command in .ini file is

chdir = /path/to/app/folder
socket = :8080
module = app-name.wsgi

shuffling/permutating a DataFrame in pandas

A simple solution in pandas is to use the sample method independently on each column. Use apply to iterate over each column:

df = pd.DataFrame({'a':[1,2,3,4,5,6], 'b':[1,2,3,4,5,6]})
df

   a  b
0  1  1
1  2  2
2  3  3
3  4  4
4  5  5
5  6  6

df.apply(lambda x: x.sample(frac=1).values)

   a  b
0  4  2
1  1  6
2  6  5
3  5  3
4  2  4
5  3  1

You must use .value so that you return a numpy array and not a Series, or else the returned Series will align to the original DataFrame not changing a thing:

df.apply(lambda x: x.sample(frac=1))

   a  b
0  1  1
1  2  2
2  3  3
3  4  4
4  5  5
5  6  6

How to shutdown my Jenkins safely?

You can also look in the init script area (e.g. centos vi /etc/init.d/jenkins ) for details on how the service is actually started and stopped.

How to create web service (server & Client) in Visual Studio 2012?

  1. Create a new empty Asp.NET Web Application.
  2. Solution Explorer right click on the project root.
  3. Choose the menu item Add-> Web Service

Hide options in a select list using jQuery

In reference to redsquare's suggestion, I ended up doing this:

var selectItems = $("#edit-field-service-sub-cat-value option[value=" + title + "]").detach();

and then to reverse this:

$("#edit-field-service-sub-cat-value").append(selectItems);

Wamp Server not goes to green color

You should also make sure that the ports WAMP uses aren't already in use.

That can be done by typing the following command into the command prompt:

netstat –o

ORA-01652: unable to extend temp segment by 128 in tablespace SYSTEM: How to extend?

Each tablespace has one or more datafiles that it uses to store data.

The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.

To find out if the actual limit is 32gb, run the following:

select value from v$parameter where name = 'db_block_size';

Compare the result you get with the first column below, and that will indicate what your max datafile size is.

I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).

Block Sz   Max Datafile Sz (Gb)   Max DB Sz (Tb)

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

   2,048                  8,192          524,264

   4,096                 16,384        1,048,528

   8,192                 32,768        2,097,056

  16,384                 65,536        4,194,112

  32,768                131,072        8,388,224

You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):

select bytes/1024/1024 as mb_size,
       maxbytes/1024/1024 as maxsize_set,
       x.*
from   dba_data_files x

MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).

If your datafile has a low max size or autoextend is not on you could simply run:

alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;

However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:

alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;

How to convert a string to integer in C?

Yes, you can store the integer directly:

int num = 45;

If you must parse a string, atoi or strol is going to win the "shortest amount of code" contest.

Auto-size dynamic text to fill fixed size container

This is the most elegant solution I have created. It uses binary search, doing 10 iterations. The naive way was to do a while loop and increase the font size by 1 until the element started to overflow. You can determine when an element begins to overflow using element.offsetHeight and element.scrollHeight. If scrollHeight is bigger than offsetHeight, you have a font size that is too big.

Binary search is a much better algorithm for this. It also is limited by the number of iterations you want to perform. Simply call flexFont and insert the div id and it will adjust the font size between 8px and 96px.

I have spent some time researching this topic and trying different libraries, but ultimately I think this is the easiest and most straightforward solution that will actually work.

Note if you want you can change to use offsetWidth and scrollWidth, or add both to this function.

// Set the font size using overflow property and div height
function flexFont(divId) {
    var content = document.getElementById(divId);
    content.style.fontSize = determineMaxFontSize(content, 8, 96, 10, 0) + "px";
};

// Use binary search to determine font size
function determineMaxFontSize(content, min, max, iterations, lastSizeNotTooBig) {
    if (iterations === 0) {
        return lastSizeNotTooBig;
    }
    var obj = fontSizeTooBig(content, min, lastSizeNotTooBig);

    // if `min` too big {....min.....max.....}
    // search between (avg(min, lastSizeTooSmall)), min)
    // if `min` too small, search between (avg(min,max), max)
    // keep track of iterations, and the last font size that was not too big
    if (obj.tooBig) {
        (lastSizeTooSmall === -1) ?
            determineMaxFontSize(content, min / 2, min, iterations - 1, obj.lastSizeNotTooBig, lastSizeTooSmall) :
                determineMaxFontSize(content, (min + lastSizeTooSmall) / 2, min, iterations - 1, obj.lastSizeNotTooBig, lastSizeTooSmall);

    } else {
        determineMaxFontSize(content, (min + max) / 2, max, iterations - 1, obj.lastSizeNotTooBig, min);
    }
}

// determine if fontSize is too big based on scrollHeight and offsetHeight, 
// keep track of last value that did not overflow
function fontSizeTooBig(content, fontSize, lastSizeNotTooBig) {
    content.style.fontSize = fontSize + "px";
    var tooBig = content.scrollHeight > content.offsetHeight;
    return {
        tooBig: tooBig,
        lastSizeNotTooBig: tooBig ? lastSizeNotTooBig : fontSize
    };
}

Firebase TIMESTAMP to date and Time

Firebase.ServerValue.TIMESTAMP is not actual timestamp it is constant that will be replaced with actual value in server if you have it set into some variable.

mySessionRef.update({ startedAt: Firebase.ServerValue.TIMESTAMP });
mySessionRef.on('value', function(snapshot){ console.log(snapshot.val()) })
//{startedAt: 1452508763895}

if you want to get server time then you can use following code

  fb.ref("/.info/serverTimeOffset").on('value', function(offset) {
    var offsetVal = offset.val() || 0;
    var serverTime = Date.now() + offsetVal;
  });

Undefined reference to sqrt (or other mathematical functions)

Here are my observation, firstly you need to include the header math.h as sqrt() function declared in math.h header file. For e.g

#include <math.h>

secondly, if you read manual page of sqrt you will notice this line Link with -lm.

#include <math.h> /* header file you need to include */

double sqrt(double x); /* prototype of sqrt() function */

Link with -lm. /* Library linking instruction */

But application still says undefined reference to sqrt. Do you see any problem here?

Compiler error is correct as you haven't linked your program with library lm & linker is unable to find reference of sqrt(), you need to link it explicitly. For e.g

gcc -Wall -Wextra -Werror -pedantic test.c -lm

Calling stored procedure with return value

The version of EnterpriseLibrary on my machine had other parameters. This was working:

        SqlParameter retval = new SqlParameter("@ReturnValue", System.Data.SqlDbType.Int);
        retval.Direction = System.Data.ParameterDirection.ReturnValue;
        cmd.Parameters.Add(retval);
        db.ExecuteNonQuery(cmd);
        object o = cmd.Parameters["@ReturnValue"].Value;

How to source virtualenv activate in a Bash script

Although it doesn't add the "(.env)" prefix to the shell prompt, I found this script works as expected.

#!/bin/bash
script_dir=`dirname $0`
cd $script_dir
/bin/bash -c ". ../.env/bin/activate; exec /bin/bash -i"

e.g.

user@localhost:~/src$ which pip
/usr/local/bin/pip
user@localhost:~/src$ which python
/usr/bin/python
user@localhost:~/src$ ./shell
user@localhost:~/src$ which pip
~/.env/bin/pip
user@localhost:~/src$ which python
~/.env/bin/python
user@localhost:~/src$ exit
exit

matplotlib: plot multiple columns of pandas data frame on the bar chart

You can plot several columns at once by supplying a list of column names to the plot's y argument.

df.plot(x="X", y=["A", "B", "C"], kind="bar")

enter image description here

This will produce a graph where bars are sitting next to each other.

In order to have them overlapping, you would need to call plot several times, and supplying the axes to plot to as an argument ax to the plot.

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

y = np.random.rand(10,4)
y[:,0]= np.arange(10)
df = pd.DataFrame(y, columns=["X", "A", "B", "C"])

ax = df.plot(x="X", y="A", kind="bar")
df.plot(x="X", y="B", kind="bar", ax=ax, color="C2")
df.plot(x="X", y="C", kind="bar", ax=ax, color="C3")

plt.show()

enter image description here

Update query using Subquery in Sql Server

The title of this thread asks how a subquery can be used in an update. Here's an example of that:

update [dbName].[dbo].[MyTable] 
set MyColumn = 1 
where 
    (
        select count(*) 
        from [dbName].[dbo].[MyTable] mt2 
        where
            mt2.ID > [dbName].[dbo].[MyTable].ID
            and mt2.Category = [dbName].[dbo].[MyTable].Category
    ) > 0

python filter list of dictionaries based on key value

Use filter, or if the number of dictionaries in exampleSet is too high, use ifilter of the itertools module. It would return an iterator, instead of filling up your system's memory with the entire list at once:

from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
    print elem

jquery - Check for file extension before uploading

Here is a simple code for javascript validation, and after it validates it will clean the input file.

<input type="file" id="image" accept="image/*" onChange="validate(this.value)"/>

function validate(file) {
    var ext = file.split(".");
    ext = ext[ext.length-1].toLowerCase();      
    var arrayExtensions = ["jpg" , "jpeg", "png", "bmp", "gif"];

    if (arrayExtensions.lastIndexOf(ext) == -1) {
        alert("Wrong extension type.");
        $("#image").val("");
    }
}

AlertDialog.Builder with custom layout and EditText; cannot access view

/**
 * Shows  confirmation dialog about signing in.
 */
private void startAuthDialog() {
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    AlertDialog alertDialog = dialogBuilder.create();
    alertDialog.show();

    alertDialog.getWindow().setLayout(800, 1400);
    LayoutInflater inflater = this.getLayoutInflater();
    View dialogView = inflater.inflate(R.layout.auth_dialog, null);
    alertDialog.getWindow().setContentView(dialogView);
    EditText editText = (EditText) dialogView.findViewById(R.id.label_field);
    editText.setText("test label");
}

matrix multiplication algorithm time complexity

Using linear algebra, there exist algorithms that achieve better complexity than the naive O(n3). Solvay Strassen algorithm achieves a complexity of O(n2.807) by reducing the number of multiplications required for each 2x2 sub-matrix from 8 to 7.

The fastest known matrix multiplication algorithm is Coppersmith-Winograd algorithm with a complexity of O(n2.3737). Unless the matrix is huge, these algorithms do not result in a vast difference in computation time. In practice, it is easier and faster to use parallel algorithms for matrix multiplication.

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

Add the below property into the web.config file for IIS sites. This worked for me on my intranet in IE11.

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <clear />
      <add name="X-UA-Compatible" value="IE=edge" />
    </customHeaders>
  </httpProtocol>
</system.webServer> 

How to open existing project in Eclipse

i use Mac and i deleted ADT bundle source. faced the same error so i went to project > clean and adb ran normally.

Java - Reading XML file

One of the possible implementations:

File file = new File("userdata.xml");
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
        .newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
String usr = document.getElementsByTagName("user").item(0).getTextContent();
String pwd = document.getElementsByTagName("password").item(0).getTextContent();

when used with the XML content:

<credentials>
    <user>testusr</user>
    <password>testpwd</password>
</credentials>

results in "testusr" and "testpwd" getting assigned to the usr and pwd references above.

Render Partial View Using jQuery in ASP.NET MVC

Using standard Ajax call to achieve same result

        $.ajax({
            url: '@Url.Action("_SearchStudents")?NationalId=' + $('#NationalId').val(),
            type: 'GET',
            error: function (xhr) {
                alert('Error: ' + xhr.statusText);

            },
            success: function (result) {

                $('#divSearchResult').html(result);
            }
        });




public ActionResult _SearchStudents(string NationalId)
        {

           //.......

            return PartialView("_SearchStudents", model);
        }

Get the list of stored procedures created and / or modified on a particular date?

Here is the "newer school" version.

SELECT * FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = N'PROCEDURE' and ROUTINE_SCHEMA = N'dbo' 
and CREATED = '20120927'

Bootstrap close responsive menu "on click"

I've got it to work with animation!

Menu in html:

<div id="nav-main" class="nav-collapse collapse">
     <ul class="nav">
         <li>
             <a href='#somewhere'>Somewhere</a>
         </li>
     </ul>
 </div>

Binding click event on all a elements in navigation to collapse menu (Bootstrap collapse plugin):

 $(function(){ 
     var navMain = $("#nav-main");
     navMain.on("click", "a", null, function () {
         navMain.collapse('hide');
     });
 });

EDIT To make it more generic we can use following code snippet

 $(function(){ 
     var navMain = $(".navbar-collapse"); // avoid dependency on #id
     // "a:not([data-toggle])" - to avoid issues caused
     // when you have dropdown inside navbar
     navMain.on("click", "a:not([data-toggle])", null, function () {
         navMain.collapse('hide');
     });
 });

How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

I will show visually the problem, using the great example from James answer and adding the alternative solution.

When you do the follow query, without the FETCH:

Select e from Employee e 
join e.phones p 
where p.areaCode = '613'

You will have the follow results from Employee as you expected:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613
1 James 6 416

But when you add the FETCH word on JOIN, this is what happens:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613

The generated SQL is the same for the two queries, but the Hibernate removes on memory the 416 register when you use WHERE on the FETCH join.

So, to bring all phones and apply the WHERE correctly, you need to have two JOINs: one for the WHERE and another for the FETCH. Like:

Select e from Employee e 
join e.phones p 
join fetch e.phones      //no alias, to not commit the mistake
where p.areaCode = '613'

How to add form validation pattern in Angular 2?

My solution with Angular 4.0.1: Just showing the UI for required CVC input - where the CVC must be exactly 3 digits:

    <form #paymentCardForm="ngForm">         
...
        <md-input-container align="start">
            <input #cvc2="ngModel" mdInput type="text" id="cvc2" name="cvc2" minlength="3" maxlength="3" placeholder="CVC" [(ngModel)]="paymentCard.cvc2" [disabled]="isBusy" pattern="\d{3}" required />
            <md-hint *ngIf="cvc2.errors && (cvc2.touched || submitted)" class="validation-result">
                <span [hidden]="!cvc2.errors.required && cvc2.dirty">
                    CVC is required.
                </span>
                <span [hidden]="!cvc2.errors.minlength && !cvc2.errors.maxlength && !cvc2.errors.pattern">
                    CVC must be 3 numbers.
                </span>
            </md-hint>
        </md-input-container>
...
<button type="submit" md-raised-button color="primary" (click)="confirm($event, paymentCardForm.value)" [disabled]="isBusy || !paymentCardForm.valid">Confirm</button>
</form>

Sorting arrays in javascript by object key value

Use Array's sort() method, eg

myArray.sort(function(a, b) {
    return a.distance - b.distance;
});

Insert new column into table in sqlite?

You can add new column with the query

ALTER TABLE TableName ADD COLUMN COLNew CHAR(25)

But it will be added at the end, not in between the existing columns.

How do I collapse sections of code in Visual Studio Code for Windows?

With JavaScript:

//#region REGION_NAME
   ...code here
//#endregion

Getting the number of filled cells in a column (VBA)

One way is to: (Assumes index column begins at A1)

MsgBox Range("A1").End(xlDown).Row

Which is looking for the 1st unoccupied cell downwards from A1 and showing you its ordinal row number.

You can select the next empty cell with:

Range("A1").End(xlDown).Offset(1, 0).Select

If you need the end of a dataset (including blanks), try: Range("A:A").SpecialCells(xlLastCell).Row

Round to 5 (or other number) in Python

def round_up_to_base(x, base=10):
    return x + (base - x) % base

def round_down_to_base(x, base=10):
    return x - (x % base)

which gives

for base=5:

>>> [i for i in range(20)]
[0, 1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> [round_down_to_base(x=i, base=5) for i in range(20)]
[0, 0,  0,  0,  0,  5,  5,  5,  5,  5,  10, 10, 10, 10, 10, 15, 15, 15, 15, 15]

>>> [round_up_to_base(x=i, base=5) for i in range(20)]
[0, 5,  5,  5,  5,  5,  10, 10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20, 20, 20]

for base=10:

>>> [i for i in range(20)]
[0, 1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> [round_down_to_base(x=i, base=10) for i in range(20)]
[0, 0,  0,  0,  0,  0,  0,  0,  0,  0,  10, 10, 10, 10, 10, 10, 10, 10, 10, 10]

>>> [round_up_to_base(x=i, base=10) for i in range(20)]
[0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 20, 20, 20, 20, 20, 20, 20, 20, 20]

tested in Python 3.7.9

Change value in a cell based on value in another cell

If you want to do something like the following example, you'd have to use nested ifs.

If percentage is greater than or equal to 93%, then corresponding value in B should be 4 and if the percentage is greater than or equal to 90% and less than 92%, then corresponding value in B to be 3.7, etc.

Here's how you'd do it:

=IF(A2>=93%, 4, IF(A2>=90%, 3.7,IF(A2>=87%,3.3,0)))

How do I look inside a Python object?

While pprint has been mentioned already by others I'd like to add some context.

The pprint module provides a capability to “pretty-print” arbitrary Python data structures in a form which can be used as input to the interpreter. If the formatted structures include objects which are not fundamental Python types, the representation may not be loadable. This may be the case if objects such as files, sockets, classes, or instances are included, as well as many other built-in objects which are not representable as Python constants.

pprint might be in high-demand by developers with a PHP background who are looking for an alternative to var_dump().

Objects with a dict attribute can be dumped nicely using pprint() mixed with vars(), which returns the __dict__ attribute for a module, class, instance, etc.:

from pprint import pprint
pprint(vars(your_object))

So, no need for a loop.

To dump all variables contained in the global or local scope simply use:

pprint(globals())
pprint(locals())

locals() shows variables defined in a function.
It's also useful to access functions with their corresponding name as a string key, among other usages:

locals()['foo']() # foo()
globals()['foo']() # foo()

Similarly, using dir() to see the contents of a module, or the attributes of an object.

And there is still more.

What is the equivalent of Java static methods in Kotlin?

You need to pass companion object for static method because kotlin don’t have static keyword - Members of the companion object can be called by using simply the class name as the qualifier:

package xxx
    class ClassName {
              companion object {
                       fun helloWord(str: String): String {
                            return stringValue
                      }
              }
    }

Rails: Using greater than/less than with a where statement

Another fancy possibility is...

User.where("id > :id", id: 100)

This feature allows you to create more comprehensible queries if you want to replace in multiple places, for example...

User.where("id > :id OR number > :number AND employee_id = :employee", id: 100, number: 102, employee: 1205)

This has more meaning than having a lot of ? on the query...

User.where("id > ? OR number > ? AND employee_id = ?", 100, 102, 1205)

Angular 2 - Checking for server errors from subscribe

As stated in the relevant RxJS documentation, the .subscribe() method can take a third argument that is called on completion if there are no errors.

For reference:

  1. [onNext] (Function): Function to invoke for each element in the observable sequence.
  2. [onError] (Function): Function to invoke upon exceptional termination of the observable sequence.
  3. [onCompleted] (Function): Function to invoke upon graceful termination of the observable sequence.

Therefore you can handle your routing logic in the onCompleted callback since it will be called upon graceful termination (which implies that there won't be any errors when it is called).

this.httpService.makeRequest()
    .subscribe(
      result => {
        // Handle result
        console.log(result)
      },
      error => {
        this.errors = error;
      },
      () => {
        // 'onCompleted' callback.
        // No errors, route to new page here
      }
    );

As a side note, there is also a .finally() method which is called on completion regardless of the success/failure of the call. This may be helpful in scenarios where you always want to execute certain logic after an HTTP request regardless of the result (i.e., for logging purposes or for some UI interaction such as showing a modal).

Rx.Observable.prototype.finally(action)

Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.

For instance, here is a basic example:

import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/finally';

// ...

this.httpService.getRequest()
    .finally(() => {
      // Execute after graceful or exceptionally termination
      console.log('Handle logging logic...');
    })
    .subscribe (
      result => {
        // Handle result
        console.log(result)
      },
      error => {
        this.errors = error;
      },
      () => {
        // No errors, route to new page
      }
    );

JavaScript Object Id

I've just come across this, and thought I'd add my thoughts. As others have suggested, I'd recommend manually adding IDs, but if you really want something close to what you've described, you could use this:

var objectId = (function () {
    var allObjects = [];

    var f = function(obj) {
        if (allObjects.indexOf(obj) === -1) {
            allObjects.push(obj);
        }
        return allObjects.indexOf(obj);
    }
    f.clear = function() {
      allObjects = [];
    };
    return f;
})();

You can get any object's ID by calling objectId(obj). Then if you want the id to be a property of the object, you can either extend the prototype:

Object.prototype.id = function () {
    return objectId(this);
}

or you can manually add an ID to each object by adding a similar function as a method.

The major caveat is that this will prevent the garbage collector from destroying objects when they drop out of scope... they will never drop out of the scope of the allObjects array, so you might find memory leaks are an issue. If your set on using this method, you should do so for debugging purpose only. When needed, you can do objectId.clear() to clear the allObjects and let the GC do its job (but from that point the object ids will all be reset).

How to increment datetime by custom months in python without using library

Similar in ideal to Dave Webb's solution, but without all of that tricky modulo arithmetic:

import datetime, calendar

def increment_month(date):
    # Go to first of this month, and add 32 days to get to the next month
    next_month = date.replace(day=1) + datetime.timedelta(32)
    # Get the day of month that corresponds
    day = min(date.day, calendar.monthrange(next_month.year, next_month.month)[1])
    return next_month.replace(day=day)

Pyspark replace strings in Spark dataframe column

For Spark 1.5 or later, you can use the functions package:

from pyspark.sql.functions import *
newDf = df.withColumn('address', regexp_replace('address', 'lane', 'ln'))

Quick explanation:

  • The function withColumn is called to add (or replace, if the name exists) a column to the data frame.
  • The function regexp_replace will generate a new column by replacing all substrings that match the pattern.

How to check the first character in a string in Bash or UNIX shell?

$ foo="/some/directory/file"
$ [ ${foo:0:1} == "/" ] && echo 1 || echo 0
1
$ foo="[email protected]:/some/directory/file"
$ [ ${foo:0:1} == "/" ] && echo 1 || echo 0
0

How to clear all input fields in bootstrap modal when clicking data-dismiss button?

In addition to @Malk, I wanted to clear all fields in the popup, except the hidden fields. To do that just use this:

$('.modal').on('hidden.bs.modal', function () {
    $(this)
        .find("input:not([type=hidden]),textarea,select")
        .val('')
        .end()
        .find("input[type=checkbox], input[type=radio]")
        .prop("checked", "")
        .end();
});

This will clear all fields, except the hidden ones.

Search and replace part of string in database

Update database and Set fieldName=Replace (fieldName,'FindString','ReplaceString')

How to drop a PostgreSQL database if there are active connections to it?

You could kill all connections before dropping the database using the pg_terminate_backend(int) function.

You can get all running backends using the system view pg_stat_activity

I'm not entirely sure, but the following would probably kill all sessions:

select pg_terminate_backend(procpid)
from pg_stat_activity
where datname = 'doomed_database'

Of course you may not be connected yourself to that database

How to convert a SVG to a PNG with ImageMagick?

why don't you give a try to inkscape command line, this is my bat file to convert all svg in this dir to png:

FOR %%x IN (*.svg) DO C:\Ink\App\Inkscape\inkscape.exe %%x -z --export-dpi=500 --export-area-drawing --export-png="%%~nx.png"

Assign multiple values to array in C

With code like this:

const int node_ct = 8;
const int expected[node_ct] = { 1, 3, 4, 2, 5, 6, 7, 8 };

And in the configure.ac

AC_PROG_CC_C99

The compiler on my dev box was happy. The compiler on the server complained with:

error: variable-sized object may not be initialized
   const int expected[node_ct] = { 1, 3, 4, 2, 5, 6, 7, 8 };

and

warning: excess elements in array initializer
   const int expected[node_ct] = { 1, 3, 4, 2, 5, 6, 7, 8 };

for each element

It doesn't complain at all about, for example:

int expected[] = { 1, 2, 3, 4, 5 };

however, I decided that I like the check on size.

Rather than fighting, I went with a varargs initializer:

#include <stdarg.h>

void int_array_init(int *a, const int ct, ...) {
  va_list args;
  va_start(args, ct);
  for(int i = 0; i < ct; ++i) {
    a[i] = va_arg(args, int);
  }
  va_end(args);
}

called like,

const int node_ct = 8;
int expected[node_ct];
int_array_init(expected, node_ct, 1, 3, 4, 2, 5, 6, 7, 8);

As such, the varargs support is more robust than the support for the array initializer.

Someone might be able to do something like this in a macro.

Find PR with sample code at https://github.com/wbreeze/davenport/pull/15/files

Regarding https://stackoverflow.com/a/3535455/608359 from @paxdiablo, I liked it; but, felt insecure about having the number of times the initializaion pointer advances synchronized with the number of elements allocated to the array. Worst case, the initializing pointer moves beyond the allocated length. As such, the diff in the PR contains,

  int expected[node_ct];
- int *p = expected;
- *p++ = 1; *p++ = 2; *p++ = 3; *p++ = 4;
+ int_array_init(expected, node_ct, 1, 2, 3, 4);

The int_array_init method will safely assign junk if the number of arguments is fewer than the node_ct. The junk assignment ought to be easier to catch and debug.

Border color on default input style

I would have thought this would have been answered already - but surely what you want is this: box-shadow: 0 0 3px #CC0000;

Example: http://jsfiddle.net/vmzLW/

Finding index of character in Swift String

I have found this solution for swift2:

var str = "abcdefghi"
let indexForCharacterInString = str.characters.indexOf("c") //returns 2

How does the @property decorator work in Python?

Decorator is a function that takes a function as an argument and returns closure. Closure is a set of inner function and free variable. Inner function is closing over free variable and that is why it is called 'closure'. Free variable is variable that outside the inner function and passed in to inner via docorator.

As the name says, decorator is decorating the received function.

function decorator(undecorated_func):
    print("calling decorator func")
    inner():
       print("I am inside inner")
       return undecorated_func
    return inner

this is a simple decorator function. It received "undecorated_func" and passed it to inner() as a free variable, inner() printed "I am inside inner" and returned undecorated_func. When we call decorator(undecorated_func), it is returning the inner. Here is the key, in decorators we are naming the inner function as the name of the function that we passed.

   undecorated_function= decorator(undecorated_func) 

now inner function is called "undecorated_func". Since inner is now named as "undecorated_func", we passed "undecorated_func" to the decorator and we returned "undecorated_func" plus printed out "I am inside inner". so this print statement decorated our "undecorated_func".

now lets define a class with property decorator:

class Person:
    def __init__(self,name):
        self._name=name
    @property
    def name(self):
        return self._name
    @name.setter
    def name(self.value):
        self._name=value

when we decorated name() with @property(), this is what happened:

name=property(name) # Person.__dict__ you ll see name 

first argument of property() is getter. this is what happened in the second decoration:

   name=name.setter(name) 

As I mentioned above, decorator returns the inner function, and we name the inner function with the name of the function that we passed.

Here is an important thing to be aware of. "name" is immutable. in the first decoration we got this:

  name=property(name)

in the second one we got this

  name=name.setter(name)

We are not modifying name obj. In the second decoration, python sees that this is property object and it already had getter. So python creates a new "name" object, adds the "fget" from the first obj and then sets the "fset".

Installing specific laravel version with composer create-project

composer create-project laravel/laravel=4.1.27 your-project-name --prefer-dist

And then you probably need to install all of vendor packages, so

composer install

Replacing column values in a pandas DataFrame

You can also use apply with .get i.e.

w['female'] = w['female'].apply({'male':0, 'female':1}.get):

w = pd.DataFrame({'female':['female','male','female']})
print(w)

Dataframe w:

   female
0  female
1    male
2  female

Using apply to replace values from the dictionary:

w['female'] = w['female'].apply({'male':0, 'female':1}.get)
print(w)

Result:

   female
0       1
1       0
2       1 

Note: apply with dictionary should be used if all the possible values of the columns in the dataframe are defined in the dictionary else, it will have empty for those not defined in dictionary.

mySQL Error 1040: Too Many Connection

you need check your all connection. Then try to close it one by one. it maybe caused by one of your connection.

I have similar case, the root cause come from my monitoring server. So when I closed it, it works.

AWK to print field $2 first, then field $1

The awk is ok. I'm guessing the file is from a windows system and has a CR (^m ascii 0x0d) on the end of the line.

This will cause the cursor to go to the start of the line after $2.

Use dos2unix or vi with :se ff=unix to get rid of the CRs.

How to upload a file using Java HttpClient library working with PHP

For those having a hard time implementing the accepted answer (which requires org.apache.http.entity.mime.MultipartEntity) you may be using org.apache.httpcomponents 4.2.* In this case, you have to explicitly install httpmime dependency, in my case:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.2.5</version>
</dependency>

Apache Cordova - uninstall globally

Try this for Windows:

    npm uninstall -g cordova

Try this for MAC:

    sudo npm uninstall -g cordova

You can also add Cordova like this:

  1. If You Want To install the previous version of Cordova through the Node Package Manager (npm):

    npm install -g [email protected]
    
  2. If You Want To install the latest version of Cordova:

    npm install -g cordova 
    

Enjoy!

Matrix Multiplication in pure Python?

The shape of your matrix C is wrong; it's the transpose of what you actually want it to be. (But I agree with ulmangt: the Right Thing is almost certainly to use numpy, really.)

how to show progress bar(circle) in an activity having a listview before loading the listview with data

There are several methods of showing a progress bar (circle) while loading an activity. In your case, one with a ListView in it.

IN ACTIONBAR

If you are using an ActionBar, you can call the ProgressBar like this (this could go in your onCreate()

requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);  
setProgressBarIndeterminateVisibility(true);

And after you are done displaying the list, to hide it.

setProgressBarIndeterminateVisibility(false);

IN THE LAYOUT (The XML)

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/linlaHeaderProgress"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="gone" >

        <ProgressBar
            android:id="@+id/pbHeaderProgress"
            style="@style/Spinner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
        </ProgressBar>
    </LinearLayout>

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:cacheColorHint="@android:color/transparent"
        android:divider="#00000000"
        android:dividerHeight="0dp"
        android:fadingEdge="none"
        android:persistentDrawingCache="scrolling"
        android:smoothScrollbar="false" >
    </ListView>
</LinearLayout>

And in your activity (Java) I use an AsyncTask to fetch data for my lists. SO, in the AsyncTask's onPreExecute() I use something like this:

// CAST THE LINEARLAYOUT HOLDING THE MAIN PROGRESS (SPINNER)
LinearLayout linlaHeaderProgress = (LinearLayout) findViewById(R.id.linlaHeaderProgress);

@Override
protected void onPreExecute() {    
    // SHOW THE SPINNER WHILE LOADING FEEDS
    linlaHeaderProgress.setVisibility(View.VISIBLE);
}

and in the onPostExecute(), after setting the adapter to the ListView:

@Override
protected void onPostExecute(Void result) {     
    // SET THE ADAPTER TO THE LISTVIEW
    lv.setAdapter(adapter);

    // CHANGE THE LOADINGMORE STATUS TO PERMIT FETCHING MORE DATA
    loadingMore = false;

    // HIDE THE SPINNER AFTER LOADING FEEDS
    linlaHeaderProgress.setVisibility(View.GONE);
}

EDIT: This is how it looks in my app while loading one of several ListViews

enter image description here

jQuery - Getting the text value of a table cell in the same row as a clicked element

so you can use parent() to reach to the parent tr and then use find to gather the td with class two

var Something = $(this).parent().find(".two").html();

or

var Something = $(this).parent().parent().find(".two").html();

use as much as parent() what ever the depth of the clicked object according to the tr row

hope this works...

Connecting to local SQL Server database using C#

In Data Source (on the left of Visual Studio) right click on the database, then Configure Data Source With Wizard. A new window will appear, expand the Connection string, you can find the connection string in there

C++ convert string to hexadecimal and vice versa

As of C++17 there's also std::from_chars. The following function takes a string of hex characters and returns a vector of T:

#include <charconv>

template<typename T>
std::vector<T> hexstr_to_vec(const std::string& str, unsigned char chars_per_num = 2)
{
  std::vector<T> out(str.size() / chars_per_num, 0);

  T value;
  for (int i = 0; i < str.size() / chars_per_num; i++) {
    std::from_chars<T>(
      str.data() + (i * chars_per_num),
      str.data() + (i * chars_per_num) + chars_per_num,
      value,
      16
    );
    out[i] = value;
  }

  return out;
}

How to "inverse match" with regex?

If you want to do this in RegexBuddy, there are two ways to get a list of all lines not matching a regex.

On the toolbar on the Test panel, set the test scope to "Line by line". When you do that, an item List All Lines without Matches will appear under the List All button on the same toolbar. (If you don't see the List All button, click the Match button in the main toolbar.)

On the GREP panel, you can turn on the "line-based" and the "invert results" checkboxes to get a list of non-matching lines in the files you're grepping through.

How to create JSON object Node.js

What I believe you're looking for is a way to work with arrays as object values:

var o = {} // empty Object
var key = 'Orientation Sensor';
o[key] = []; // empty Array, which you can push() values into


var data = {
    sampleTime: '1450632410296',
    data: '76.36731:3.4651554:0.5665419'
};
var data2 = {
    sampleTime: '1450632410296',
    data: '78.15431:0.5247617:-0.20050584'
};
o[key].push(data);
o[key].push(data2);

This is standard JavaScript and not something NodeJS specific. In order to serialize it to a JSON string you can use the native JSON.stringify:

JSON.stringify(o);
//> '{"Orientation Sensor":[{"sampleTime":"1450632410296","data":"76.36731:3.4651554:0.5665419"},{"sampleTime":"1450632410296","data":"78.15431:0.5247617:-0.20050584"}]}'

Get name of current class?

PEP 3155 introduced __qualname__, which was implemented in Python 3.3.

For top-level functions and classes, the __qualname__ attribute is equal to the __name__ attribute. For nested classes, methods, and nested functions, the __qualname__ attribute contains a dotted path leading to the object from the module top-level.

It is accessible from within the very definition of a class or a function, so for instance:

class Foo:
    print(__qualname__)

will effectively print Foo. You'll get the fully qualified name (excluding the module's name), so you might want to split it on the . character.

However, there is no way to get an actual handle on the class being defined.

>>> class Foo:
...     print('Foo' in globals())
... 
False

passing several arguments to FUN of lapply (and others *apply)

You can do it in the following way:

 myfxn <- function(var1,var2,var3){
      var1*var2*var3

    }

    lapply(1:3,myfxn,var2=2,var3=100)

and you will get the answer:

[[1]] [1] 200

[[2]] [1] 400

[[3]] [1] 600

How do you get a directory listing sorted by creation date in python?

I've done this in the past for a Python script to determine the last updated files in a directory:

import glob
import os

search_dir = "/mydir/"
# remove anything from the list that is not a file (directories, symlinks)
# thanks to J.F. Sebastion for pointing out that the requirement was a list 
# of files (presumably not including directories)  
files = list(filter(os.path.isfile, glob.glob(search_dir + "*")))
files.sort(key=lambda x: os.path.getmtime(x))

That should do what you're looking for based on file mtime.

EDIT: Note that you can also use os.listdir() in place of glob.glob() if desired - the reason I used glob in my original code was that I was wanting to use glob to only search for files with a particular set of file extensions, which glob() was better suited to. To use listdir here's what it would look like:

import os

search_dir = "/mydir/"
os.chdir(search_dir)
files = filter(os.path.isfile, os.listdir(search_dir))
files = [os.path.join(search_dir, f) for f in files] # add path to each file
files.sort(key=lambda x: os.path.getmtime(x))

jQuery access input hidden value

To get value, use:

$.each($('input'),function(i,val){
    if($(this).attr("type")=="hidden"){
        var valueOfHidFiled=$(this).val();
        alert(valueOfHidFiled);
    }
});

or:

var valueOfHidFiled=$('input[type=hidden]').val();
alert(valueOfHidFiled);

To set value, use:

$('input[type=hidden]').attr('value',newValue);

How to insert a new line in Linux shell script?

Use this echo statement

 echo -e "Hai\nHello\nTesting\n"

The output is

Hai
Hello
Testing

C# - What does the Assert() method do? Is it still useful?

The way I think of it is Debug.Assert is a way to establish a contract about how a method is supposed to be called, focusing on specifics about the values of a paramter (instead of just the type). For example, if you are not supposed to send a null in the second parameter you add the Assert around that parameter to tell the consumer not to do that.

It prevents someone from using your code in a boneheaded way. But it also allows that boneheaded way to go through to production and not give the nasty message to a customer (assuming you build a Release build).

Find an object in SQL Server (cross-database)

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go


/**********************************************************************
Naziv procedure     : sp_rfv_FIND
Ime i prezime autora: Srdjan Nadrljanski
Datum kreiranja     : 13.06.2013. 
Namena              : Traži sql objekat na celom serveru
Tabele              : 
Ulazni parametri    : 
Izlazni parametri   : 
Datum zadnje izmene :  
Opis izmene         : 
exec sp_rfv_FIND 'TUN',''
**********************************************************************/
CREATE PROCEDURE [dbo].[sp_rfv_FIND] (  @SEARCHSTRING VARCHAR(255),
                                        @notcontain Varchar(255)
                                        )
AS


declare @text varchar(1500),@textinit varchar (1500)
set @textinit=
'USE @sifra

insert into ##temp2
select ''@sifra''as dbName,a.[Object Name],a.[Object Type]
from(
 SELECT DISTINCT sysobjects.name AS [Object Name]   ,
case
when sysobjects.xtype = ''C'' then ''CHECK constraint''
when sysobjects.xtype = ''D'' then ''Default or DEFAULT constraint''
when sysobjects.xtype = ''F'' then ''Foreign Key''
when sysobjects.xtype = ''FN'' then ''Scalar function''
when sysobjects.xtype = ''P'' then ''Stored Procedure''
when sysobjects.xtype = ''PK'' then ''PRIMARY KEY constraint''
when sysobjects.xtype = ''S'' then ''System table''
when sysobjects.xtype = ''TF'' then ''Function''
when sysobjects.xtype = ''TR'' then ''Trigger''
when sysobjects.xtype = ''U'' then ''User table''
when sysobjects.xtype = ''UQ'' then ''UNIQUE constraint''
when sysobjects.xtype = ''V'' then ''View''
when sysobjects.xtype = ''X'' then ''Extended stored procedure''
end as [Object Type]
FROM sysobjects
WHERE
sysobjects.type in (''C'',''D'',''F'',''FN'',''P'',''K'',''S'',''TF'',''TR'',''U'',''V'',''X'')
AND sysobjects.category = 0
AND CHARINDEX(''@SEARCHSTRING'',sysobjects.name)>0
AND ((CHARINDEX(''@notcontain'',sysobjects.name)=0 or 
CHARINDEX(''@notcontain'',sysobjects.name)<>0)) 
)a'

    set @textinit=replace(@textinit,'@SEARCHSTRING',@SEARCHSTRING)
    set @textinit=replace(@textinit,'@notcontain',@notcontain)


SELECT name AS dbName,cast(null as varchar(255)) as ObjectName,cast(null as varchar(255)) as ObjectType  
into ##temp1 
from master.dbo.sysdatabases order by name

SELECT * INTO ##temp2 FROM ##temp1 WHERE 1 = 0


declare @sifra VARCHAR(255),@suma int,@brojac int

set @suma=(select count(dbName) from ##temp1) 

DECLARE c_k CURSOR LOCAL FAST_FORWARD FOR
SELECT dbName FROM ##temp1 ORDER BY dbName DESC

OPEN c_k
FETCH NEXT FROM c_K INTO @sifra
SET @brojac = 1
WHILE (@@fetch_status = 0 ) AND (@brojac <= @suma)
BEGIN

    set @text=replace(@textinit,'@sifra',@sifra)

    exec (@text)

    SET @brojac = @brojac +1

    DELETE FROM ##temp1 WHERE dbName = @sifra

       FETCH NEXT FROM c_k INTO @sifra 
END
close c_k
DEALLOCATE c_k

select * from ##temp2
order by dbName,ObjectType
drop table ##temp2
drop table ##temp1

Font from origin has been blocked from loading by Cross-Origin Resource Sharing policy

Nginx:

location ~* \.(eot|ttf|woff)$ {
   add_header Access-Control-Allow-Origin '*';
}

AWS S3:

  1. Select your bucket
  2. Click properties on the right top
  3. Permisions => Edit Cors Configuration => Save
  4. Save

http://schock.net/articles/2013/07/03/hosting-web-fonts-on-a-cdn-youre-going-to-need-some-cors/

How to make Google Fonts work in IE?

I tried all the options from above and they didn't work. Then I located the google font (Over the Rainbow) in my folder (new) and used IE conditional below and it worked perfect.

<!--[if IE]>
<style type="text/css">
    @font-face {
    font-family: "Over the Rainbow";
    src: url("../new/over.ttf");
    src: local("Over the Rainbow"), url("../new/over.ttf");
    }
</style>
<![endif]-->

I hope it will help

How to get the root dir of the Symfony2 application?

You can also use regular expression in addition to this:

    $directoryPath = $this->container->getParameter('kernel.root_dir') . '/../web/bundles/yourbundle/';
    $directoryPath = preg_replace("/app..../i", "", $directoryPath);
    echo $directoryPath;

How do I set default values for functions parameters in Matlab?

I've found that the parseArgs function can be very helpful.

Should CSS always preceed Javascript?

Steve Souders has already given a definitive answer but...

I wonder whether there's an issue with both Sam's original test and Josh's repeat of it.

Both tests appear to have been performed on low latency connections where setting up the TCP connection will have a trivial cost.

How this affects the result of the test I'm not sure and I'd want to look at the waterfalls for the tests over a 'normal' latency connection but...

The first file downloaded should get the connection used for the html page, and the second file downloaded will get the new connection. (Flushing the early alters that dynamic, but it's not being done here)

In newer browsers the second TCP connection is opened speculatively so the connection overhead is reduced / goes away, in older browsers this isn't true and the second connection will have the overhead of being opened.

Quite how/if this affects the outcome of the tests I'm not sure.

How to stop asynctask thread in android?

You can't just kill asynctask immediately. In order it to stop you should first cancel it:

task.cancel(true);

and than in asynctask's doInBackground() method check if it's already cancelled:

isCancelled()

and if it is, stop executing it manually.

Facebook key hash does not match any stored key hashes

I got the same problem. I found that I used wrong hashkey. keytool printed wrong hashkey because I run command with wrong alias.
Please check your command again.It will resolve your issue

keytool -exportcert -alias "test fb sdk" -storepass android -keypass android -keystore "C:\keystore.keystore" | openssl sha1 -binary | openssl base64

Image style height and width not taken in outlook mails

Put the width and height in separate attributes, with no unit:

<img style="margin: 0; border: 0; padding: 0; display: block;"
src="images/img.jpg" width="120" height="150">

Another Option:

<!--[if gte mso 9]>
<style type="text/css">
img.header { width: 600px; } /* or something like that */
</style>
<![endif]-->

What is Hive: Return Code 2 from org.apache.hadoop.hive.ql.exec.MapRedTask

I faced the same issue because I didn't have permission to query the database I was trying to.

In the case you don't have permission to query the table/database, besides the Return Code 2 from org.apache.hadoop.hive.ql.exec.MapRedTask error, you will see that in Cloudera Manager is not even registering your query.

Value of type 'T' cannot be converted to

Both lines have the same problem

T newT1 = "some text";
T newT2 = (string)t;

The compiler doesn't know that T is a string and so has no way of knowing how to assign that. But since you checked you can just force it with

T newT1 = "some text" as T;
T newT2 = t; 

you don't need to cast the t since it's already a string, also need to add the constraint

where T : class

Using pickle.dump - TypeError: must be str, not bytes

Just had same issue. In Python 3, Binary modes 'wb', 'rb' must be specified whereas in Python 2x, they are not needed. When you follow tutorials that are based on Python 2x, that's why you are here.

import pickle

class MyUser(object):
    def __init__(self,name):
        self.name = name

user = MyUser('Peter')

print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'

with open(filename,'wb') as file_object:
    file_object.write(serialized)

with open(filename,'rb') as file_object:
    raw_data = file_object.read()

deserialized = pickle.loads(raw_data)


print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")

Why are empty catch blocks a bad idea?

This goes hand-in-hand with, "Don't use exceptions to control program flow.", and, "Only use exceptions for exceptional circumstances." If these are done, then exceptions should only be occurring when there's a problem. And if there's a problem, you don't want to fail silently. In the rare anomalies where it's not necessary to handle the problem you should at least log the exception, just in case the anomaly becomes no longer an anomaly. The only thing worse than failing is failing silently.

Using %f with strftime() in Python to get microseconds

With Python's time module you can't get microseconds with %f.

For those who still want to go with time module only, here is a workaround:

now = time.time()
mlsec = repr(now).split('.')[1][:3]
print time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), time.localtime(now))

You should get something like 2017-01-16 16:42:34.625 EET (yes, I use milliseconds as it's fairly enough).

To break the code into details, paste the below code into a Python console:

import time

# Get current timestamp
now = time.time()

# Debug now
now
print now
type(now)

# Debug strf time
struct_now = time.localtime(now)
print struct_now
type(struct_now)

# Print nicely formatted date
print time.strftime("%Y-%m-%d %H:%M:%S %Z", struct_now)

# Get miliseconds
mlsec = repr(now).split('.')[1][:3]
print mlsec

# Get your required timestamp string
timestamp = time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), struct_now)
print timestamp

For clarification purposes, I also paste my Python 2.7.12 result here:

>>> import time
>>> # get current timestamp
... now = time.time()
>>> # debug now
... now
1484578293.519106
>>> print now
1484578293.52
>>> type(now)
<type 'float'>
>>> # debug strf time
... struct_now = time.localtime(now)
>>> print struct_now
time.struct_time(tm_year=2017, tm_mon=1, tm_mday=16, tm_hour=16, tm_min=51, tm_sec=33, tm_wday=0, tm_yday=16, tm_isdst=0)
>>> type(struct_now)
<type 'time.struct_time'>
>>> # print nicely formatted date
... print time.strftime("%Y-%m-%d %H:%M:%S %Z", struct_now)
2017-01-16 16:51:33 EET
>>> # get miliseconds
... mlsec = repr(now).split('.')[1][:3]
>>> print mlsec
519
>>> # get your required timestamp string
... timestamp = time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), struct_now)
>>> print timestamp
2017-01-16 16:51:33.519 EET
>>>

Angular 2 router no base href set

Since 2.0 beta :)

import { APP_BASE_HREF } from 'angular2/platform/common';

Why do I get an UnsupportedOperationException when trying to remove an element from a List?

Replace

List<String> list=Arrays.asList(split);

to

List<String> list = New ArrayList<>();
list.addAll(Arrays.asList(split));

or

List<String> list = new ArrayList<>(Arrays.asList(split));

or

List<String> list = new ArrayList<String>(Arrays.asList(split));

or (Better for Remove elements)

List<String> list = new LinkedList<>(Arrays.asList(split));

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?

the mysqli_queryexcepts 2 parameters , first variable is mysqli_connectequivalent variable , second one is the query you have provided

$name1 = mysqli_connect(localhost,tdoylex1_dork,dorkk,tdoylex1_dork);

$name2 = mysqli_query($name1,"SELECT name FROM users ORDER BY RAND() LIMIT 1");

Indexing vectors and arrays with +:

This is another way to specify the range of the bit-vector.

x +: N, The start position of the vector is given by x and you count up from x by N.

There is also

x -: N, in this case the start position is x and you count down from x by N.

N is a constant and x is an expression that can contain iterators.

It has a couple of benefits -

  1. It makes the code more readable.

  2. You can specify an iterator when referencing bit-slices without getting a "cannot have a non-constant value" error.

Static variable inside of a function in C

There are two issues here, lifetime and scope.

The scope of variable is where the variable name can be seen. Here, x is visible only inside function foo().

The lifetime of a variable is the period over which it exists. If x were defined without the keyword static, the lifetime would be from the entry into foo() to the return from foo(); so it would be re-initialized to 5 on every call.

The keyword static acts to extend the lifetime of a variable to the lifetime of the programme; e.g. initialization occurs once and once only and then the variable retains its value - whatever it has come to be - over all future calls to foo().

How to reset (clear) form through JavaScript?

You can simply do:

$("#client.frm").trigger('reset')

How can you determine a point is between two other points on a line segment?

Check if the cross product of (b-a) and (c-a) is 0, as tells Darius Bacon, tells you if the points a, b and c are aligned.

But, as you want to know if c is between a and b, you also have to check that the dot product of (b-a) and (c-a) is positive and is less than the square of the distance between a and b.

In non-optimized pseudocode:

def isBetween(a, b, c):
    crossproduct = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y)

    # compare versus epsilon for floating point values, or != 0 if using integers
    if abs(crossproduct) > epsilon:
        return False

    dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y)*(b.y - a.y)
    if dotproduct < 0:
        return False

    squaredlengthba = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y)
    if dotproduct > squaredlengthba:
        return False

    return True

When and why do I need to use cin.ignore() in C++?

It is better to use scanf(" %[^\n]",str) in c++ than cin.ignore() after cin>> statement.To do that first you have to include < cstdio > header.

Get UTC time and local time from NSDate object

In addition to other answers, you can write an extension for Date class to get formatted Data in specific TimeZone to make it as utility function for future use. Like

 extension Date {

 func dateInTimeZone(timeZoneIdentifier: String, dateFormat: String) -> String  {
 let dtf = DateFormatter()
 dtf.timeZone = TimeZone(identifier: timeZoneIdentifier)
 dtf.dateFormat = dateFormat

 return dtf.string(from: self)
 }
}

Now you can call it like

 Date().dateInTimeZone(timeZoneIdentifier: "UTC", dateFormat: "yyyy-MM-dd HH:mm:ss");

execute shell command from android

You should grab the standard input of the su process just launched and write down the command there, otherwise you are running the commands with the current UID.

Try something like this:

try{
    Process su = Runtime.getRuntime().exec("su");
    DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

    outputStream.writeBytes("screenrecord --time-limit 10 /sdcard/MyVideo.mp4\n");
    outputStream.flush();

    outputStream.writeBytes("exit\n");
    outputStream.flush();
    su.waitFor();
}catch(IOException e){
    throw new Exception(e);
}catch(InterruptedException e){
    throw new Exception(e);
}

Server.MapPath - Physical path given, virtual path expected

if you already know your folder is: E:\ftproot\sales then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/folder/folder1 and you want to know the real path in the disk...

String.Format not work in TypeScript

FIDDLE: https://jsfiddle.net/1ytxfcwx/

NPM: https://www.npmjs.com/package/typescript-string-operations

GITHUB: https://github.com/sevensc/typescript-string-operations

I implemented a class for String. Its not perfect but it works for me.

use it i.e. like this:

var getFullName = function(salutation, lastname, firstname) {
    return String.Format('{0} {1:U} {2:L}', salutation, lastname, firstname)
}

export class String {
    public static Empty: string = "";

    public static isNullOrWhiteSpace(value: string): boolean {
        try {
            if (value == null || value == 'undefined')
                return false;

            return value.replace(/\s/g, '').length < 1;
        }
        catch (e) {
            return false;
        }
    }

    public static Format(value, ...args): string {
        try {
            return value.replace(/{(\d+(:.*)?)}/g, function (match, i) {
                var s = match.split(':');
                if (s.length > 1) {
                    i = i[0];
                    match = s[1].replace('}', '');
                }

                var arg = String.formatPattern(match, args[i]);
                return typeof arg != 'undefined' && arg != null ? arg : String.Empty;
            });
        }
        catch (e) {
            return String.Empty;
        }
    }

    private static formatPattern(match, arg): string {
        switch (match) {
            case 'L':
                arg = arg.toLowerCase();
                break;
            case 'U':
                arg = arg.toUpperCase();
                break;
            default:
                break;
        }

        return arg;
    }
}

EDIT:

I extended the class and created a repository on github. It would be great if you can help to improve it!

https://github.com/sevensc/typescript-string-operations

or download the npm package

https://www.npmjs.com/package/typescript-string-operations

Class Diagrams in VS 2017

Noticed this in the beta and thought I had a bad install. The UI elements to add new Class Diagrams were missing and I was unable to open existing *.cd Class Diagram files in my solutions. Just upgraded to 2017 and found the problem remains. After some investigation it seems the Class Designer component is no longer installed by default.

Re-running the VS Installer and adding the Class Designer component restores both my ability to open and edit Class Diagrams as well as the UI elements needed to create new ones

VS Installer > Individual Components > Class Designer

Creating Roles in Asp.net Identity MVC 5

As an improvement on Peters code above you can use this:

   var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

   if (!roleManager.RoleExists("Member"))
            roleManager.Create(new IdentityRole("Member"));

What is the maximum number of characters that nvarchar(MAX) will hold?

2^31-1 bytes. So, a little less than 2^31-1 characters for varchar(max) and half that for nvarchar(max).

nchar and nvarchar

IIS_IUSRS and IUSR permissions in IIS8

I would use specific user (and NOT Application user). Then I will enable impersonation in the application. Once you do that whatever account is set as the specific user, those credentials would used to access local resources on that server (Not for external resources).

Specific User setting is specifically meant for accessing local resources.

Sql script to find invalid email addresses

I find this simple T-SQL query useful for returning valid e-mail addresses

SELECT email
FROM People
WHERE email LIKE '%_@__%.__%' 
    AND PATINDEX('%[^a-z,0-9,@,.,_]%', REPLACE(email, '-', 'a')) = 0

The PATINDEX bit eliminates all e-mail addresses containing characters that are not in the allowed a-z, 0-9, '@', '.', '_' & '-' set of characters.

It can be reversed to do what you want like this:

SELECT email
FROM People
WHERE NOT (email LIKE '%_@__%.__%' 
    AND PATINDEX('%[^a-z,0-9,@,.,_]%', REPLACE(email, '-', 'a')) = 0)

How to check the differences between local and github before the pull

git pull is really equivalent to running git fetch and then git merge. The git fetch updates your so-called "remote-tracking branches" - typically these are ones that look like origin/master, github/experiment, etc. that you see with git branch -r. These are like a cache of the state of branches in the remote repository that are updated when you do git fetch (or a successful git push).

So, suppose you've got a remote called origin that refers to your GitHub repository, you would do:

git fetch origin

... and then do:

git diff master origin/master

... in order to see the difference between your master, and the one on GitHub. If you're happy with those differences, you can merge them in with git merge origin/master, assuming master is your current branch.

Personally, I think that doing git fetch and git merge separately is generally a good idea.

Bootstrap date time picker

You don't need to give local path. just give cdn link of bootstrap datetimepicker. and it works.

_x000D_
_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
_x000D_
<body>_x000D_
_x000D_
   <div class="container">_x000D_
      <div class="row">_x000D_
        <div class='col-sm-6'>_x000D_
            <div class="form-group">_x000D_
                <div class='input-group date' id='datetimepicker'>_x000D_
                    <input type='text' class="form-control" />_x000D_
                    <span class="input-group-addon">_x000D_
                        <span class="glyphicon glyphicon-calendar"></span>_x000D_
                    </span>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
        <script type="text/javascript">_x000D_
            $(function () {_x000D_
                $('#datetimepicker').datepicker();_x000D_
            });_x000D_
        </script>_x000D_
      </div>_x000D_
   </div>_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Scroll to element on click in Angular 4

I have done something like what you're asking just by using jQuery to find the element (such as document.getElementById(...)) and using the .focus() call.

How to give spacing between buttons using bootstrap

using bootstrap you can add <div class="col-sm-1 col-xs-1 col-md-1 col-lg-1"></div> between buttons.

How to get query parameters from URL in Angular 5?

At, i think Angular 8:

ActivatedRoute.params has been replaced by ActivatedRoute.paramMap ActivatedRoute.queryParams has been replaced by ActivatedRoute.queryParamMap

Invert colors of an image in CSS or JavaScript

Can be done in major new broswers using the code below

.img {
    -webkit-filter:invert(100%);
     filter:progid:DXImageTransform.Microsoft.BasicImage(invert='1');
}

However, if you want it to work across all browsers you need to use Javascript. Something like this gist will do the job.

AngularJS: ng-show / ng-hide not working with `{{ }}` interpolation

Since ng-show is an angular attribute i think, we don't need to put the evaluation flower brackets ({{}})..

For attributes like class we need to encapsulate the variables with evaluation flower brackets ({{}}).

How do I read a specified line in a text file?

Read five lines each time, just put your statement in if statement , thats it

        String str1 = @"C:\Users\TEMP\Desktop\StaN.txt";   

        System.IO.StreamReader file = new System.IO.StreamReader(str1);

        line = file.ReadLine();

        Int32 ctn=0;

        try
        {

            while ((line = file.ReadLine()) != null)
            {

                    if (Counter == ctn)
                    {
                        MessageBox.Show("I am here");
                        ctn=ctn+5;
                        continue;
                    }
                    else
                    {
                        Counter++;
                        //MessageBox.Show(Counter.ToString());
                        MessageBox.Show(line.ToString());
                    } 
                }

            file.Close();
        }
        catch (Exception er)
        {

        }

Using <style> tags in the <body> with other HTML

I guess this may be an issue about limited contexts, e.g. WYIWYG editors on a web system used by not-programmers users, that limits the possibilities of follow the standards. Sometimes (like TinyMCE), it's a lib that puts your content/code inside a textarea tag, that is rendered by the editor as a big div tag. And sometimes, it may be an old version of these editors.

I'm supposing that:

  1. these not-programmers users don't have an open channel with the system admins (or institution's webdevs), to ask for including some CSS rules at the system's stylesheets. Actually, it would be impractical for the admins (or webdevs), considering the number of requests in that sense that they would have.
  2. this system is legacy and still doesn't support newer versions of HTML.

In some cases, without use style rules, it may be a very poor design experience. So, yes, these users need customization. Okay, but what would be the solutions, in this scenario? Considering the different ways to insert CSS in a html page, I suppose these solutions:


1st option: ask your sysadm

Ask to your system adm for including some CSS rules at the system's stylesheets. This will be an external or internal CSS solution. As already said, it might be not possible.


2nd option: <link> on <body>

Use external style sheet on the body tag, i.e., use of the link tag inside the area you have access (that will be, on the site, inside the body tag and not in the head tag). Some sources says this is okay, but "not a good practice", like MDN:

A <link> element can occur either in the <head> or <body> element, depending on whether it has a link type that is body-ok. For example, the stylesheet link type is body-ok, and therefore <link rel="stylesheet"> is permitted in the body. However, this isn't a good practice to follow; it makes more sense to separate your <link> elements from your body content, putting them in the <head>.

Some others, restrict it to the <head> section, like w3schools:

Note: This element goes only in the head section, but it can appear any number of times.

Testing

I tested it here (desktop environment, on a browser) and it works for me. Create a file foo.html:

<!DOCTYPE html>
<html>
<head></head>
<body>
    <link href="bar.css" type="text/css" rel="stylesheet">
    <h1 class="test1">Hello</h1>
    <h1 class="test2">World</h1>
</body>
</html>

And then a CSS file, at the same directory, called bar.css:

.test1 { 
    color: green;
};

Well, this will just looks possible if you have how upload an CSS file somewhere at the institution system. Maybe this would be the case.


3rd option: <style> on <body>

Use internet style sheet on the body tag, i.e., use of the style tag inside the area you have access (that will be, on the site, inside the body tag and not in the head tag). This is what Charles Salvia's and Sz's answers here are about. Choosing this option, consider their concerns.


4th, 5th and 6th options: JS ways

Alert These ones are related to modifying the <head> element of the page. Maybe this will not be allowed by the institution's system administrators. So, it's recommended to ask them permission first.

Okay, supposing permission granted, the strategy is access the <head>. How? JavaScript methods.

4th option: new <link> on <head>

This is another version of the 2nd option. Use external style sheet on the <head> tag, i.e., use of the <link> element outside the area you have access (that will be, on the site, not inside the body tag and yes inside the head tag). This solution complies with the recommendations of MDN and w3schools, as cited above, on 2nd option solution. A new Link object will be created.

To solve the matter through JS, there are many ways but at the following codelines I demonstrate one simple.

Testing

I tested it here (desktop environment, on a browser) and it works for me. Create a file f.html:

<!DOCTYPE html>
<html>
<head></head>
<body>
    <h1 class="test1">Hello</h1>
    <h1 class="test2">World</h1>
    <script>
        // JS code here
    </script>
</body>
</html>

Inside the script tag:

var newLink = document.createElement("link");
newLink.href = "bar.css";
newLink.rel = "stylesheet";
newLink.type = "text/css";
document.getElementsByTagName("head")[0].appendChild(newLink);

And then at the CSS file, at the same directory, called bar.css (as at the 2nd option):

.test1 { 
    color: green;
};

As I already said: this will just looks possible if you have how upload an CSS file somewhere at the institution system.

5th option: new <style> on <head>

Use new internal style sheet on the <head> tag, i.e., use of a new <style> element outside the area you have access (that will be, on the site, not inside the body tag and yes inside the head tag). A new Style object will be created.

This is solved through JS. One simple way is demonstrated following.

Testing

I tested it here (desktop environment, on a browser) and it works for me. Create a file foobar.html:

<!DOCTYPE html>
<html>
<head></head>
<body>
    <h1 class="test1">Hello</h1>
    <h1 class="test2">World</h1>
    <script>
        // JS code here
    </script>
</body>
</html>

Inside the script tag:

var newStyle = document.createElement("style");
newStyle.innerHTML = 
    "h1.test1 {"+
        "color: green;"+
    "}";
document.getElementsByTagName("head")[0].appendChild(newStyle);

6th option: using an existing <style> on <head>

Use an existing internal style sheet on the <head> tag, i.e., use of a <style> element outside the area you have access (that will be, on the site, not inside the body tag and yes inside the head tag), if some exists. A new Style object will be created or a CSSStyleSheet object will be used (in the code of the solution adopted here).

This is at some point of view risky. First, because it may not exists some <style> object. Depending of the way you implement this solution, you may get undefined return (the system may use external style sheet). Second, because you will be editing the system design author's work (authorship issues). Third, because it may not be allowed at your institution's IT politics of safety. So, do ask permission to do this (as at in other JS solutions).

Supposing, again, permission was granted:

You will need to consider some restrictions of the method available to this way: insertRule(). The solution proposed uses the default scenario, and a operation at the first stylesheet, if some exists.

Testing

I tested it here (desktop environment, on a browser) and it works for me. Create a file foo_bar.html:

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <h1 class="test1">Hello</h1>
    <h1 class="test2">World</h1>
    <script>
      // JS code here
    </script>
  </body>
</html>

Inside the script tag:

function demoLoop(){ // remove this line
    var elmnt = document.getElementsByTagName("style");
    if (elmnt.length === 0) {
        // there isn't style objects, so it's more interesting create one
        var newStyle = document.createElement("style");
        newStyle.innerHTML =
            "h1.test1 {" +
                "color: green;" +
            "}";
        document.getElementsByTagName("head")[0].appendChild(newStyle);
    } else {
        // Using CSSStyleSheet interface
        var firstCSS = document.styleSheets[0];
        firstCSS.insertRule("h1.test2{color:blue;}"); // at this way (without index specified), will be like an Array unshift() method
    }
} // remove this too
demoLoop(); // remove this too
demoLoop(); // remove this too

Another approach to this solution it's using CSSStyleDeclaration object (docs at w3schools and MDN). But it may not be interesting, considering the risk to override existing rules on the system's CSS.


7th option: inline CSS

Use inline CSS. This solve the problem, although depending of the page size (in code lines), the maintenance (by the author itself or other assigned person) of code can be very difficult.

But depending of the context of your role at the institution, or its web system security policies, this might be the unique available solution to you.

Testing

Create a file _foobar.html:

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <h1 style="color: green;">Hello</h1>
    <h1 style="color: blue;">World</h1>    
  </body>
</html>

Answering strictly the question asked by Gagan

How is a browser supposed to render css which is non contiguous?

  1. Is it supposed to generate some data structure using all the css styles on a page and use that for rendering?
  2. Or does it render using style information in the order it sees?

(quote adapted)

For a more accurate answer, I suggest Google these articles:

  • How Browsers Work: Behind the scenes of modern web browsers
  • Render-tree Construction, Layout, and Paint
  • What Does It Mean To “Render” a Webpage?
  • How browser rendering works — behind the scenes
  • Rendering - HTML Standard
  • 10 Rendering — HTML5

Get only specific attributes with from Laravel Collection

this is a follow up on the patricus [answer][1] above but for nested arrays:

$topLevelFields =  ['id','status'];
$userFields = ['first_name','last_name','email','phone_number','op_city_id'];

return $onlineShoppers->map(function ($user) { 
    return collect($user)->only($topLevelFields)
                             ->merge(collect($user['user'])->only($userFields))->all();  
    })->all();

How to include libraries in Visual Studio 2012?

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

example:

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

How to produce an csv output file from stored procedure in SQL Server

I have tried this and it is working fine for me:

sqlcmd -S servername -E -s~ -W -k1 -Q  "sql query here" > "\\file_path\file_name.csv"

How to work with complex numbers in C?

To extract the real part of a complex-valued expression z, use the notation as __real__ z. Similarly, use __imag__ attribute on the z to extract the imaginary part.

For example;

__complex__ float z;
float r;
float i;
r = __real__ z;
i = __imag__ z;

r is the real part of the complex number "z" i is the imaginary part of the complex number "z"