Programs & Examples On #Static members

A static member is a data field that is shared by all instances of a class or structure for the same program. Static member exists even when no objects of the static data member's class exist. A feature of C++, roughly equivalent to Java static fields.

How to initialize static variables

I use a combination of Tjeerd Visser's and porneL's answer.

class Something
{
    private static $foo;

    private static getFoo()
    {
        if ($foo === null)
            $foo = [[ complicated initializer ]]
        return $foo;
    }

    public static bar()
    {
        [[ do something with self::getFoo() ]]
    }
}

But an even better solution is to do away with the static methods and use the Singleton pattern. Then you just do the complicated initialization in the constructor. Or make it a "service" and use DI to inject it into any class that needs it.

How to initialize private static members in C++?

If you want to initialize some compound type (f.e. string) you can do something like that:

class SomeClass {
  static std::list<string> _list;

  public:
    static const std::list<string>& getList() {
      struct Initializer {
         Initializer() {
           // Here you may want to put mutex
           _list.push_back("FIRST");
           _list.push_back("SECOND");
           ....
         }
      }
      static Initializer ListInitializationGuard;
      return _list;
    }
};

As the ListInitializationGuard is a static variable inside SomeClass::getList() method it will be constructed only once, which means that constructor is called once. This will initialize _list variable to value you need. Any subsequent call to getList will simply return already initialized _list object.

Of course you have to access _list object always by calling getList() method.

Error message Strict standards: Non-static method should not be called statically in php

use className->function(); instead className::function() ;

How to replace plain URLs with links?

Try the below function :

function anchorify(text){
  var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  var text1=text.replace(exp, "<a href='$1'>$1</a>");
  var exp2 =/(^|[^\/])(www\.[\S]+(\b|$))/gim;
  return text1.replace(exp2, '$1<a target="_blank" href="http://$2">$2</a>');
}

alert(anchorify("Hola amigo! https://www.sharda.ac.in/academics/"));

Reading a resource file from within jar

Rather than trying to address the resource as a File just ask the ClassLoader to return an InputStream for the resource instead via getResourceAsStream:

InputStream in = getClass().getResourceAsStream("/file.txt"); 
BufferedReader reader = new BufferedReader(new InputStreamReader(in));

As long as the file.txt resource is available on the classpath then this approach will work the same way regardless of whether the file.txt resource is in a classes/ directory or inside a jar.

The URI is not hierarchical occurs because the URI for a resource within a jar file is going to look something like this: file:/example.jar!/file.txt. You cannot read the entries within a jar (a zip file) like it was a plain old File.

This is explained well by the answers to:

Losing Session State

I was only losing the session which was not a string or integer but a datarow. Putting the data in a serializable object and saving that into the session worked for me.

UIScrollView Scrollable Content Size Ambiguity

I was getting the same error.. i have done following

  1. View(Superview)
  2. ScrollView 0,0,600,600
  3. UIView inside ScrollView : 0,0,600,600
  4. UIView contains image view , label

Now add leading/trailing/top/bottom for scrollView(2) then UIView(3).

Select View(1) and View(3) set equally height and weight.. its solved my issue.

I have done the video that will help :

https://www.youtube.com/watch?v=s-CPN3xZS1A

Getting the difference between two repositories

See http://git.or.cz/gitwiki/GitTips, section "How to compare two local repositories" in "General".

In short you are using GIT_ALTERNATE_OBJECT_DIRECTORIES environment variable to have access to object database of the other repository, and using git rev-parse with --git-dir / GIT_DIR to convert symbolic name in other repository to SHA-1 identifier.

Modern version would look something like this (assuming that you are in 'repo_a'):

GIT_ALTERNATE_OBJECT_DIRECTORIES=../repo_b/.git/objects \
   git diff $(git --git-dir=../repo_b/.git rev-parse --verify HEAD) HEAD

where ../repo_b/.git is path to object database in repo_b (it would be repo_b.git if it were bare repository). Of course you can compare arbitrary versions, not only HEADs.


Note that if repo_a and repo_b are the same repository, it might make more sense to put both of them in the same repository, either using "git remote add -f ..." to create nickname(s) for repository for repeated updates, or obe off "git fetch ..."; as described in other responses.

Validating URL in Java

The java.net.URL class is in fact not at all a good way of validating URLs. MalformedURLException is not thrown on all malformed URLs during construction. Catching IOException on java.net.URL#openConnection().connect() does not validate URL either, only tell wether or not the connection can be established.

Consider this piece of code:

    try {
        new URL("http://.com");
        new URL("http://com.");
        new URL("http:// ");
        new URL("ftp://::::@example.com");
    } catch (MalformedURLException malformedURLException) {
        malformedURLException.printStackTrace();
    }

..which does not throw any exceptions.

I recommend using some validation API implemented using a context free grammar, or in very simplified validation just use regular expressions. However I need someone to suggest a superior or standard API for this, I only recently started searching for it myself.

Note It has been suggested that URL#toURI() in combination with handling of the exception java.net. URISyntaxException can facilitate validation of URLs. However, this method only catches one of the very simple cases above.

The conclusion is that there is no standard java URL parser to validate URLs.

Is there an equivalent of CSS max-width that works in HTML emails?

Yes, there is a way to emulate max-width using a table, thus giving you both responsive and Outlook-friendly layout. What's more, this solution doesn't require conditional comments.

Suppose you want the equivalent of a centered div with max-width of 350px. You create a table, set the width to 100%. The table has three cells in a row. Set the width of the center TD to 350 (using the HTML width attribute, not CSS), and there you go.

If you want your content aligned left instead of centered, just leave out the first empty cell.

Example:

<table border="0" cellspacing="0" width="100%">
    <tr>
        <td></td>
        <td width="350">The width of this cell should be a maximum of 
                  350 pixels, but shrink to widths less than 350 pixels.
        </td>
        <td></td>
     </tr>
</table> 

In the jsfiddle I give the table a border so you can see what's going on, but obviously you wouldn't want one in real life:

http://jsfiddle.net/YcwM7/

Mergesort with Python

def mergeSort(alist):
    print("Splitting ",alist)
    if len(alist)>1:
        mid = len(alist)//2
        lefthalf = alist[:mid]
        righthalf = alist[mid:]

        mergeSort(lefthalf)
        mergeSort(righthalf)

        i=0
        j=0
        k=0
        while i < len(lefthalf) and j < len(righthalf):
            if lefthalf[i] < righthalf[j]:
                alist[k]=lefthalf[i]
                i=i+1
            else:
                alist[k]=righthalf[j]
                j=j+1
            k=k+1

        while i < len(lefthalf):
            alist[k]=lefthalf[i]
            i=i+1
            k=k+1

        while j < len(righthalf):
            alist[k]=righthalf[j]
            j=j+1
            k=k+1
    print("Merging ",alist)

alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)

How to disable phone number linking in Mobile Safari?

You can also use the <a> label with javascript: void(0) as href value.

Example as follow:
<a href="javascript: void(0)">+44 456 77 89 87</a>

Getting Access Denied when calling the PutObject operation with bucket-level permission

If you have set public access for bucket and if it is still not working, edit bucker policy and paste following:

    {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:PutObject",
                "s3:PutObjectAcl",
                "s3:GetObject",
                "s3:GetObjectAcl",
                "s3:DeleteObject"
            ],
            "Resource": [
                "arn:aws:s3:::yourbucketnamehere",
                "arn:aws:s3:::yourbucketnamehere/*"
            ],
            "Effect": "Allow",
            "Principal": "*"
        }
    ]
}

OR condition in Regex

A classic "or" would be |. For example, ab|de would match either side of the expression.

However, for something like your case you might want to use the ? quantifier, which will match the previous expression exactly 0 or 1 times (1 times preferred; i.e. it's a "greedy" match). Another (probably more relyable) alternative would be using a custom character group:

\d+\s+[A-Z\s]+\s+[A-Z][A-Za-z]+

This pattern will match:

  • \d+: One or more numbers.
  • \s+: One or more whitespaces.
  • [A-Z\s]+: One or more uppercase characters or space characters
  • \s+: One or more whitespaces.
  • [A-Z][A-Za-z\s]+: An uppercase character followed by at least one more character (uppercase or lowercase) or whitespaces.

If you'd like a more static check, e.g. indeed only match ABC and A ABC, then you can combine a (non-matching) group and define the alternatives inside (to limit the scope):

\d (?:ABC|A ABC) Street

Or another alternative using a quantifier:

\d (?:A )?ABC Street

How do I get the XML root node with C#?

Agree with Jewes, XmlReader is the better way to go, especially if working with a larger XML document or processing multiple in a loop - no need to parse the entire document if you only need the document root.

Here's a simplified version, using XmlReader and MoveToContent().

http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.movetocontent.aspx

using (XmlReader xmlReader = XmlReader.Create(p_fileName))
{
  if (xmlReader.MoveToContent() == XmlNodeType.Element)
    rootNodeName = xmlReader.Name;
}

Create Setup/MSI installer in Visual Studio 2017

You need to install this extension to Visual Studio 2017/2019 in order to get access to the Installer Projects.

According to the page:

This extension provides the same functionality that currently exists in Visual Studio 2015 for Visual Studio Installer projects. To use this extension, you can either open the Extensions and Updates dialog, select the online node, and search for "Visual Studio Installer Projects Extension," or you can download directly from this page.

Once you have finished installing the extension and restarted Visual Studio, you will be able to open existing Visual Studio Installer projects, or create new ones.

How to overcome root domain CNAME restrictions?

I don't know how they are getting away with it, or what negative side effects their may be, but I'm using Hover.com to host some of my domains, and recently setup the apex of my domain as a CNAME there. Their DNS editing tool did not complain at all, and my domain happily resolves via the CNAME assigned.

Here is what Dig shows me for this domain (actual domain obfuscated as mydomain.com):

; <<>> DiG 9.8.3-P1 <<>> mydomain.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 2056
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;mydomain.com.          IN  A

;; ANSWER SECTION:
mydomain.com.       394 IN  CNAME   myapp.parseapp.com.
myapp.parseapp.com. 300 IN  CNAME   parseapp.com.
parseapp.com.       60  IN  A   54.243.93.102

Keyboard shortcut to comment lines in Sublime Text 3

For Brazilian ABNT Keyboards you do Ctrl + ; to comment and repeat it to remove the comment.

Get last field using awk substr

If you're open to a Perl solution, here one similar to fedorqui's awk solution:

perl -F/ -lane 'print $F[-1]' input

-F/ specifies / as the field separator
$F[-1] is the last element in the @F autosplit array

How do you post data with a link

I assume that each house is stored in its own table and has an 'id' field, e.g house id. So when you loop through the houses and display them, you could do something like this:

<a href="house.php?id=<?php echo $house_id;?>">
  <?php echo $house_name;?>
</a>

Then in house.php, you would get the house id using $_GET['id'], validate it using is_numeric() and then display its info.

What is the best comment in source code you have ever encountered?

Found in the JUnit API:

/**
 * ...as the moon sets over the early morning Merlin, Oregon
 * mountains, our intrepid adventurers type...
 */
public Test createTest(Class theClass, String name) {
    ...
}

How do I remove the passphrase for the SSH key without having to create a new key?

On the Mac you can store the passphrase for your private ssh key in your Keychain, which makes the use of it transparent. If you're logged in, it is available, when you are logged out your root user cannot use it. Removing the passphrase is a bad idea because anyone with the file can use it.

ssh-keygen -K

Add this to ~/.ssh/config

UseKeychain yes

?: operator (the 'Elvis operator') in PHP

It evaluates to the left operand if the left operand is truthy, and the right operand otherwise.

In pseudocode,

foo = bar ?: baz;

roughly resolves to

foo = bar ? bar : baz;

or

if (bar) {
    foo = bar;
} else {
    foo = baz;
}

with the difference that bar will only be evaluated once.

You can also use this to do a "self-check" of foo as demonstrated in the code example you posted:

foo = foo ?: bar;

This will assign bar to foo if foo is null or falsey, else it will leave foo unchanged.

Some more examples:

<?php
    var_dump(5 ?: 0); // 5
    var_dump(false ?: 0); // 0
    var_dump(null ?: 'foo'); // 'foo'
    var_dump(true ?: 123); // true
    var_dump('rock' ?: 'roll'); // 'rock'
?>

By the way, it's called the Elvis operator.

Elvis operator

Unable to find a @SpringBootConfiguration when doing a JpaTest

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureWebMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;



@RunWith(SpringRunner.class)
@DataJpaTest
@SpringBootTest
@AutoConfigureWebMvc
public class RepoTest {

    @Autowired
    private ThingShiftDetailsRepository thingShiftDetailsRepo;

    @Test
    public void findThingShiftDetails() {
            ShiftDetails details = new ShiftDetails();
            details.setThingId(1);

            thingShiftDetailsRepo.save(details);

            ShiftDetails dbDetails = thingShiftDetailsRepo.findByThingId(1);
            System.out.println(dbDetails);
    }
}

Above annotations worked well for me. I am using spring boot with JPA.

What is LDAP used for?

LDAP is also used to store your credentials in a network security system and retrieve it with your password and decrypted key giving you access to the services.

How do you select a particular option in a SELECT element in jQuery?

By value, what worked for me with jQuery 1.7 was the below code, try this:

$('#id option[value=theOptionValue]').prop('selected', 'selected').change();

Combining CSS Pseudo-elements, ":after" the ":last-child"

I am using the same technique in a media query which effectively turns a bullet list into an inline list on smaller devices as they save space.

So the change from:

  • List item 1
  • List item 2
  • List item 3

to:

List Item 1; List Item 2; List Item 3.

error 1265. Data truncated for column when trying to load data from txt file

This error can also be the result of not having the line,

FIELDS SPECIFIED BY ','

(if you're using commas to separate the fields) in your MySQL syntax, as described in this page of the MySQL docs.

Dart: mapping a list (list.map)

I try this same method, but with a different list with more values in the function map. My problem was to forget a return statement. This is very important :)

 bottom: new TabBar(
      controller: _controller,
      isScrollable: true,
      tabs:
        moviesTitles.map((title) { return Tab(text: title)}).toList()
      ,
    ),

How do I set the default locale in the JVM?

You can do this:

enter image description here

enter image description here

And to capture locale. You can do this:

private static final String LOCALE = LocaleContextHolder.getLocale().getLanguage()
            + "-" + LocaleContextHolder.getLocale().getCountry();

read subprocess stdout line by line

Indeed, if you sorted out the iterator then buffering could now be your problem. You could tell the python in the sub-process not to buffer its output.

proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)

becomes

proc = subprocess.Popen(['python','-u', 'fake_utility.py'],stdout=subprocess.PIPE)

I have needed this when calling python from within python.

Select DataFrame rows between two dates

With my testing of pandas version 0.22.0 you can now answer this question easier with more readable code by simply using between.

# create a single column DataFrame with dates going from Jan 1st 2018 to Jan 1st 2019
df = pd.DataFrame({'dates':pd.date_range('2018-01-01','2019-01-01')})

Let's say you want to grab the dates between Nov 27th 2018 and Jan 15th 2019:

# use the between statement to get a boolean mask
df['dates'].between('2018-11-27','2019-01-15', inclusive=False)

0    False
1    False
2    False
3    False
4    False

# you can pass this boolean mask straight to loc
df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=False)]

    dates
331 2018-11-28
332 2018-11-29
333 2018-11-30
334 2018-12-01
335 2018-12-02

Notice the inclusive argument. very helpful when you want to be explicit about your range. notice when set to True we return Nov 27th of 2018 as well:

df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=True)]

    dates
330 2018-11-27
331 2018-11-28
332 2018-11-29
333 2018-11-30
334 2018-12-01

This method is also faster than the previously mentioned isin method:

%%timeit -n 5
df.loc[df['dates'].between('2018-11-27','2019-01-15', inclusive=True)]
868 µs ± 164 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)


%%timeit -n 5

df.loc[df['dates'].isin(pd.date_range('2018-01-01','2019-01-01'))]
1.53 ms ± 305 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)

However, it is not faster than the currently accepted answer, provided by unutbu, only if the mask is already created. but if the mask is dynamic and needs to be reassigned over and over, my method may be more efficient:

# already create the mask THEN time the function

start_date = dt.datetime(2018,11,27)
end_date = dt.datetime(2019,1,15)
mask = (df['dates'] > start_date) & (df['dates'] <= end_date)

%%timeit -n 5
df.loc[mask]
191 µs ± 28.5 µs per loop (mean ± std. dev. of 7 runs, 5 loops each)

Missing Push Notification Entitlement

In XCode 8 you need to enable push in the Capabilities tab on your target, on top of enabling everything on the provisions and certificates: Xcode 8 "the aps-environment entitlement is missing from the app's signature" on submit

My blog post about this here.

Join between tables in two different databases?

SELECT *
FROM A.tableA JOIN B.tableB 

or

SELECT *
  FROM A.tableA JOIN B.tableB
  ON A.tableA.id = B.tableB.a_id;

How do I select the "last child" with a specific class name in CSS?

$('.class')[$(this).length - 1] 

or

$( "p" ).last().addClass( "selected" );

Mips how to store user input string

# This code works fine in QtSpim simulator

.data
    buffer: .space 20
    str1:  .asciiz "Enter string"
    str2:  .asciiz "You wrote:\n"

.text

main:
    la $a0, str1    # Load and print string asking for string
    li $v0, 4
    syscall

    li $v0, 8       # take in input

    la $a0, buffer  # load byte space into address
    li $a1, 20      # allot the byte space for string

    move $t0, $a0   # save string to t0
    syscall

    la $a0, str2    # load and print "you wrote" string
    li $v0, 4
    syscall

    la $a0, buffer  # reload byte space to primary address
    move $a0, $t0   # primary address = t0 address (load pointer)
    li $v0, 4       # print string
    syscall

    li $v0, 10      # end program
    syscall

Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

The controller function/object represents an abstraction model-view-controller (MVC). While there is nothing new to write about MVC, it is still the most significant advanatage of angular: split the concerns into smaller pieces. And that's it, nothing more, so if you need to react on Model changes coming from View the Controller is the right person to do that job.

The story about link function is different, it is coming from different perspective then MVC. And is really essential, once we want to cross the boundaries of a controller/model/view (template).

Let' start with the parameters which are passed into the link function:

function link(scope, element, attrs) {
  • scope is an Angular scope object.
  • element is the jqLite-wrapped element that this directive matches.
  • attrs is an object with the normalized attribute names and their corresponding values.

To put the link into the context, we should mention that all directives are going through this initialization process steps: Compile, Link. An Extract from Brad Green and Shyam Seshadri book Angular JS:

Compile phase (a sister of link, let's mention it here to get a clear picture):

In this phase, Angular walks the DOM to identify all the registered directives in the template. For each directive, it then transforms the DOM based on the directive’s rules (template, replace, transclude, and so on), and calls the compile function if it exists. The result is a compiled template function,

Link phase:

To make the view dynamic, Angular then runs a link function for each directive. The link functions typically creates listeners on the DOM or the model. These listeners keep the view and the model in sync at all times.

A nice example how to use the link could be found here: Creating Custom Directives. See the example: Creating a Directive that Manipulates the DOM, which inserts a "date-time" into page, refreshed every second.

Just a very short snippet from that rich source above, showing the real manipulation with DOM. There is hooked function to $timeout service, and also it is cleared in its destructor call to avoid memory leaks

.directive('myCurrentTime', function($timeout, dateFilter) {

 function link(scope, element, attrs) {

 ...

 // the not MVC job must be done
 function updateTime() {
   element.text(dateFilter(new Date(), format)); // here we are manipulating the DOM
 }

 function scheduleUpdate() {
   // save the timeoutId for canceling
   timeoutId = $timeout(function() {
     updateTime(); // update DOM
     scheduleUpdate(); // schedule the next update
   }, 1000);
 }

 element.on('$destroy', function() {
   $timeout.cancel(timeoutId);
 });

 ...

Gson: Directly convert String to JsonObject (no POJO)

Try to use getAsJsonObject() instead of a straight cast used in the accepted answer:

JsonObject o = new JsonParser().parse("{\"a\": \"A\"}").getAsJsonObject();

iPhone is not available. Please reconnect the device

Well, to be able to even get some information about why this happens, I did this:

  1. Open Xcode
  2. Go to windows ? Devices and Simulators
  3. Select your phone on the left
  4. Scroll down on the right side and see the error
  5. Enter image description here
  6. Update to latest Xcode version
  7. Update you phone to the latest iOS
  8. Unpair your phone from windows ? Devices and Simulators.
  9. Pair your iPhone
  10. Enjoy

twitter bootstrap autocomplete dropdown / combobox with Knockoutjs

Select2 for Bootstrap 3 native plugin

https://fk.github.io/select2-bootstrap-css/index.html

this plugin uses select2 jquery plugin

nuget

PM> Install-Package Select2-Bootstrap

UIWebView open links in Safari

Here's the Xamarin iOS equivalent of drawnonward's answer.

class WebviewDelegate : UIWebViewDelegate {
    public override bool ShouldStartLoad (UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType) {
        if (navigationType == UIWebViewNavigationType.LinkClicked) {
            UIApplication.SharedApplication.OpenUrl (request.Url);
            return false;
        }
        return true;
    }
}

How to strip HTML tags from string in JavaScript?

cleanText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");

Distilled from this website (web.achive).

This regex looks for <, an optional slash /, one or more characters that are not >, then either > or $ (the end of the line)

Examples:

'<div>Hello</div>' ==> 'Hello'
 ^^^^^     ^^^^^^
'Unterminated Tag <b' ==> 'Unterminated Tag '
                  ^^

But it is not bulletproof:

'If you are < 13 you cannot register' ==> 'If you are '
            ^^^^^^^^^^^^^^^^^^^^^^^^
'<div data="score > 42">Hello</div>' ==> ' 42">Hello'
 ^^^^^^^^^^^^^^^^^^          ^^^^^^

If someone is trying to break your application, this regex will not protect you. It should only be used if you already know the format of your input. As other knowledgable and mostly sane people have pointed out, to safely strip tags, you must use a parser.

If you do not have acccess to a convenient parser like the DOM, and you cannot trust your input to be in the right format, you may be better off using a package like sanitize-html, and also other sanitizers are available.

How can I get a first element from a sorted list?

Using Java 8 streams, you can turn your list into a stream and get the first item in a list using the .findFirst() method.

List<String> stringsList = Arrays.asList("zordon", "alpha", "tommy");
Optional<String> optional = stringsList.stream().findFirst();
optional.get(); // "zordon"

The .findFirst() method will return an Optional that may or may not contain a string value (it may not contain a value if the stringsList is empty).

Then to unwrap the item from the Optional use the .get() method.

How to make the web page height to fit screen height

you can use css to set the body tag to these settings:

body
{
padding:0px;
margin:0px;
width:100%;
height:100%;
}

Java JDBC connection status

You also can use

public boolean isDbConnected(Connection con) {
    try {
        return con != null && !con.isClosed();
    } catch (SQLException ignored) {}

    return false;
}

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

This could be solved without VBA by the following technique.

In this example I am counting all the threes (3) in the range A:A of the sheets Page M904, Page M905 and Page M906.

List all the sheet names in a single continuous range like in the following example. Here listed in the range D3:D5.

enter image description here

Then by having the lookup value in cell B2, the result can be found in cell B4 by using the following formula:

=SUMPRODUCT(COUNTIF(INDIRECT("'"&D3:D5&"'!A:A"), B2))

What are queues in jQuery?

This thread helped me a lot with my problem, but I've used $.queue in a different way and thought I would post what I came up with here. What I needed was a sequence of events (frames) to be triggered, but the sequence to be built dynamically. I have a variable number of placeholders, each of which should contain an animated sequence of images. The data is held in an array of arrays, so I loop through the arrays to build each sequence for each of the placeholders like this:

/* create an empty queue */
var theQueue = $({});
/* loop through the data array */
for (var i = 0; i < ph.length; i++) {
    for (var l = 0; l < ph[i].length; l++) {
        /* create a function which swaps an image, and calls the next function in the queue */
        theQueue.queue("anim", new Function("cb", "$('ph_"+i+"' img').attr('src', '/images/"+i+"/"+l+".png');cb();"));
        /* set the animation speed */
        theQueue.delay(200,'anim');
    }
}
/* start the animation */
theQueue.dequeue('anim');

This is a simplified version of the script I have arrived at, but should show the principle - when a function is added to the queue, it is added using the Function constructor - this way the function can be written dynamically using variables from the loop(s). Note the way the function is passed the argument for the next() call, and this is invoked at the end. The function in this case has no time dependency (it doesn't use $.fadeIn or anything like that), so I stagger the frames using $.delay.

Connect Java to a MySQL database

Short Code

public class DB {

    public static Connection c;

    public static Connection getConnection() throws Exception {
        if (c == null) {
            Class.forName("com.mysql.jdbc.Driver");
            c =DriverManager.getConnection("jdbc:mysql://localhost:3306/DATABASE", "USERNAME", "Password");
        }
        return c;
    }

    // Send data TO Database
    public static void setData(String sql) throws Exception {
        DB.getConnection().createStatement().executeUpdate(sql);
    }

    // Get Data From Database
    public static ResultSet getData(String sql) throws Exception {
        ResultSet rs = DB.getConnection().createStatement().executeQuery(sql);
        return rs;
    }
}

How to remove indentation from an unordered list item?

I have the same problem with a footer I'm trying to divide up. I found that this worked for me by trying few of above suggestions combined:

footer div ul {
    list-style-position: inside;
    padding-left: 0;
}

This seems to keep it to the left under my h1 and the bullet points inside the div rather than outside to the left.

No provider for HttpClient

I had same issue. After browsing and struggling with issue found the below solution

import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';

imports: [
  HttpModule,
  HttpClientModule
]

Import HttpModule and HttpClientModule in app.module.ts and add into the imports like mentioned above.

Error "can't load package: package my_prog: found packages my_prog and main"

Yes, each package must be defined in its own directory.

The source structure is defined in How to Write Go Code.

A package is a component that you can use in more than one program, that you can publish, import, get from an URL, etc. So it makes sense for it to have its own directory as much as a program can have a directory.

Setting environment variables via launchd.conf no longer works in OS X Yosemite/El Capitan/macOS Sierra/Mojave?

You can give https://github.com/ersiner/osx-env-sync a try. It handles both command line and GUI apps from a single source and works withe the latest version of OS X (Yosemite).

You can use path substitutions and other shell tricks since what you write is regular bash script to be sourced by bash in the first place. No restrictions.. (Check osx-env-sync documentation and you'll understand how it achieves this.)

I answered a similar question here where you'll find more.

HTML5 tag for horizontal line break

You can make a div that has the same attributes as the <hr> tag. This way it is fully able to be customized. Here is some sample code:

The HTML:

<h3>This is a header.</h3>
<div class="customHr">.</div>

<p>Here is some sample paragraph text.<br>
This demonstrates what could go below a custom hr.</p>

The CSS:

.customHr {
    width: 95%
    font-size: 1px;
    color: rgba(0, 0, 0, 0);
    line-height: 1px;

    background-color: grey;
    margin-top: -6px;
    margin-bottom: 10px;
}

To see how the project turns out, here is a JSFiddle for the above code: http://jsfiddle.net/SplashHero/qmccsc06/1/

What does "commercial use" exactly mean?

If the usage of something is part of the process of you making money, then it's generally considered a commercial use. If the purpose of the site is to, through some means or another, directly or indirectly, make you money, then it's probably commercial use.

If, on the other hand, something is merely incidental (not part of the process of production/working, but instead simply tacked on to the side), there are potential grounds for it not to be considered commercial use.

Detecting an "invalid date" Date instance in JavaScript

The selected answer is excellent, and I'm using it as well. However, if you're looking for a way to validate user date input, you should be aware that the Date object is very persistent about making what might appear to be invalid construction arguments into valid ones. The following unit test code illustrates the point:

QUnit.test( "valid date test", function( assert ) {
  //The following are counter-examples showing how the Date object will 
  //wrangle several 'bad' dates into a valid date anyway
  assert.equal(isValidDate(new Date(1980, 12, 15)), true);
  d = new Date();
  d.setFullYear(1980);
  d.setMonth(1);
  d.setDate(33);
  assert.equal(isValidDate(d), true);
  assert.equal(isValidDate(new Date(1980, 100, 150)), true);
  //If you go to this exterme, then the checker will fail
  assert.equal(isValidDate(new Date("This is junk")), false);
  //This is a valid date string
  assert.equal(isValidDate(new Date("November 17, 1989")), true);
  //but is this?
  assert.equal(isValidDate(new Date("November 35, 1989")), false);  
  //Ha!  It's not.  So, the secret to working with this version of 
  //isValidDate is to pass in dates as text strings... Hooboy
  //alert(d.toString());
});

How to reload apache configuration for a site without restarting apache?

Updated for Apache 2.4, for non-systemd (e.g., CentOS 6.x, Amazon Linux AMI) and for systemd (e.g., CentOS 7.x):

There are two ways of having the apache process reload the configuration, depending on what you want done with its current threads, either advise to exit when idle, or killing them directly.

Note that Apache recommends using apachectl -k as the command, and for systemd, the command is replaced by httpd -k

apachectl -k graceful or httpd -k graceful

Apache will advise its threads to exit when idle, and then apache reloads the configuration (it doesn't exit itself), this means statistics are not reset.

apachectl -k restart or httpd -k restart

This is similar to stop, in that the process kills off its threads, but then the process reloads the configuration file, rather than killing itself.

Source: https://httpd.apache.org/docs/2.4/stopping.html

Java: convert seconds to minutes, hours and days

You should try this

import java.util.Scanner;

public class Time_converter {

    public static void main(String[] args) {

        Scanner input = new Scanner (System.in);
        int seconds;
        int minutes ;
        int hours;
        System.out.print("Enter the number of seconds : ");
        seconds = input.nextInt();
        hours = seconds / 3600;
        minutes = (seconds%3600)/60;
        int seconds_output = (seconds% 3600)%60;


        System.out.println("The time entered in hours,minutes and seconds is:");
        System.out.println(hours  + " hours :" + minutes + " minutes:" + seconds_output +" seconds"); 
    }

}

String formatting in Python 3

Python 3.6 now supports shorthand literal string interpolation with PEP 498. For your use case, the new syntax is simply:

f"({self.goals} goals, ${self.penalties})"

This is similar to the previous .format standard, but lets one easily do things like:

>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal('12.34567')
>>> f'result: {value:{width}.{precision}}'
'result:      12.35'

Eclipse CDT project built but "Launch Failed. Binary Not Found"

Make sure that the folder name does not contain .c extension. When I removed the .c extension in my folder name it worked automatically.

How to get parameters from the URL with JSP

About the Implicit Objects of the Unified Expression Language, the Java EE 5 Tutorial writes:

Implicit Objects

The JSP expression language defines a set of implicit objects:

  • pageContext: The context for the JSP page. Provides access to various objects including:
    • servletContext: The context for the JSP page’s servlet and any web components contained in the same application. See Accessing the Web Context.
    • session: The session object for the client. See Maintaining Client State.
    • request: The request triggering the execution of the JSP page. See Getting Information from Requests.
    • response: The response returned by the JSP page. See Constructing Responses.
  • In addition, several implicit objects are available that allow easy access to the following objects:
    • param: Maps a request parameter name to a single value
    • paramValues: Maps a request parameter name to an array of values
    • header: Maps a request header name to a single value
    • headerValues: Maps a request header name to an array of values
    • cookie: Maps a cookie name to a single cookie
    • initParam: Maps a context initialization parameter name to a single value
  • Finally, there are objects that allow access to the various scoped variables described in Using Scope Objects.
    • pageScope: Maps page-scoped variable names to their values
    • requestScope: Maps request-scoped variable names to their values
    • sessionScope: Maps session-scoped variable names to their values
    • applicationScope: Maps application-scoped variable names to their values

The interesting parts are in bold :)

So, to answer your question, you should be able to access it like this (using EL):

${param.accountID}

Or, using JSP Scriptlets (not recommended):

<%
    String accountId = request.getParameter("accountID");
%>

Retrieve version from maven pom.xml in code

Sometimes the Maven command line is sufficient when scripting something related to the project version, e.g. for artifact retrieval via URL from a repository:

mvn help:evaluate -Dexpression=project.version -q -DforceStdout

Usage example:

VERSION=$( mvn help:evaluate -Dexpression=project.version -q -DforceStdout )
ARTIFACT_ID=$( mvn help:evaluate -Dexpression=project.artifactId -q -DforceStdout )
GROUP_ID_URL=$( mvn help:evaluate -Dexpression=project.groupId -q -DforceStdout | sed -e 's#\.#/#g' )
curl -f -S -O http://REPO-URL/mvn-repos/${GROUP_ID_URL}/${ARTIFACT_ID}/${VERSION}/${ARTIFACT_ID}-${VERSION}.jar

drag drop files into standard html file input

This is what I came out with.

Using Jquery and Html. This will add it to the insert files.

_x000D_
_x000D_
var dropzone = $('#dropzone')_x000D_
_x000D_
_x000D_
dropzone.on('drag dragstart dragend dragover dragenter dragleave drop', function(e) {_x000D_
    e.preventDefault();_x000D_
    e.stopPropagation();_x000D_
  })_x000D_
_x000D_
dropzone.on('dragover dragenter', function() {_x000D_
    $(this).addClass('is-dragover');_x000D_
  })_x000D_
dropzone.on('dragleave dragend drop', function() {_x000D_
    $(this).removeClass('is-dragover');_x000D_
  })  _x000D_
  _x000D_
dropzone.on('drop',function(e) {_x000D_
 var files = e.originalEvent.dataTransfer.files;_x000D_
 // Now select your file upload field _x000D_
 // $('input_field_file').prop('files',files)_x000D_
  });
_x000D_
input { margin: 15px 10px !important;}_x000D_
_x000D_
.dropzone {_x000D_
 padding: 50px;_x000D_
 border: 2px dashed #060;_x000D_
}_x000D_
_x000D_
.dropzone.is-dragover {_x000D_
  background-color: #e6ecef;_x000D_
}_x000D_
_x000D_
.dragover {_x000D_
 bg-color: red;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<div class="" draggable='true' style='padding: 20px'>_x000D_
 <div id='dropzone' class='dropzone'>_x000D_
  Drop Your File Here_x000D_
 </div>_x000D_
 </div>
_x000D_
_x000D_
_x000D_

How to allow users to check for the latest app version from inside the app?

You should first check the app version on the market and compare it with the version of the app on the device. If they are different, it may be an update available. In this post I wrote down the code for getting the current version of market and current version on the device and compare them together. I also showed how to show the update dialog and redirect the user to the update page. Please visit this link: https://stackoverflow.com/a/33925032/5475941

Java: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

I had the same problem with the certificates error and was because of SNI, and http client that I used didn't had SNI implemented. So an version update did the job

   <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.3.6</version>
    </dependency>

Merging two CSV files using Python

When I'm working with csv files, I often use the pandas library. It makes things like this very easy. For example:

import pandas as pd

a = pd.read_csv("filea.csv")
b = pd.read_csv("fileb.csv")
b = b.dropna(axis=1)
merged = a.merge(b, on='title')
merged.to_csv("output.csv", index=False)

Some explanation follows. First, we read in the csv files:

>>> a = pd.read_csv("filea.csv")
>>> b = pd.read_csv("fileb.csv")
>>> a
   title  stage    jan    feb
0   darn  3.001  0.421  0.532
1     ok  2.829  1.036  0.751
2  three  1.115  1.146  2.921
>>> b
   title    mar    apr    may       jun  Unnamed: 5
0   darn  0.631  1.321  0.951    1.7510         NaN
1     ok  1.001  0.247  2.456    0.3216         NaN
2  three  0.285  1.283  0.924  956.0000         NaN

and we see there's an extra column of data (note that the first line of fileb.csv -- title,mar,apr,may,jun, -- has an extra comma at the end). We can get rid of that easily enough:

>>> b = b.dropna(axis=1)
>>> b
   title    mar    apr    may       jun
0   darn  0.631  1.321  0.951    1.7510
1     ok  1.001  0.247  2.456    0.3216
2  three  0.285  1.283  0.924  956.0000

Now we can merge a and b on the title column:

>>> merged = a.merge(b, on='title')
>>> merged
   title  stage    jan    feb    mar    apr    may       jun
0   darn  3.001  0.421  0.532  0.631  1.321  0.951    1.7510
1     ok  2.829  1.036  0.751  1.001  0.247  2.456    0.3216
2  three  1.115  1.146  2.921  0.285  1.283  0.924  956.0000

and finally write this out:

>>> merged.to_csv("output.csv", index=False)

producing:

title,stage,jan,feb,mar,apr,may,jun
darn,3.001,0.421,0.532,0.631,1.321,0.951,1.751
ok,2.829,1.036,0.751,1.001,0.247,2.456,0.3216
three,1.115,1.146,2.921,0.285,1.283,0.924,956.0

How to register ASP.NET 2.0 to web server(IIS7)?

Open Control Panel - Programs - Turn Windows Features on or off expand - Internet Information Services expand - World Wide Web Services expand - Application development Features check - ASP.Net

Its advisable you check other feature to avoid future problem that might not give direct error messages Please don't forget to mark this question as answered if it solves your problem for the purpose of others

facebook Uncaught OAuthException: An active access token must be used to query information about the current user

Just check for the current Facebook user id $user and if it returned null then you need to reauthorize the user (or use the custom $_SESSION user id value - not recommended)

require 'facebook/src/facebook.php';


// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => 'APP_ID',
  'secret' => 'APP_SECRET',
));

$user = $facebook->getUser();

$photo_details = array('message' => 'my place');
$file='photos/my.jpg'; //Example image file
$photo_details['image'] = '@' . realpath($file);

if ($user) {
  try {
    // We have a valid FB session, so we can use 'me'
    $upload_photo = $facebook->api('/me/photos', 'post', $photo_details);
  } catch (FacebookApiException $e) {
    error_log($e);
  }
}


// login or logout url will be needed depending on current user state.
if ($user) {
  $logoutUrl = $facebook->getLogoutUrl();
} else {
// redirect to Facebook login to get a fresh user access_token
  $loginUrl = $facebook->getLoginUrl();
  header('Location: ' . $loginUrl);
}

I've written a tutorial on how to upload a picture to the user's wall.

How to allow download of .json file with ASP.NET

Just had this issue but had to find the config for IIS Express so I could add the mime types. For me, it was located at C:\Users\<username>\Documents\IISExpress\config\applicationhost.config and I was able to add in the correct "mime map" there.

How can I convert a file pointer ( FILE* fp ) to a file descriptor (int fd)?

Even if fileno(FILE *) may return a file descriptor, be VERY careful not to bypass stdio's buffer. If there is buffer data (either read or unflushed write), reads/writes from the file descriptor might give you unexpected results.

To answer one of the side questions, to convert a file descriptor to a FILE pointer, use fdopen(3)

Can I call methods in constructor in Java?

The constructor is called only once, so you can safely do what you want, however the disadvantage of calling methods from within the constructor, rather than directly, is that you don't get direct feedback if the method fails. This gets more difficult the more methods you call.

One solution is to provide methods that you can call to query the 'health' of the object once it's been constructed. For example the method isConfigOK() can be used to see if the config read operation was OK.

Another solution is to throw exceptions in the constructor upon failure, but it really depends on how 'fatal' these failures are.

class A
{
    Map <String,String> config = null;
    public A()
    {
        readConfig();
    }

    protected boolean readConfig()
    {
        ...
    }

    public boolean isConfigOK()
    {
        // Check config here
        return true;
    }
};

How to resolve git error: "Updates were rejected because the tip of your current branch is behind"

This issue occurs when someone has commited the code to develop/master and latest code has not been rebased from develop/master and you're trying to overwrite new changes to develop/master branch

Solution:

  • Take a backup if you're working on feature branch and switch to master/develop branch by doing git checkout develop/master
  • Do git pull
  • You will get changes and merge conflicts occur when you have made changes in the same file which has not been rebased from develop/master
  • Resolve the conflicts if it occurs and do git push,this should work

Why does MSBuild look in C:\ for Microsoft.Cpp.Default.props instead of c:\Program Files (x86)\MSBuild? ( error MSB4019)

I'm seeing this in a VS2017 environment. My build script calls VsDevCmd.bat first, and to solve this problem I set the VCTargetsPath environment variable after VsDevCmd and before calling MSBuild:

set VCTargetsPath=%VCIDEInstallDir%VCTargets

How to determine if a number is positive or negative?

It seems arbitrary to me because I don't know how you would get the number as any type, but what about checking Abs(number) != number? Maybe && number != 0

What's the simplest way to print a Java array?

In JDK1.8 you can use aggregate operations and a lambda expression:

String[] strArray = new String[] {"John", "Mary", "Bob"};

// #1
Arrays.asList(strArray).stream().forEach(s -> System.out.println(s));

// #2
Stream.of(strArray).forEach(System.out::println);

 // #3
 Arrays.stream(strArray).forEach(System.out::println);

/* output:
John
Mary
Bob
*/

Also, starting with Java 8, one could also take advantage of the join() method provided by the String class to print out array elements, without the brackets, and separated by a delimiter of choice (which is the space character for the example shown below)

string[] greeting = {"Hey", "there", "amigo!"};
String delimiter = " ";
String.join(delimiter, greeting) 

` The output will be "Hey there amigo!"

How to clear a chart from a canvas so that hover events cannot be triggered?

Chart.js has a bug: Chart.controller(instance) registers any new chart in a global property Chart.instances[] and deletes it from this property on .destroy().

But at chart creation Chart.js also writes ._meta property to dataset variable:

var meta = dataset._meta[me.id];
if (!meta) {
   meta = dataset._meta[me.id] = {
       type: null,
       data: [],
       dataset: null,
       controller: null,
       hidden: null,     // See isDatasetVisible() comment
       xAxisID: null,
       yAxisID: null
   };

and it doesn't delete this property on destroy().

If you use your old dataset object without removing ._meta property, Chart.js will add new dataset to ._meta without deletion previous data. Thus, at each chart's re-initialization your dataset object accumulates all previous data.

In order to avoid this, destroy dataset object after calling Chart.destroy().

Anaconda Installed but Cannot Launch Navigator

On windows 10, I faced the same error - only Anaconda Prompt was showing in the startup menu. What I did is i re-installed Anaconda and selected install for all users of the pc (in my initial installation I have installed only for current user).

What is the best way to do a substring in a batch file?

Nicely explained above!

For all those who may suffer like me to get this working in a localized Windows (mine is XP in Slovak), you may try to replace the % with a !

So:

SET TEXT=Hello World
SET SUBSTRING=!TEXT:~3,5!
ECHO !SUBSTRING!

Converting java.util.Properties to HashMap<String,String>

i use this:

for (Map.Entry<Object, Object> entry:properties.entrySet()) {
    map.put((String) entry.getKey(), (String) entry.getValue());
}

"replace" function examples

Here's an example where I found the replace( ) function helpful for giving me insight. The problem required a long integer vector be changed into a character vector and with its integers replaced by given character values.

## figuring out replace( )
(test <- c(rep(1,3),rep(2,2),rep(3,1)))

which looks like

[1] 1 1 1 2 2 3

and I want to replace every 1 with an A and 2 with a B and 3 with a C

letts <- c("A","B","C")

so in my own secret little "dirty-verse" I used a loop

for(i in 1:3)
{test <- replace(test,test==i,letts[i])}

which did what I wanted

test
[1] "A" "A" "A" "B" "B" "C"

In the first sentence I purposefully left out that the real objective was to make the big vector of integers a factor vector and assign the integer values (levels) some names (labels).

So another way of doing the replace( ) application here would be

(test <- factor(test,labels=letts))
[1] A A A B B C
Levels: A B C

Remove element from JSON Object

JSfiddle

function deleteEmpty(obj){
        for(var k in obj)
         if(k == "children"){
             if(obj[k]){
                     deleteEmpty(obj[k]);
             }else{
                   delete obj.children;
              } 
         }
    }

for(var i=0; i< a.children.length; i++){
 deleteEmpty(a.children[i])
}

how to make a jquery "$.post" request synchronous

If you want an synchronous request set the async property to false for the request. Check out the jQuery AJAX Doc

Error in finding last used cell in Excel with VBA

Note: this answer was motivated by this comment. The purpose of UsedRange is different from what is mentioned in the answer above.

As to the correct way of finding the last used cell, one has first to decide what is considered used, and then select a suitable method. I conceive at least three meanings:

  1. Used = non-blank, i.e., having data.

  2. Used = "... in use, meaning the section that contains data or formatting." As per official documentation, this is the criterion used by Excel at the time of saving. See also this official documentation. If one is not aware of this, the criterion may produce unexpected results, but it may also be intentionally exploited (less often, surely), e.g., to highlight or print specific regions, which may eventually have no data. And, of course, it is desirable as a criterion for the range to use when saving a workbook, lest losing part of one's work.

  3. Used = "... in use, meaning the section that contains data or formatting" or conditional formatting. Same as 2., but also including cells that are the target for any Conditional Formatting rule.

How to find the last used cell depends on what you want (your criterion).

For criterion 1, I suggest reading this answer. Note that UsedRange is cited as unreliable. I think that is misleading (i.e., "unfair" to UsedRange), as UsedRange is simply not meant to report the last cell containing data. So it should not be used in this case, as indicated in that answer. See also this comment.

For criterion 2, UsedRange is the most reliable option, as compared to other options also designed for this use. It even makes it unnecessary to save a workbook to make sure that the last cell is updated. Ctrl+End will go to a wrong cell prior to saving (“The last cell is not reset until you save the worksheet”, from http://msdn.microsoft.com/en-us/library/aa139976%28v=office.10%29.aspx. It is an old reference, but in this respect valid).

For criterion 3, I do not know any built-in method. Criterion 2 does not account for Conditional Formatting. One may have formatted cells, based on formulas, which are not detected by UsedRange or Ctrl+End. In the figure, the last cell is B3, since formatting was applied explicitly to it. Cells B6:D7 have a format derived from a Conditional Formatting rule, and this is not detected even by UsedRange. Accounting for this would require some VBA programming.

enter image description here


As to your specific question: What's the reason behind this?

Your code uses the first cell in your range E4:E48 as a trampoline, for jumping down with End(xlDown).

The "erroneous" output will obtain if there are no non-blank cells in your range other than perhaps the first. Then, you are leaping in the dark, i.e., down the worksheet (you should note the difference between blank and empty string!).

Note that:

  1. If your range contains non-contiguous non-blank cells, then it will also give a wrong result.

  2. If there is only one non-blank cell, but it is not the first one, your code will still give you the correct result.

Is there a way to detect if a browser window is not currently active?

This is an adaptation of the answer from Andy E.

This will do a task e.g. refresh the page every 30 seconds, but only if the page is visible and focused.

If visibility can't be detected, then only focus will be used.

If the user focuses the page, then it will update immediately

The page won't update again until 30 seconds after any ajax call

var windowFocused = true;
var timeOut2 = null;

$(function(){
  $.ajaxSetup ({
    cache: false
  });
  $("#content").ajaxComplete(function(event,request, settings){
       set_refresh_page(); // ajax call has just been made, so page doesn't need updating again for 30 seconds
   });
  // check visibility and focus of window, so as not to keep updating unnecessarily
  (function() {
      var hidden, change, vis = {
              hidden: "visibilitychange",
              mozHidden: "mozvisibilitychange",
              webkitHidden: "webkitvisibilitychange",
              msHidden: "msvisibilitychange",
              oHidden: "ovisibilitychange" /* not currently supported */
          };
      for (hidden in vis) {
          if (vis.hasOwnProperty(hidden) && hidden in document) {
              change = vis[hidden];
              break;
          }
      }
      document.body.className="visible";
      if (change){     // this will check the tab visibility instead of window focus
          document.addEventListener(change, onchange,false);
      }

      if(navigator.appName == "Microsoft Internet Explorer")
         window.onfocus = document.onfocusin = document.onfocusout = onchangeFocus
      else
         window.onfocus = window.onblur = onchangeFocus;

      function onchangeFocus(evt){
        evt = evt || window.event;
        if (evt.type == "focus" || evt.type == "focusin"){
          windowFocused=true; 
        }
        else if (evt.type == "blur" || evt.type == "focusout"){
          windowFocused=false;
        }
        if (evt.type == "focus"){
          update_page();  // only update using window.onfocus, because document.onfocusin can trigger on every click
        }

      }

      function onchange () {
        document.body.className = this[hidden] ? "hidden" : "visible";
        update_page();
      }

      function update_page(){
        if(windowFocused&&(document.body.className=="visible")){
          set_refresh_page(1000);
        }
      }


  })();
  set_refresh_page();
})

function get_date_time_string(){
  var d = new Date();
  var dT = [];
  dT.push(d.getDate());
  dT.push(d.getMonth())
  dT.push(d.getFullYear());
  dT.push(d.getHours());
  dT.push(d.getMinutes());
  dT.push(d.getSeconds());
  dT.push(d.getMilliseconds());
  return dT.join('_');
}

function do_refresh_page(){

// do tasks here

// e.g. some ajax call to update part of the page.

// (date time parameter will probably force the server not to cache)

//      $.ajax({
//        type: "POST",
//        url: "someUrl.php",
//        data: "t=" + get_date_time_string()+"&task=update",
//        success: function(html){
//          $('#content').html(html);
//        }
//      });

}

function set_refresh_page(interval){
  interval = typeof interval !== 'undefined' ? interval : 30000; // default time = 30 seconds
  if(timeOut2 != null) clearTimeout(timeOut2);
  timeOut2 = setTimeout(function(){
    if((document.body.className=="visible")&&windowFocused){
      do_refresh_page();
    }
    set_refresh_page();
  }, interval);
}

jQuery: If this HREF contains

use this

$("a").each(function () {
    var href=$(this).prop('href');
    if (href.indexOf('?') > -1) {
        alert("Contains questionmark");
    }
});

How to get a Color from hexadecimal Color String

For shortened Hex code

int red = colorString.charAt(1) == '0' ? 0 : 255;
int blue = colorString.charAt(2) == '0' ? 0 : 255;
int green = colorString.charAt(3) == '0' ? 0 : 255;
Color.rgb(red, green,blue);

Rounding a number to the nearest 5 or 10 or X

'Example: Round 499 to nearest 5. You would use the ROUND() FUNCTION.

a = inputbox("number to be rounded")
 b = inputbox("Round to nearest _______ ")


  strc = Round(A/B)
  strd = strc*B


 msgbox( a & ",  Rounded to the nearest " & b & ", is" & vbnewline & strd)

Removing Duplicate Values from ArrayList

if you want to use only arraylist then I am worried there is no better way which will create a huge performance benefit. But by only using arraylist i would check before adding into the list like following

void addToList(String s){
  if(!yourList.contains(s))
       yourList.add(s);
}

In this cases using a Set is suitable.

How to break out of a loop from inside a switch?

Premise

The following code should be considered bad form, regardless of language or desired functionality:

while( true ) {
}

Supporting Arguments

The while( true ) loop is poor form because it:

  • Breaks the implied contract of a while loop.
    • The while loop declaration should explicitly state the only exit condition.
  • Implies that it loops forever.
    • Code within the loop must be read to understand the terminating clause.
    • Loops that repeat forever prevent the user from terminating the program from within the program.
  • Is inefficient.
    • There are multiple loop termination conditions, including checking for "true".
  • Is prone to bugs.
    • Cannot easily determine where to put code that will always execute for each iteration.
  • Leads to unnecessarily complex code.
  • Automatic source code analysis.
    • To find bugs, program complexity analysis, security checks, or automatically derive any other source code behaviour without code execution, specifying the initial breaking condition(s) allows algorithms to determine useful invariants, thereby improving automatic source code analysis metrics.
  • Infinite loops.
    • If everyone always uses while(true) for loops that are not infinite, we lose the ability to concisely communicate when loops actually have no terminating condition. (Arguably, this has already happened, so the point is moot.)

Alternative to "Go To"

The following code is better form:

while( isValidState() ) {
  execute();
}

bool isValidState() {
  return msg->state != DONE;
}

Advantages

No flag. No goto. No exception. Easy to change. Easy to read. Easy to fix. Additionally the code:

  1. Isolates the knowledge of the loop's workload from the loop itself.
  2. Allows someone maintaining the code to easily extend the functionality.
  3. Allows multiple terminating conditions to be assigned in one place.
  4. Separates the terminating clause from the code to execute.
  5. Is safer for Nuclear Power plants. ;-)

The second point is important. Without knowing how the code works, if someone asked me to make the main loop let other threads (or processes) have some CPU time, two solutions come to mind:

Option #1

Readily insert the pause:

while( isValidState() ) {
  execute();
  sleep();
}

Option #2

Override execute:

void execute() {
  super->execute();
  sleep();
}

This code is simpler (thus easier to read) than a loop with an embedded switch. The isValidState method should only determine if the loop should continue. The workhorse of the method should be abstracted into the execute method, which allows subclasses to override the default behaviour (a difficult task using an embedded switch and goto).

Python Example

Contrast the following answer (to a Python question) that was posted on StackOverflow:

  1. Loop forever.
  2. Ask the user to input their choice.
  3. If the user's input is 'restart', continue looping forever.
  4. Otherwise, stop looping forever.
  5. End.
Code
while True: 
    choice = raw_input('What do you want? ')

    if choice == 'restart':
        continue
    else:
        break

print 'Break!' 

Versus:

  1. Initialize the user's choice.
  2. Loop while the user's choice is the word 'restart'.
  3. Ask the user to input their choice.
  4. End.
Code
choice = 'restart';

while choice == 'restart': 
    choice = raw_input('What do you want? ')

print 'Break!'

Here, while True results in misleading and overly complex code.

C pointer to array/array of pointers disambiguation

Use the cdecl program, as suggested by K&R.

$ cdecl
Type `help' or `?' for help
cdecl> explain int* arr1[8];
declare arr1 as array 8 of pointer to int
cdecl> explain int (*arr2)[8]
declare arr2 as pointer to array 8 of int
cdecl> explain int *(arr3[8])
declare arr3 as array 8 of pointer to int
cdecl>

It works the other way too.

cdecl> declare x as pointer to function(void) returning pointer to float
float *(*x)(void )

Is <div style="width: ;height: ;background: "> CSS?

1)Yes it is, when there is style then it is styling your code(css).2) is belong to html it is like a container that keep your css.

How to overcome "datetime.datetime not JSON serializable"?

The json.dumps method can accept an optional parameter called default which is expected to be a function. Every time JSON tries to convert a value it does not know how to convert it will call the function we passed to it. The function will receive the object in question, and it is expected to return the JSON representation of the object.

def myconverter(o):
 if isinstance(o, datetime.datetime):
    return o.__str__()

print(json.dumps(d, default = myconverter)) 

Keep values selected after form submission

Since WordPress already uses jQuery you can try something like this:

var POST=<?php echo json_encode($_POST); ?>;
for(k in POST){
  $("#"+k).val(POST[k]);
}

Split large string in n-size chunks in JavaScript

You can use reduce() without any regex:

(str, n) => {
  return str.split('').reduce(
    (acc, rec, index) => {
      return ((index % n) || !(index)) ? acc.concat(rec) : acc.concat(',', rec)
    },
    ''
  ).split(',')
}

ERROR: Error 1005: Can't create table (errno: 121)

I faced this error (errno 121) but it was caused by mysql-created intermediate tables that had been orphaned, preventing me from altering a table even though no such constraint name existed across any of my tables. At some point, my MySQL had crashed or failed to cleanup an intermediate table (table name starting with a #sql-) which ended up presenting me with an error such as: Can't create table '#sql-' (errno 121) when trying to run an ALTER TABLE with certain constraint names.

According to the docs at http://dev.mysql.com/doc/refman/5.7/en/innodb-troubleshooting-datadict.html , you can search for these orphan tables with:

SELECT * FROM INFORMATION_SCHEMA.INNODB_SYS_TABLES WHERE NAME LIKE '%#sql%';

The version I was working with was 5.1, but the above command only works on versions >= 5.6 (manual is incorrect about it working for 5.5 or earlier, because INNODB_SYS_TABLES does not exist in such versions). I was able to find the orphaned temporary table (which did not match the one named in the message) by searching my mysql data directory in command line:

find . -iname '#*'

After discovering the filename, such as #sql-9ad_15.frm, I was able to drop that orphaned table in MySQL:

USE myschema;
DROP TABLE `#mysql50##sql-9ad_15`;

After doing so, I was then able to successfully run my ALTER TABLE.

For completeness, as per the MySQL documentation linked, "the #mysql50# prefix tells MySQL to ignore file name safe encoding introduced in MySQL 5.1."

Choose File Dialog

I have implemented the Samsung File Selector Dialog, it provides the ability to open, save file, file extension filter, and create new directory in the same dialog I think it worth trying Here is the Link you have to log in to Samsung developer site to view the solution

CSS hide scroll bar, but have element scrollable

Similar to Kiloumap L'artélon's answer,

::-webkit-scrollbar {
    display:none;
}

works too

How to get images in Bootstrap's card to be the same height/width?

.card-img-top {
width: 100%;
height: 30vh;
object-fit: contain;
}

Contain will help in getting Complete Image displayed inside Card.

Adjust height "30vh" according to your need!

How to percent-encode URL parameters in Python?

In Python 3, urllib.quote has been moved to urllib.parse.quote and it does handle unicode by default.

>>> from urllib.parse import quote
>>> quote('/test')
'/test'
>>> quote('/test', safe='')
'%2Ftest'
>>> quote('/El Niño/')
'/El%20Ni%C3%B1o/'

MySQL Update Column +1?

update post set count = count + 1 where id = 101

What does int argc, char *argv[] mean?

Both of

int main(int argc, char *argv[]);
int main();

are legal definitions of the entry point for a C or C++ program. Stroustrup: C++ Style and Technique FAQ details some of the variations that are possible or legal for your main function.

What is the difference between Document style and RPC style communication?

An RPC style web service uses the names of the method and its parameters to generate XML structures representing a method’s call stack. Document style indicates the SOAP body contains an XML document which can be validated against pre-defined XML schema document.

A good starting point : SOAP Binding: Difference between Document and RPC Style Web Services

IIS Request Timeout on long ASP.NET operation

Remove ~ character in location so

path="~/Admin/SomePage.aspx"

becomes

path="Admin/SomePage.aspx"

OpenCV - DLL missing, but it's not?

No need to do any of that. It is a visual studio error.

just go here: http://connect.microsoft.com/VisualStudio/Downloads/DownloadDetails.aspx?DownloadID=31354

and download the appropriate fix for your computer's OS

close visual studio, run the fix and then restart VS

The code should run without any error.

How to suppress Pandas Future warning ?

Found this on github...

import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

import pandas

Dealing with HTTP content in HTTPS pages

I realise that this is an old thread but one option is just to remove the http: part from the image URL so that 'http://some/image.jpg' becomes '//some/image.jpg'. This will also work with CDNs

Github "Updates were rejected because the remote contains work that you do not have locally."

You may refer to: How to deal with "refusing to merge unrelated histories" error:

$ git pull --allow-unrelated-histories
$ git push -f origin master

Laravel 5 Carbon format datetime

Declare in model:

class ModelName extends Model
{      

 protected $casts = [
    'created_at' => 'datetime:d/m/Y', // Change your format
    'updated_at' => 'datetime:d/m/Y',
];

Extract file basename without path and extension in bash

Pure bash, no basename, no variable juggling. Set a string and echo:

p=/the/path/foo.txt
echo "${p//+(*\/|.*)}"

Output:

foo

Note: the bash extglob option must be "on", (Ubuntu sets extglob "on" by default), if it's not, do:

shopt -s extglob

Walking through the ${p//+(*\/|.*)}:

  1. ${p -- start with $p.
  2. // substitute every instance of the pattern that follows.
  3. +( match one or more of the pattern list in parenthesis, (i.e. until item #7 below).
  4. 1st pattern: *\/ matches anything before a literal "/" char.
  5. pattern separator | which in this instance acts like a logical OR.
  6. 2nd pattern: .* matches anything after a literal "." -- that is, in bash the "." is just a period char, and not a regex dot.
  7. ) end pattern list.
  8. } end parameter expansion. With a string substitution, there's usually another / there, followed by a replacement string. But since there's no / there, the matched patterns are substituted with nothing; this deletes the matches.

Relevant man bash background:

  1. pattern substitution:
  ${parameter/pattern/string}
          Pattern substitution.  The pattern is expanded to produce a pat
          tern just as in pathname expansion.  Parameter is  expanded  and
          the  longest match of pattern against its value is replaced with
          string.  If pattern begins with /, all matches  of  pattern  are
          replaced   with  string.   Normally  only  the  first  match  is
          replaced.  If pattern begins with #, it must match at the begin-
          ning of the expanded value of parameter.  If pattern begins with
          %, it must match at the end of the expanded value of  parameter.
          If string is null, matches of pattern are deleted and the / fol
          lowing pattern may be omitted.  If parameter is @ or *, the sub
          stitution  operation  is applied to each positional parameter in
          turn, and the expansion is the resultant list.  If parameter  is
          an  array  variable  subscripted  with  @ or *, the substitution
          operation is applied to each member of the array  in  turn,  and
          the expansion is the resultant list.
  1. extended pattern matching:
  If the extglob shell option is enabled using the shopt builtin, several
   extended  pattern  matching operators are recognized.  In the following
   description, a pattern-list is a list of one or more patterns separated
   by a |.  Composite patterns may be formed using one or more of the fol
   lowing sub-patterns:

          ?(pattern-list)
                 Matches zero or one occurrence of the given patterns
          *(pattern-list)
                 Matches zero or more occurrences of the given patterns
          +(pattern-list)
                 Matches one or more occurrences of the given patterns
          @(pattern-list)
                 Matches one of the given patterns
          !(pattern-list)
                 Matches anything except one of the given patterns

How to add number of days in postgresql datetime

For me I had to put the whole interval in single quotes not just the value of the interval.

select id,  
   title,
   created_at + interval '1 day' * claim_window as deadline from projects   

Instead of

select id,  
   title,
   created_at + interval '1' day * claim_window as deadline from projects   

Postgres Date/Time Functions

Creating a div element in jQuery

I think this is the best way to add a div:

To append a test div to the div element with ID div_id:

$("#div_id").append("div name along with id will come here, for example, test");

Now append HTML to this added test div:

$("#test").append("Your HTML");

Unsigned keyword in C++

Integer Types:

short            -> signed short
signed short
unsigned short
int              -> signed int
signed int
unsigned int
signed           -> signed int
unsigned         -> unsigned int
long             -> signed long
signed long
unsigned long

Be careful of char:

char  (is signed or unsigned depending on the implmentation)
signed char
unsigned char

Show percent % instead of counts in charts of categorical variables

As of March 2017, with ggplot2 2.2.1 I think the best solution is explained in Hadley Wickham's R for data science book:

ggplot(mydataf) + stat_count(mapping = aes(x=foo, y=..prop.., group=1))

stat_count computes two variables: count is used by default, but you can choose to use prop which shows proportions.

How to display Woocommerce product price by ID number on a custom page?

Other answers work, but

To get the full/default price:

$product->get_price_html();

Calling Oracle stored procedure from C#?

Please visit this ODP site set up by oracle for Microsoft OracleClient Developers: http://www.oracle.com/technetwork/topics/dotnet/index-085703.html

Also below is a sample code that can get you started to call a stored procedure from C# to Oracle. PKG_COLLECTION.CSP_COLLECTION_HDR_SELECT is the stored procedure built on Oracle accepting parameters PUNIT, POFFICE, PRECEIPT_NBR and returning the result in T_CURSOR.

using Oracle.DataAccess;
using Oracle.DataAccess.Client;

public DataTable GetHeader_BySproc(string unit, string office, string receiptno)
{
    using (OracleConnection cn = new OracleConnection(DatabaseHelper.GetConnectionString()))
    {
        OracleDataAdapter da = new OracleDataAdapter();
        OracleCommand cmd = new OracleCommand();
        cmd.Connection = cn;
        cmd.InitialLONGFetchSize = 1000;
        cmd.CommandText = DatabaseHelper.GetDBOwner() + "PKG_COLLECTION.CSP_COLLECTION_HDR_SELECT";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("PUNIT", OracleDbType.Char).Value = unit;
        cmd.Parameters.Add("POFFICE", OracleDbType.Char).Value = office;
        cmd.Parameters.Add("PRECEIPT_NBR", OracleDbType.Int32).Value = receiptno;
        cmd.Parameters.Add("T_CURSOR", OracleDbType.RefCursor).Direction = ParameterDirection.Output;

        da.SelectCommand = cmd;
        DataTable dt = new DataTable();
        da.Fill(dt);
        return dt;
    }
}

Label python data points on plot

I had a similar issue and ended up with this:

enter image description here

For me this has the advantage that data and annotation are not overlapping.

from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)

# annotations at the side (ordered by B values)
x0,x1=ax.get_xlim()
y0,y1=ax.get_ylim()
for ii, ind in enumerate(np.argsort(B)):
    x = A[ind]
    y = B[ind]
    xPos = x1 + .02 * (x1 - x0)
    yPos = y0 + ii * (y1 - y0)/(len(B) - 1)
    ax.annotate('',#label,
          xy=(x, y), xycoords='data',
          xytext=(xPos, yPos), textcoords='data',
          arrowprops=dict(
                          connectionstyle="arc3,rad=0.",
                          shrinkA=0, shrinkB=10,
                          arrowstyle= '-|>', ls= '-', linewidth=2
                          ),
          va='bottom', ha='left', zorder=19
          )
    ax.text(xPos + .01 * (x1 - x0), yPos,
            '({:.2f}, {:.2f})'.format(x,y),
            transform=ax.transData, va='center')

plt.grid()
plt.show()

Using the text argument in .annotate ended up with unfavorable text positions. Drawing lines between a legend and the data points is a mess, as the location of the legend is hard to address.

How to make type="number" to positive numbers only

If you try to enter a negative number, the onkeyup event blocks this and if you use the arrow on the input number, the onblur event resolves that part.

_x000D_
_x000D_
<input type="number" _x000D_
    onkeyup="if(this.value<0)this.value=1"_x000D_
    onblur="if(this.value<0)this.value=1"_x000D_
>
_x000D_
_x000D_
_x000D_

Creating a list/array in excel using VBA to get a list of unique names in a column

I realize this is an old question, but I use a much simpler way. Typically I just grab the list that I need, either by query or copying an existing list or whatever, then remove the duplicates. We will assume for this answer that your list is already in column C, row 4, as per the original question. This method works for whatever size list you have and you can select header yes or no.

Dim rng as range
Range("C4").Select
Set rng = Range(Selection, Selection.End(xlDown))
rng.RemoveDuplicates Columns:=1, Header:=xlYes

pyplot axes labels for subplots

The methods in the other answers will not work properly when the yticks are large. The ylabel will either overlap with ticks, be clipped on the left or completely invisible/outside of the figure.

I've modified Hagne's answer so it works with more than 1 column of subplots, for both xlabel and ylabel, and it shifts the plot to keep the ylabel visible in the figure.

def set_shared_ylabel(a, xlabel, ylabel, labelpad = 0.01, figleftpad=0.05):
    """Set a y label shared by multiple axes
    Parameters
    ----------
    a: list of axes
    ylabel: string
    labelpad: float
        Sets the padding between ticklabels and axis label"""

    f = a[0,0].get_figure()
    f.canvas.draw() #sets f.canvas.renderer needed below

    # get the center position for all plots
    top = a[0,0].get_position().y1
    bottom = a[-1,-1].get_position().y0

    # get the coordinates of the left side of the tick labels
    x0 = 1
    x1 = 1
    for at_row in a:
        at = at_row[0]
        at.set_ylabel('') # just to make sure we don't and up with multiple labels
        bboxes, _ = at.yaxis.get_ticklabel_extents(f.canvas.renderer)
        bboxes = bboxes.inverse_transformed(f.transFigure)
        xt = bboxes.x0
        if xt < x0:
            x0 = xt
            x1 = bboxes.x1
    tick_label_left = x0

    # shrink plot on left to prevent ylabel clipping
    # (x1 - tick_label_left) is the x coordinate of right end of tick label,
    # basically how much padding is needed to fit tick labels in the figure
    # figleftpad is additional padding to fit the ylabel
    plt.subplots_adjust(left=(x1 - tick_label_left) + figleftpad)

    # set position of label, 
    # note that (figleftpad-labelpad) refers to the middle of the ylabel
    a[-1,-1].set_ylabel(ylabel)
    a[-1,-1].yaxis.set_label_coords(figleftpad-labelpad,(bottom + top)/2, transform=f.transFigure)

    # set xlabel
    y0 = 1
    for at in axes[-1]:
        at.set_xlabel('')  # just to make sure we don't and up with multiple labels
        bboxes, _ = at.xaxis.get_ticklabel_extents(fig.canvas.renderer)
        bboxes = bboxes.inverse_transformed(fig.transFigure)
        yt = bboxes.y0
        if yt < y0:
            y0 = yt
    tick_label_bottom = y0

    axes[-1, -1].set_xlabel(xlabel)
    axes[-1, -1].xaxis.set_label_coords((left + right) / 2, tick_label_bottom - labelpad, transform=fig.transFigure)

It works for the following example, while Hagne's answer won't draw ylabel (since it's outside of the canvas) and KYC's ylabel overlaps with the tick labels:

import matplotlib.pyplot as plt
import itertools

fig, axes = plt.subplots(3, 4, sharey='row', sharex=True, squeeze=False)
fig.subplots_adjust(hspace=.5)
for i, a in enumerate(itertools.chain(*axes)):
    a.plot([0,4**i], [0,4**i])
    a.set_title(i)
set_shared_ylabel(axes, 'common X', 'common Y')
plt.show()

Alternatively, if you are fine with colorless axis, I've modified Julian Chen's solution so ylabel won't overlap with tick labels.

Basically, we just have to set ylims of the colorless so it matches the largest ylims of the subplots so the colorless tick labels sets the correct location for the ylabel.

Again, we have to shrink the plot to prevent clipping. Here I've hard coded the amount to shrink, but you can play around to find a number that works for you or calculate it like in the method above.

import matplotlib.pyplot as plt
import itertools

fig, axes = plt.subplots(3, 4, sharey='row', sharex=True, squeeze=False)
fig.subplots_adjust(hspace=.5)
miny = maxy = 0
for i, a in enumerate(itertools.chain(*axes)):
    a.plot([0,4**i], [0,4**i])
    a.set_title(i)
    miny = min(miny, a.get_ylim()[0])
    maxy = max(maxy, a.get_ylim()[1])

# add a big axes, hide frame
# set ylim to match the largest range of any subplot
ax_invis = fig.add_subplot(111, frameon=False)
ax_invis.set_ylim([miny, maxy])

# hide tick and tick label of the big axis
plt.tick_params(labelcolor='none', top=False, bottom=False, left=False, right=False)
plt.xlabel("common X")
plt.ylabel("common Y")

# shrink plot to prevent clipping
plt.subplots_adjust(left=0.15)
plt.show()

What do I need to do to get Internet Explorer 8 to accept a self signed certificate?

I have tried lots and lots of steps from different people posted on different websites. But none of them mention that I should add the certificate into the Trusted People keystore.

That's right, placing it under trusted CA is not enough for my case, I have to put the certs inside the Trusted People also.

That's:

  1. Run MMC
  2. Add Certificate Snap-in choose Local Computer
  3. Expand Certificates(Local Computer) -> Trusted People -> Certificates
  4. Right click All Task -> Import
  5. Finish the wizard

To export the certificate:

  1. Run IE as admin (right click, run as admin)
  2. When prompted invalid cert, go ahead visit the website anyway
  3. Click the certificate error near the address, click view certificate
  4. Go to Details tab, click Copy To file
  5. Save as *.cer file.

I'm on IE9, Windows 7

Why don't self-closing script elements work?

In case anyone's curious, the ultimate reason is that HTML was originally a dialect of SGML, which is XML's weird older brother. In SGML-land, elements can be specified in the DTD as either self-closing (e.g. BR, HR, INPUT), implicitly closeable (e.g. P, LI, TD), or explicitly closeable (e.g. TABLE, DIV, SCRIPT). XML, of course, has no concept of this.

The tag-soup parsers used by modern browsers evolved out of this legacy, although their parsing model isn't pure SGML anymore. And of course, your carefully-crafted XHTML is being treated as badly-written SGML-inspired tag-soup unless you send it with an XML mime type. This is also why...

<p><div>hello</div></p>

...gets interpreted by the browser as:

<p></p><div>hello</div><p></p>

...which is the recipe for a lovely obscure bug that can throw you into fits as you try to code against the DOM.

How to add "on delete cascade" constraints?

Usage:

select replace_foreign_key('user_rates_posts', 'post_id', 'ON DELETE CASCADE');

Function:

CREATE OR REPLACE FUNCTION 
    replace_foreign_key(f_table VARCHAR, f_column VARCHAR, new_options VARCHAR) 
RETURNS VARCHAR
AS $$
DECLARE constraint_name varchar;
DECLARE reftable varchar;
DECLARE refcolumn varchar;
BEGIN

SELECT tc.constraint_name, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name 
FROM 
    information_schema.table_constraints AS tc 
    JOIN information_schema.key_column_usage AS kcu
      ON tc.constraint_name = kcu.constraint_name
    JOIN information_schema.constraint_column_usage AS ccu
      ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY' 
   AND tc.table_name= f_table AND kcu.column_name= f_column
INTO constraint_name, reftable, refcolumn;

EXECUTE 'alter table ' || f_table || ' drop constraint ' || constraint_name || 
', ADD CONSTRAINT ' || constraint_name || ' FOREIGN KEY (' || f_column || ') ' ||
' REFERENCES ' || reftable || '(' || refcolumn || ') ' || new_options || ';';

RETURN 'Constraint replaced: ' || constraint_name || ' (' || f_table || '.' || f_column ||
 ' -> ' || reftable || '.' || refcolumn || '); New options: ' || new_options;

END;
$$ LANGUAGE plpgsql;

Be aware: this function won't copy attributes of initial foreign key. It only takes foreign table name / column name, drops current key and replaces with new one.

java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication Maven

The answer to the above question is "none of the above". When you download new STS it won't support the old Spring Boot parent version. Just update parent version with latest comes with STS it will work.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

If you have problem getting the latest, just create a new Spring Starter Project. Go to File->New->Spring Start Project and create a demo project you will get the latest parent version, change your version with that all will work. I do this every time I change STS.

Create directory if it does not exist

Use:

$path = "C:\temp\"

If (!(test-path $path))
{
    md C:\Temp\
}
  • The first line creates a variable named $path and assigns it the string value of "C:\temp\"

  • The second line is an If statement which relies on the Test-Path cmdlet to check if the variable $path does not exist. The not exists is qualified using the ! symbol.

  • Third line: If the path stored in the string above is not found, the code between the curly brackets will be run.

md is the short version of typing out: New-Item -ItemType Directory -Path $path

Note: I have not tested using the -Force parameter with the below to see if there is undesirable behavior if the path already exists.

New-Item -ItemType Directory -Path $path

How do I disable log messages from the Requests library?

Kbrose's guidance on finding which logger was generating log messages was immensely useful. For my Django project, I had to sort through 120 different loggers until I found that it was the elasticsearch Python library that was causing issues for me. As per the guidance in most of the questions, I disabled it by adding this to my loggers:

      ...
      'elasticsearch': {
          'handlers': ['console'],
          'level': logging.WARNING,
      },     
      ...

Posting here in case someone else is seeing the unhelpful log messages come through whenever they run an Elasticsearch query.

How to convert 2D float numpy array to 2D int numpy array?

If you're not sure your input is going to be a Numpy array, you can use asarray with dtype=int instead of astype:

>>> np.asarray([1,2,3,4], dtype=int)
array([1, 2, 3, 4])

If the input array already has the correct dtype, asarray avoids the array copy while astype does not (unless you specify copy=False):

>>> a = np.array([1,2,3,4])
>>> a is np.asarray(a)  # no copy :)
True
>>> a is a.astype(int)  # copy :(
False
>>> a is a.astype(int, copy=False)  # no copy :)
True

phpMyAdmin + CentOS 6.0 - Forbidden

I had the same issue.

Only after I changed in php.ini variable

display_errors = Off

to

display_errors = On

Phpadmin started working.. crazy....

Assert a function/method was not called using Mock

Judging from other answers, no one except @rob-kennedy talked about the call_args_list.

It's a powerful tool for that you can implement the exact contrary of MagicMock.assert_called_with()

call_args_list is a list of call objects. Each call object represents a call made on a mocked callable.

>>> from unittest.mock import MagicMock
>>> m = MagicMock()
>>> m.call_args_list
[]
>>> m(42)
<MagicMock name='mock()' id='139675158423872'>
>>> m.call_args_list
[call(42)]
>>> m(42, 30)
<MagicMock name='mock()' id='139675158423872'>
>>> m.call_args_list
[call(42), call(42, 30)]

Consuming a call object is easy, since you can compare it with a tuple of length 2 where the first component is a tuple containing all the positional arguments of the related call, while the second component is a dictionary of the keyword arguments.

>>> ((42,),) in m.call_args_list
True
>>> m(42, foo='bar')
<MagicMock name='mock()' id='139675158423872'>
>>> ((42,), {'foo': 'bar'}) in m.call_args_list
True
>>> m(foo='bar')
<MagicMock name='mock()' id='139675158423872'>
>>> ((), {'foo': 'bar'}) in m.call_args_list
True

So, a way to address the specific problem of the OP is

def test_something():
    with patch('something') as my_var:
        assert ((some, args),) not in my_var.call_args_list

Note that this way, instead of just checking if a mocked callable has been called, via MagicMock.called, you can now check if it has been called with a specific set of arguments.

That's useful. Say you want to test a function that takes a list and call another function, compute(), for each of the value of the list only if they satisfy a specific condition.

You can now mock compute, and test if it has been called on some value but not on others.

Convert columns to string in Pandas

Here's the other one, particularly useful to convert the multiple columns to string instead of just single column:

In [76]: import numpy as np
In [77]: import pandas as pd
In [78]: df = pd.DataFrame({
    ...:     'A': [20, 30.0, np.nan],
    ...:     'B': ["a45a", "a3", "b1"],
    ...:     'C': [10, 5, np.nan]})
    ...: 

In [79]: df.dtypes ## Current datatype
Out[79]: 
A    float64
B     object
C    float64
dtype: object

## Multiple columns string conversion
In [80]: df[["A", "C"]] = df[["A", "C"]].astype(str) 

In [81]: df.dtypes ## Updated datatype after string conversion
Out[81]: 
A    object
B    object
C    object
dtype: object

Unable to merge dex

For me it was updating the firebase messaging in app\build.gradle:

compile 'com.google.firebase:firebase-messaging:10.0.1'

to

compile 'com.google.firebase:firebase-messaging:11.4.2'

Log4j output not displayed in Eclipse console

There is a case I make: exception happen in somewhere, but I catched the exception without print anything, thus the code didn't even reach the log4j code, so no output.

Reading content from URL with Node.js

the data object is a buffer of bytes. Simply call .toString() to get human-readable code:

console.log( data.toString() );

reference: Node.js buffers

Unable to open debugger port in IntelliJ

Set the MAVEN_OPTS. It should work !!

export MAVEN_OPTS="-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=4000,server=y,suspend=n"

mvn spring-boot:run -Dserver.port=8090

pip3: command not found but python3-pip is already installed

Probably pip3 is installed in /usr/local/bin/ which is not in the PATH of the sudo (root) user. Use this instead

sudo /usr/local/bin/pip3 install virtualenv

Calling startActivity() from outside of an Activity?

Try changing to this line:

PendingIntent pendingIntent = PendingIntent.getBroadcast(getContext(), 0, i, 0);

YouTube iframe embed - full screen

jut add allowfullscreen="true" to iframe

  <iframe src="URL here" allowfullscreen="true"> </iframe>

AttributeError: 'module' object has no attribute 'urlopen'

Use six module to make you code compatible between python2 and python3

urllib.request.urlopen("<your-url>")```

Looking to understand the iOS UIViewController lifecycle

Haider's answer is correct for pre-iOS 6. However, as of iOS 6 viewDidUnload and viewWillUnload are never called. The docs state: "Views are no longer purged under low-memory conditions and so this method is never called."

Is it not possible to stringify an Error using JSON.stringify?

You can solve this with a one-liner( errStringified ) in plain javascript:

var error = new Error('simple error message');
var errStringified = (err => JSON.stringify(Object.getOwnPropertyNames(Object.getPrototypeOf(err)).reduce(function(accumulator, currentValue) { return accumulator[currentValue] = err[currentValue], accumulator}, {})))(error);
console.log(errStringified);

It works with DOMExceptions as well.

Turn on torch/flash on iPhone

iWasRobbed's answer is great, except there is an AVCaptureSession running in the background all the time. On my iPhone 4s it takes about 12% CPU power according to Instrument so my app took about 1% battery in a minute. In other words if the device is prepared for AV capture it's not cheap.

Using the code below my app requires 0.187% a minute so the battery life is more than 5x longer.

This code works just fine on any device (tested on both 3GS (no flash) and 4s). Tested on 4.3 in simulator as well.

#import <AVFoundation/AVFoundation.h>

- (void) turnTorchOn:(BOOL)on {

    Class captureDeviceClass = NSClassFromString(@"AVCaptureDevice");
    if (captureDeviceClass != nil) {
        AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        if ([device hasTorch] && [device hasFlash]){

            [device lockForConfiguration:nil];
            if (on) {
                [device setTorchMode:AVCaptureTorchModeOn];
                [device setFlashMode:AVCaptureFlashModeOn];
                torchIsOn = YES;
            } else {
                [device setTorchMode:AVCaptureTorchModeOff];
                [device setFlashMode:AVCaptureFlashModeOff];
                torchIsOn = NO;            
            }
            [device unlockForConfiguration];
        }
    }
}

How to iterate over the files of a certain directory, in Java?

I guess there are so many ways to make what you want. Here's a way that I use. With the commons.io library you can iterate over the files in a directory. You must use the FileUtils.iterateFiles method and you can process each file.

You can find the information here: http://commons.apache.org/proper/commons-io/download_io.cgi

Here's an example:

Iterator it = FileUtils.iterateFiles(new File("C:/"), null, false);
        while(it.hasNext()){
            System.out.println(((File) it.next()).getName());
        }

You can change null and put a list of extentions if you wanna filter. Example: {".xml",".java"}

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

FAQ

Questions from the top of my head since that time I gone crazy with jacoco.

My application server (jBoss, Glassfish..) located in Iraq, Syria, whatever.. Is it possible to get multi-module coverage when running integration tests on it? Jenkins and Sonar are also on different servers.

Yes. You have to use jacoco agent that runs in mode output=tcpserver, jacoco ant lib. Basically two jars. This will give you 99% success.

How does jacoco agent works?

You append a string

-javaagent:[your_path]/jacocoagent.jar=destfile=/jacoco.exec,output=tcpserver,address=*

to your application server JAVA_OPTS and restart it. In this string only [your_path] have to be replaced with the path to jacocoagent.jar, stored(store it!) on your VM where app server runs. Since that time you start app server, all applications that are deployed will be dynamically monitored and their activity (meaning code usage) will be ready for you to get in jacocos .exec format by tcl request.

Could I reset jacoco agent to start collecting execution data only since the time my test start?

Yes, for that purpose you need jacocoant.jar and ant build script located in your jenkins workspace.

So basically what I need from http://www.eclemma.org/jacoco/ is jacocoant.jar located in my jenkins workspace, and jacocoagent.jar located on my app server VM?

That's right.

I don't want to use ant, I've heard that jacoco maven plugin can do all the things too.

That's not right, jacoco maven plugin can collect unit test data and some integration tests data(see Arquillian Jacoco), but if you have for example rest assured tests as a separated build in jenkins, and want to show multi-module coverage, I can't see how maven plugin can help you.

What exactly does jacoco agent produce?

Only coverage data in .exec format. Sonar then can read it.

Does jacoco need to know where my java classes located are?

No, sonar does, but not jacoco. When you do mvn sonar:sonar path to classes comes into play.

So what about the ant script?

It has to be presented in your jenkins workspace. Mine ant script, I called it jacoco.xml looks like that:

<project name="Jacoco library to collect code coverage remotely" xmlns:jacoco="antlib:org.jacoco.ant">
    <property name="jacoco.port" value="6300"/>
    <property name="jacocoReportFile" location="${workspace}/it-jacoco.exec"/>

    <taskdef uri="antlib:org.jacoco.ant" resource="org/jacoco/ant/antlib.xml">
        <classpath path="${workspace}/tools/jacoco/jacocoant.jar"/>
    </taskdef>

    <target name="jacocoReport">
            <jacoco:dump address="${jacoco.host}" port="${jacoco.port}" dump="true" reset="true" destfile="${jacocoReportFile}" append="false"/>
    </target>

    <target name="jacocoReset">
            <jacoco:dump address="${jacoco.host}" port="${jacoco.port}" reset="true" destfile="${jacocoReportFile}" append="false"/>
        <delete file="${jacocoReportFile}"/>
    </target>
</project>

Two mandatory params you should pass when invoking this script -Dworkspace=$WORKSPACE use it to point to your jenkins workspace and -Djacoco.host=yourappserver.com host without http://

Also notice that I put my jacocoant.jar to ${workspace}/tools/jacoco/jacocoant.jar

What should I do next?

Did you start your app server with jacocoagent.jar?

Did you put ant script and jacocoant.jar in your jenkins workspace?

If yes the last step is to configure a jenkins build. Here is the strategy:

  1. Invoke ant target jacocoReset to reset all previously collected data.
  2. Run your tests
  3. Invoke ant target jacocoReport to get report

If everything is right, you will see it-jacoco.exec in your build workspace.

Look at the screenshot, I also have ant installed in my workspace in $WORKSPACE/tools/ant dir, but you can use one that is installed in your jenkins.

enter image description here

How to push this report in sonar?

Maven sonar:sonar will do the job (don't forget to configure it), point it to main pom.xml so it will run through all modules. Use sonar.jacoco.itReportPath=$WORKSPACE/it-jacoco.exec parameter to tell sonar where your integration test report is located. Every time it will analyse new module classes, it will look for information about coverage in it-jacoco.exec.

I already have jacoco.exec in my `target` dir, `mvn sonar:sonar` ignores/removes it

By default mvn sonar:sonar does clean and deletes your target dir, use sonar.dynamicAnalysis=reuseReports to avoid it.

Microsoft.ReportViewer.Common Version=12.0.0.0

Version 12 of the ReportViewer bits is referred to as Microsoft Report Viewer 2015 Runtime and can downloaded for installation from the following link:

https://www.microsoft.com/en-us/download/details.aspx?id=45496

UPDATE:

The ReportViewer bits are also available as a NUGET package: https://www.nuget.org/packages/Microsoft.ReportViewer.Runtime.Common/12.0.2402.15

Install-Package Microsoft.ReportViewer.Runtime.Common

405 method not allowed Web API

Chrome often times tries to do an OPTIONS call before doing a post. It does this to make sure the CORS headers are in order. It can be problematic if you are not handling the OPTIONS call in your API controller.

public void Options() { }

How to hide command output in Bash

You can redirect stdout to /dev/null.

yum install nano > /dev/null

Or you can redirect both stdout and stderr,

yum install nano &> /dev/null.

But if the program has a quiet option, that's even better.

Reload nginx configuration

Maybe you're not doing it as root?

Try sudo nginx -s reload, if it still doesn't work, you might want to try sudo pkill -HUP nginx.

Path.Combine absolute with relative path strings


Path.GetFullPath(@"c:\windows\temp\..\system32")?

sql set variable using COUNT

You can select directly into the variable rather than using set:

DECLARE @times int

SELECT @times = COUNT(DidWin)
FROM thetable
WHERE DidWin = 1 AND Playername='Me'

If you need to set multiple variables you can do it from the same select (example a bit contrived):

DECLARE @wins int, @losses int

SELECT @wins = SUM(DidWin), @losses = SUM(DidLose)
FROM thetable
WHERE Playername='Me'

If you are partial to using set, you can use parentheses:

DECLARE @wins int, @losses int

SET (@wins, @losses) = (SELECT SUM(DidWin), SUM(DidLose)
FROM thetable
WHERE Playername='Me');

Explicit Return Type of Lambda

You can explicitly specify the return type of a lambda by using -> Type after the arguments list:

[]() -> Type { }

However, if a lambda has one statement and that statement is a return statement (and it returns an expression), the compiler can deduce the return type from the type of that one returned expression. You have multiple statements in your lambda, so it doesn't deduce the type.

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

Red lines under the ViewBag was my headache for 3 month ). Just remove the Microsoft.CSharp reference from project and then add it again.

twitter bootstrap text-center when in xs mode

Css Part is:

CSS:

@media (max-width: 767px) {

  // Align text to center.
  .text-xs-center {
    text-align: center;
  } 
}

And the HTML part will be ( this text center work only below 767px width )

HTML:

 <div class="col-xs-12 col-sm-6 text-right text-xs-center">
        <p>
            <a href="#"><i class="fa fa-facebook"></i></a> 
            <a href="#"><i class="fa fa-twitter"></i></a> 
            <a href="#"><i class="fa fa-google-plus"></i></a>
        </p>
 </div>

Get the value in an input text box

To get the textbox value, you can use the jQuery val() function.

For example,

$('input:textbox').val() – Get textbox value.

$('input:textbox').val("new text message") – Set the textbox value.

Javascript - remove an array item by value

Here are some helper functions I use:

Array.contains = function (arr, key) {
    for (var i = arr.length; i--;) {
        if (arr[i] === key) return true;
    }
    return false;
};

Array.add = function (arr, key, value) {
    for (var i = arr.length; i--;) {
        if (arr[i] === key) return arr[key] = value;
    }
    this.push(key);
};

Array.remove = function (arr, key) {
    for (var i = arr.length; i--;) {
        if (arr[i] === key) return arr.splice(i, 1);
    }
};

How do I know the script file name in a Bash script?

# ------------- SCRIPT ------------- #

#!/bin/bash

echo
echo "# arguments called with ---->  ${@}     "
echo "# \$1 ---------------------->  $1       "
echo "# \$2 ---------------------->  $2       "
echo "# path to me --------------->  ${0}     "
echo "# parent path -------------->  ${0%/*}  "
echo "# my name ------------------>  ${0##*/} "
echo
exit

# ------------- CALLED ------------- #

# Notice on the next line, the first argument is called within double, 
# and single quotes, since it contains two words

$  /misc/shell_scripts/check_root/show_parms.sh "'hello there'" "'william'"

# ------------- RESULTS ------------- #

# arguments called with --->  'hello there' 'william'
# $1 ---------------------->  'hello there'
# $2 ---------------------->  'william'
# path to me -------------->  /misc/shell_scripts/check_root/show_parms.sh
# parent path ------------->  /misc/shell_scripts/check_root
# my name ----------------->  show_parms.sh

# ------------- END ------------- #

Count the number of Occurrences of a Word in a String

We can count from many ways for the occurrence of substring:-

public class Test1 {
public static void main(String args[]) {
    String st = "abcdsfgh yfhf hghj gjgjhbn hgkhmn abc hadslfahsd abcioh abc  a ";
    count(st, 0, "a".length());

}

public static void count(String trim, int i, int length) {
    if (trim.contains("a")) {
        trim = trim.substring(trim.indexOf("a") + length);
        count(trim, i + 1, length);
    } else {
        System.out.println(i);
    }
}

public static void countMethod2() {
    int index = 0, count = 0;
    String inputString = "mynameiskhanMYlaptopnameishclMYsirnameisjasaiwalmyfrontnameisvishal".toLowerCase();
    String subString = "my".toLowerCase();

    while (index != -1) {
        index = inputString.indexOf(subString, index);
        if (index != -1) {
            count++;
            index += subString.length();
        }
    }
    System.out.print(count);
}}

Normalize columns of pandas data frame

Your problem is actually a simple transform acting on the columns:

def f(s):
    return s/s.max()

frame.apply(f, axis=0)

Or even more terse:

   frame.apply(lambda x: x/x.max(), axis=0)

linux find regex

You should have a look on the -regextype argument of find, see manpage:

      -regextype type
          Changes the regular expression syntax understood by -regex and -iregex 
          tests which occur later on the command line.  Currently-implemented  
          types  are  emacs (this is the default), posix-awk, posix-basic, 
          posix-egrep and posix-extended. 

I guess the emacs type doesn't support the [[:digit:]] construct. I tried it with posix-extended and it worked as expected:

find -regextype posix-extended -regex '.*[1234567890]'
find -regextype posix-extended -regex '.*[[:digit:]]'

convert string to char*

There are many ways. Here are at least five:

/*
 * An example of converting std::string to (const)char* using five
 * different methods. Error checking is emitted for simplicity.
 *
 * Compile and run example (using gcc on Unix-like systems):
 *
 *  $ g++ -Wall -pedantic -o test ./test.cpp
 *  $ ./test
 *  Original string (0x7fe3294039f8): hello
 *  s1 (0x7fe3294039f8): hello
 *  s2 (0x7fff5dce3a10): hello
 *  s3 (0x7fe3294000e0): hello
 *  s4 (0x7fe329403a00): hello
 *  s5 (0x7fe329403a10): hello
 */

#include <alloca.h>
#include <string>
#include <cstring>

int main()
{
    std::string s0;
    const char *s1;
    char *s2;
    char *s3;
    char *s4;
    char *s5;

    // This is the initial C++ string.
    s0 = "hello";

    // Method #1: Just use "c_str()" method to obtain a pointer to a
    // null-terminated C string stored in std::string object.
    // Be careful though because when `s0` goes out of scope, s1 points
    // to a non-valid memory.
    s1 = s0.c_str();

    // Method #2: Allocate memory on stack and copy the contents of the
    // original string. Keep in mind that once a current function returns,
    // the memory is invalidated.
    s2 = (char *)alloca(s0.size() + 1);
    memcpy(s2, s0.c_str(), s0.size() + 1);

    // Method #3: Allocate memory dynamically and copy the content of the
    // original string. The memory will be valid until you explicitly
    // release it using "free". Forgetting to release it results in memory
    // leak.
    s3 = (char *)malloc(s0.size() + 1);
    memcpy(s3, s0.c_str(), s0.size() + 1);

    // Method #4: Same as method #3, but using C++ new/delete operators.
    s4 = new char[s0.size() + 1];
    memcpy(s4, s0.c_str(), s0.size() + 1);

    // Method #5: Same as 3 but a bit less efficient..
    s5 = strdup(s0.c_str());

    // Print those strings.
    printf("Original string (%p): %s\n", s0.c_str(), s0.c_str());
    printf("s1 (%p): %s\n", s1, s1);
    printf("s2 (%p): %s\n", s2, s2);
    printf("s3 (%p): %s\n", s3, s3);
    printf("s4 (%p): %s\n", s4, s4);
    printf("s5 (%p): %s\n", s5, s5);

    // Release memory...
    free(s3);
    delete [] s4;
    free(s5);
}

Apache Tomcat :java.net.ConnectException: Connection refused

I also faced this problem . You can try any of these steps :

Ubuntu says "bash: ./program Permission denied"

Try this:

sudo chmod +x program_name
./program_name 

Declaring functions in JSP?

You need to enclose that in <%! %> as follows:

<%!

public String getQuarter(int i){
String quarter;
switch(i){
        case 1: quarter = "Winter";
        break;

        case 2: quarter = "Spring";
        break;

        case 3: quarter = "Summer I";
        break;

        case 4: quarter = "Summer II";
        break;

        case 5: quarter = "Fall";
        break;

        default: quarter = "ERROR";
}

return quarter;
}

%>

You can then invoke the function within scriptlets or expressions:

<%
     out.print(getQuarter(4));
%>

or

<%= getQuarter(17) %>

Replace last occurrence of character in string

Keep it simple

var someString = "a_b_c";
var newCharacter = "+";

var newString = someString.substring(0, someString.lastIndexOf('_')) + newCharacter + someString.substring(someString.lastIndexOf('_')+1);

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

Is the action method on your form pointing to /controller/edit/1?

Try using one of these:

// the null in the last position is the html attributes, which you usually won't use
// on a form.  These invocations are kinda ugly
Html.BeginForm("Edit", "User", new { Id = Model.Id }, FormMethod.Post, null)

Html.BeginForm(new { action="Edit", controller="User", id = Model.Id })

Or inside your form add a hidden "Id" field

@Html.HiddenFor(m => m.Id)

Using arrays or std::vectors in C++, what's the performance gap?

About duli's contribution with my own measurements.

The conclusion is that arrays of integers are faster than vectors of integers (5 times in my example). However, arrays and vectors are arround the same speed for more complex / not aligned data.

Skip the headers when editing a csv file using Python

Doing row=1 won't change anything, because you'll just overwrite that with the results of the loop.

You want to do next(reader) to skip one row.

Can a normal Class implement multiple interfaces?

public class A implements C,D {...} valid

this is the way to implement multiple inheritence in java

Pass props in Link react-router

After install react-router-dom

<Link
    to={{
      pathname: "/product-detail",
      productdetailProps: {
       productdetail: "I M passed From Props"
      }
   }}>
    Click To Pass Props
</Link>

and other end where the route is redirected do this

componentDidMount() {
            console.log("product props is", this.props.location.productdetailProps);
          }

Get human readable version of file size?

A library that has all the functionality that it seems you're looking for is humanize. humanize.naturalsize() seems to do everything you're looking for.

Non-resolvable parent POM using Maven 3.0.3 and relativePath notation

For me, it works when I double checked the parent´s "group ID" and "artifact ID" that in my case were the wrong ones and that was the problem.

functional way to iterate over range (ES6/7)

One can create an empty array, fill it (otherwise map will skip it) and then map indexes to values:

Array(8).fill().map((_, i) => i * i);

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

SELECT object_definition (OBJECT_ID(N'dbo.vEmployee'))

How do I display the current value of an Android Preference in the Preference summary?

My option is to extend ListPreference and it's clean:

public class ListPreferenceShowSummary extends ListPreference {

    private final static String TAG = ListPreferenceShowSummary.class.getName();

    public ListPreferenceShowSummary(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ListPreferenceShowSummary(Context context) {
        super(context);
        init();
    }

    private void init() {

        setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

            @Override
            public boolean onPreferenceChange(Preference arg0, Object arg1) {
                arg0.setSummary(getEntry());
                return true;
            }
        });
    }

    @Override
    public CharSequence getSummary() {
        return super.getEntry();
    }
}

Then you add in your settings.xml:

<yourpackage.ListPreferenceShowSummary
    android:key="key" android:title="title"
    android:entries="@array/entries" android:entryValues="@array/values"
    android:defaultValue="first value"/>

Bootstrap 4 img-circle class not working

In Bootstrap 4 it was renamed to .rounded-circle

Usage :

<div class="col-xs-7">
    <img src="img/gallery2.JPG" class="rounded-circle" alt="HelPic>
</div>

See migration docs from bootstrap.

A function to convert null to string

public string nullToString(string value)
{
    return value == null ?string.Empty: value;   
}

Retrofit 2.0 how to get deserialised error response.body

I was facing same issue. I solved it with retrofit. Let me show this...

If your error JSON structure are like

{
"error": {
    "status": "The email field is required."
}
}


My ErrorRespnce.java 

public class ErrorResponse {

   @SerializedName("error")
   @Expose
   private ErrorStatus error;

   public ErrorStatus getError() {
      return error;
   }

   public void setError(ErrorStatus error) {
      this.error = error;
   }
}

And this my Error status class

public class ErrorStatus {

  @SerializedName("status")
  @Expose
  private String status;

  public String getStatus() {
      return status;
  }

  public void setStatus(String status) {
      this.status = status;
  }
}

Now we need a class which can handle our json.

  public class ErrorUtils {

   public static ErrorResponse parseError (Response<?> response){
      Converter<ResponseBody , ErrorResponse> converter =          ApiClient.getClient().responseBodyConverter(ErrorResponse.class , new Annotation[0]);
    ErrorResponse errorResponse;
    try{
        errorResponse = converter.convert(response.errorBody());
    }catch (IOException e){
        return new ErrorResponse();
    }
    return errorResponse;
}
}

Now we can check our response in retrofit api call

private void registrationRequest(String name , String email , String password , String c_password){


    final Call<RegistrationResponce> registrationResponceCall = apiInterface.getRegistration(name , email , password , c_password);
    registrationResponceCall.enqueue(new Callback<RegistrationResponce>() {
        @Override
        public void onResponse(Call<RegistrationResponce> call, Response<RegistrationResponce> response) {



            if (response.code() == 200){


            }else if (response.code() == 401){


                ErrorResponse errorResponse = ErrorUtils.parseError(response);
                Toast.makeText(MainActivity.this, ""+errorResponse.getError().getStatus(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<RegistrationResponce> call, Throwable t) {

        }
    });
}

That's it now you can show your Toast

Set colspan dynamically with jquery

td.setAttribute('rowspan',x);

How can I URL encode a string in Excel VBA?

Same as WorksheetFunction.EncodeUrl with UTF-8 support:

Public Function EncodeURL(url As String) As String
  Dim buffer As String, i As Long, c As Long, n As Long
  buffer = String$(Len(url) * 12, "%")

  For i = 1 To Len(url)
    c = AscW(Mid$(url, i, 1)) And 65535

    Select Case c
      Case 48 To 57, 65 To 90, 97 To 122, 45, 46, 95  ' Unescaped 0-9A-Za-z-._ '
        n = n + 1
        Mid$(buffer, n) = ChrW(c)
      Case Is <= 127            ' Escaped UTF-8 1 bytes U+0000 to U+007F '
        n = n + 3
        Mid$(buffer, n - 1) = Right$(Hex$(256 + c), 2)
      Case Is <= 2047           ' Escaped UTF-8 2 bytes U+0080 to U+07FF '
        n = n + 6
        Mid$(buffer, n - 4) = Hex$(192 + (c \ 64))
        Mid$(buffer, n - 1) = Hex$(128 + (c Mod 64))
      Case 55296 To 57343       ' Escaped UTF-8 4 bytes U+010000 to U+10FFFF '
        i = i + 1
        c = 65536 + (c Mod 1024) * 1024 + (AscW(Mid$(url, i, 1)) And 1023)
        n = n + 12
        Mid$(buffer, n - 10) = Hex$(240 + (c \ 262144))
        Mid$(buffer, n - 7) = Hex$(128 + ((c \ 4096) Mod 64))
        Mid$(buffer, n - 4) = Hex$(128 + ((c \ 64) Mod 64))
        Mid$(buffer, n - 1) = Hex$(128 + (c Mod 64))
      Case Else                 ' Escaped UTF-8 3 bytes U+0800 to U+FFFF '
        n = n + 9
        Mid$(buffer, n - 7) = Hex$(224 + (c \ 4096))
        Mid$(buffer, n - 4) = Hex$(128 + ((c \ 64) Mod 64))
        Mid$(buffer, n - 1) = Hex$(128 + (c Mod 64))
    End Select
  Next

  EncodeURL = Left$(buffer, n)
End Function

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

The error

ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile.

can occur if the credentials that your application is trying to use to connect to RabbitMQ are incorrect or missing.

I had this happen when the RabbitMQ credentials stored in my ASP.NET application's web.config file had a value of "" for the password instead of the actual password string value.

PostgreSQL visual interface similar to phpMyAdmin?

pgAdmin 4 is a powerful and popular web-based database management tool for PostgreSQL - http://www.pgadmin.org/

How to open a local disk file with JavaScript?

The xmlhttp request method is not valid for the files on local disk because the browser security does not allow us to do so.But we can override the browser security by creating a shortcut->right click->properties In target "... browser location path.exe" append --allow-file-access-from-files.This is tested on chrome,however care should be taken that all browser windows should be closed and the code should be run from the browser opened via this shortcut.

How to get the command line args passed to a running process on unix/linux systems?

Full commandline

For Linux & Unix System you can use ps -ef | grep process_name to get the full command line.

On SunOS systems, if you want to get full command line, you can use

/usr/ucb/ps -auxww | grep -i process_name

To get the full command line you need to become super user.

List of arguments

pargs -a PROCESS_ID

will give a detailed list of arguments passed to a process. It will output the array of arguments in like this:

argv[o]: first argument
argv[1]: second..
argv[*]: and so on..

I didn't find any similar command for Linux, but I would use the following command to get similar output:

tr '\0' '\n' < /proc/<pid>/environ

How to set the maximum memory usage for JVM?

The NativeHeap can be increasded by -XX:MaxDirectMemorySize=256M (default is 128)

I've never used it. Maybe you'll find it useful.

JPA eager fetch does not join

The fetchType attribute controls whether the annotated field is fetched immediately when the primary entity is fetched. It does not necessarily dictate how the fetch statement is constructed, the actual sql implementation depends on the provider you are using toplink/hibernate etc.

If you set fetchType=EAGER This means that the annotated field is populated with its values at the same time as the other fields in the entity. So if you open an entitymanager retrieve your person objects and then close the entitymanager, subsequently doing a person.address will not result in a lazy load exception being thrown.

If you set fetchType=LAZY the field is only populated when it is accessed. If you have closed the entitymanager by then a lazy load exception will be thrown if you do a person.address. To load the field you need to put the entity back into an entitymangers context with em.merge(), then do the field access and then close the entitymanager.

You might want lazy loading when constructing a customer class with a collection for customer orders. If you retrieved every order for a customer when you wanted to get a customer list this may be a expensive database operation when you only looking for customer name and contact details. Best to leave the db access till later.

For the second part of the question - how to get hibernate to generate optimised SQL?

Hibernate should allow you to provide hints as to how to construct the most efficient query but I suspect there is something wrong with your table construction. Is the relationship established in the tables? Hibernate may have decided that a simple query will be quicker than a join especially if indexes etc are missing.

How to commit my current changes to a different branch in Git

The other answers suggesting checking out the other branch, then committing to it, only work if the checkout is possible given the local modifications. If not, you're in the most common use case for git stash:

git stash
git checkout other-branch
git stash pop

The first stash hides away your changes (basically making a temporary commit), and the subsequent stash pop re-applies them. This lets Git use its merge capabilities.

If, when you try to pop the stash, you run into merge conflicts... the next steps depend on what those conflicts are. If all the stashed changes indeed belong on that other branch, you're simply going to have to sort through them - it's a consequence of having made your changes on the wrong branch.

On the other hand, if you've really messed up, and your work tree has a mix of changes for the two branches, and the conflicts are just in the ones you want to commit back on the original branch, you can save some work. As usual, there are a lot of ways to do this. Here's one, starting from after you pop and see the conflicts:

# Unstage everything (warning: this leaves files with conflicts in your tree)
git reset

# Add the things you *do* want to commit here
git add -p     # or maybe git add -i
git commit

# The stash still exists; pop only throws it away if it applied cleanly
git checkout original-branch
git stash pop

# Add the changes meant for this branch
git add -p
git commit

# And throw away the rest
git reset --hard

Alternatively, if you realize ahead of the time that this is going to happen, simply commit the things that belong on the current branch. You can always come back and amend that commit:

git add -p
git commit
git stash
git checkout other-branch
git stash pop

And of course, remember that this all took a bit of work, and avoid it next time, perhaps by putting your current branch name in your prompt by adding $(__git_ps1) to your PS1 environment variable in your bashrc file. (See for example the Git in Bash documentation.)

Pygame Drawing a Rectangle

here's how:

import pygame
screen=pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
red=255
blue=0
green=0
left=50
top=50
width=90
height=90
filled=0
pygame.draw.rect(screen, [red, blue, green], [left, top, width, height], filled)
pygame.display.flip()
running=True
while running:
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            running=False
pygame.quit()

How do I convert number to string and pass it as argument to Execute Process Task?

Expression: "Total Count: " + (DT_WSTR, 5)@[User::Cnt]

How to run a program automatically as admin on Windows 7 at startup?

You can do this by installing the task while running as administrator via the TaskSchedler library. I'm making the assumption here that .NET/C# is a suitable platform/language given your related questions.

This library gives you granular access to the Task Scheduler API, so you can adjust settings that you cannot otherwise set via the command line by calling schtasks, such as the priority of the startup. Being a parental control application, you'll want it to have a startup priority of 0 (maximum), which schtasks will create by default a priority of 7.

Below is a code example of installing a properly configured startup task to run the desired application as administrator indefinitely at logon. This code will install a task for the very process that it's running from.

/*
Copyright © 2017 Jesse Nicholson  
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/// <summary>
/// Used for synchronization when creating run at startup task.
/// </summary>
private ReaderWriterLockSlim m_runAtStartupLock = new ReaderWriterLockSlim();

public void EnsureStarupTaskExists()
{
    try
    {
        m_runAtStartupLock.EnterWriteLock();


        using(var ts = new Microsoft.Win32.TaskScheduler.TaskService())
        {
            // Start off by deleting existing tasks always. Ensure we have a clean/current install of the task.
            ts.RootFolder.DeleteTask(Process.GetCurrentProcess().ProcessName, false);

            // Create a new task definition and assign properties
            using(var td = ts.NewTask())
            {
                td.Principal.RunLevel = Microsoft.Win32.TaskScheduler.TaskRunLevel.Highest;
                // This is not normally necessary. RealTime is the highest priority that
                // there is.
                td.Settings.Priority = ProcessPriorityClass.RealTime;
                td.Settings.DisallowStartIfOnBatteries = false;
                td.Settings.StopIfGoingOnBatteries = false;
                td.Settings.WakeToRun = false;
                td.Settings.AllowDemandStart = false;
                td.Settings.IdleSettings.RestartOnIdle = false;                    
                td.Settings.IdleSettings.StopOnIdleEnd = false;
                td.Settings.RestartCount = 0;                    
                td.Settings.AllowHardTerminate = false;
                td.Settings.Hidden = true;
                td.Settings.Volatile = false;
                td.Settings.Enabled = true;
                td.Settings.Compatibility = Microsoft.Win32.TaskScheduler.TaskCompatibility.V2;
                td.Settings.ExecutionTimeLimit = TimeSpan.Zero;

                td.RegistrationInfo.Description = "Runs the content filter at startup.";

                // Create a trigger that will fire the task at this time every other day
                var logonTrigger = new Microsoft.Win32.TaskScheduler.LogonTrigger();
                logonTrigger.Enabled = true;                    
                logonTrigger.Repetition.StopAtDurationEnd = false;
                logonTrigger.ExecutionTimeLimit = TimeSpan.Zero;
                td.Triggers.Add(logonTrigger);

                // Create an action that will launch Notepad whenever the trigger fires
                td.Actions.Add(new Microsoft.Win32.TaskScheduler.ExecAction(Process.GetCurrentProcess().MainModule.FileName, "/StartMinimized", null));

                // Register the task in the root folder
                ts.RootFolder.RegisterTaskDefinition(Process.GetCurrentProcess().ProcessName, td);
            }
        }                
    }
    finally
    {
        m_runAtStartupLock.ExitWriteLock();
    }
}

How to upload file to server with HTTP POST multipart/form-data?

Basic implementation using MultipartFormDataContent :-

HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();

form.Add(new StringContent(username), "username");
form.Add(new StringContent(useremail), "email");
form.Add(new StringContent(password), "password");            
form.Add(new ByteArrayContent(file_bytes, 0, file_bytes.Length), "profile_pic", "hello1.jpg");
HttpResponseMessage response = await httpClient.PostAsync("PostUrl", form);

response.EnsureSuccessStatusCode();
httpClient.Dispose();
string sd = response.Content.ReadAsStringAsync().Result;

How to debug in Android Studio using adb over WiFi

I'm using AS 3.2.1, and was about to try some of the plugins, but was hesitant realizing the plugins are able to monitor any data..

It's actually really simple doing it via the Terminal tab in AS:

  1. Turn on debugging over WiFi in your phone
    • Go to developer options and turn on "ADB over network"
    • You'll see the exact address and port to use when connecting
  2. Go to the Terminal tab in Android Studio
  3. Type adb tcpip 5555
  4. Type your ip address as seen in developer options i.e. adb connect 192.168.1.101
  5. Now you'll see your device in AS "Select deployment target" dialog

How to determine programmatically the current active profile using Spring boot

It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment to your bean.

@Autowired
private Environment environment;
....

this.environment.getActiveProfiles();

How to make a simple collection view with Swift

UICollectionView implementation is quite interesting. You can use the simple source code and watch a video tutorial using these links :

https://github.com/Ady901/Demo02CollectionView.git

https://www.youtube.com/watch?v=5SrgvZF67Yw

extension ViewController : UICollectionViewDataSource {

    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return nameArr.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "DummyCollectionCell", for: indexPath) as! DummyCollectionCell
        cell.titleLabel.text = nameArr[indexPath.row]
        cell.userImageView.backgroundColor = .blue
        return cell
    }

}

extension ViewController : UICollectionViewDelegate {

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let alert = UIAlertController(title: "Hi", message: "\(nameArr[indexPath.row])", preferredStyle: .alert)
        let action = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(action)
        self.present(alert, animated: true, completion: nil)
    }

}

Java regex to extract text between tags

    String s = "<B><G>Test</G></B><C>Test1</C>";

    String pattern ="\\<(.+)\\>([^\\<\\>]+)\\<\\/\\1\\>";

       int count = 0;

        Pattern p = Pattern.compile(pattern);
        Matcher m =  p.matcher(s);
        while(m.find())
        {
            System.out.println(m.group(2));
            count++;
        }

App not setup: This app is still in development mode

make sure your app is live on developer.facebook.com

This green circle is indicating the app is live enter image description here

If it is not then follow this two steps for make your app live

Step 1 Go to your application -> setting => and add Contact Email and apply save Changes

Setp 2 Then goto App Review option and make sure this toggle is Yes i added a screen shot

enter image description here

C: How to free nodes in the linked list?

You could always do it recursively like so:

void freeList(struct node* currentNode)
{
    if(currentNode->next) freeList(currentNode->next);
    free(currentNode);
}

Install Application programmatically on Android

File file = new File(dir, "App.apk");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
startActivity(intent);

I had the same problem and after several attempts, it worked out for me this way. I don't know why, but setting data and type separately screwed up my intent.

I/O error(socket error): [Errno 111] Connection refused

Its seems that server is not running properly so ensure that with terminal by

telnet ip port

example

telnet localhost 8069

It will return connected to localhost so it indicates that there is no problem with the connection Else it will return Connection refused it indicates that there is problem with the connection

How do I check if file exists in Makefile so I can delete it?

ifneq ("$(wildcard $(PATH_TO_FILE))","")
    FILE_EXISTS = 1
else
    FILE_EXISTS = 0
endif

This solution posted above works best. But make sure that you do not stringify the PATH_TO_FILE assignment E.g.,

PATH_TO_FILE = "/usr/local/lib/libhl++.a" # WILL NOT WORK

It must be

PATH_TO_FILE = /usr/local/lib/libhl++.a

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

Here's a setTimeout equivalent, mostly useful when trying to update the User Interface after a delay.

As you may know, updating the user interface can only by done from the UI thread. AsyncTask does that for you by calling its onPostExecute method from that thread.

new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // Update the User Interface
        }

    }.execute();

Java: JSON -> Protobuf & back conversion

Try JsonFormat.printer().print(MessageOrBuilder), it looks good for proto3. Yet, it is unclear how to convert the actual protobuf message (which is provided as the java package of my choice defined in the .proto file) to a com.google.protbuf.Message object.

Finding the type of an object in C++

You are looking for dynamic_cast<B*>(pointer)