Programs & Examples On #Views2

Index of element in NumPy array

I'm torn between these two ways of implementing an index of a NumPy array:

idx = list(classes).index(var)
idx = np.where(classes == var)

Both take the same number of characters, but the first method returns an int instead of a numpy.ndarray.

html vertical align the text inside input type button

The simplest thing you can do is use reset.css. It normalizes the default stylesheet across browsers, and coincidentally allows button { vertical-align: middle; } to work just fine. Give it a shot - I use it in virtually all of my projects just to kill little bugs like this.

https://gist.github.com/nathansmith/288292

Get List of connected USB Devices

Adel Hazzah's answer gives working code, Daniel Widdis's and Nedko's comments mention that you need to query Win32_USBControllerDevice and use its Dependent property, and Daniel's answer gives a lot of detail without code.

Here's a synthesis of the above discussion to provide working code that lists the directly accessible PNP device properties of all connected USB devices:

using System;
using System.Collections.Generic;
using System.Management; // reference required

namespace cSharpUtilities
{
    class UsbBrowser
    {

        public static void PrintUsbDevices()
        {
            IList<ManagementBaseObject> usbDevices = GetUsbDevices();

            foreach (ManagementBaseObject usbDevice in usbDevices)
            {
                Console.WriteLine("----- DEVICE -----");
                foreach (var property in usbDevice.Properties)
                {
                    Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
                }
                Console.WriteLine("------------------");
            }
        }

        public static IList<ManagementBaseObject> GetUsbDevices()
        {
            IList<string> usbDeviceAddresses = LookUpUsbDeviceAddresses();

            List<ManagementBaseObject> usbDevices = new List<ManagementBaseObject>();

            foreach (string usbDeviceAddress in usbDeviceAddresses)
            {
                // query MI for the PNP device info
                // address must be escaped to be used in the query; luckily, the form we extracted previously is already escaped
                ManagementObjectCollection curMoc = QueryMi("Select * from Win32_PnPEntity where PNPDeviceID = " + usbDeviceAddress);
                foreach (ManagementBaseObject device in curMoc)
                {
                    usbDevices.Add(device);
                }
            }

            return usbDevices;
        }

        public static IList<string> LookUpUsbDeviceAddresses()
        {
            // this query gets the addressing information for connected USB devices
            ManagementObjectCollection usbDeviceAddressInfo = QueryMi(@"Select * from Win32_USBControllerDevice");

            List<string> usbDeviceAddresses = new List<string>();

            foreach(var device in usbDeviceAddressInfo)
            {
                string curPnpAddress = (string)device.GetPropertyValue("Dependent");
                // split out the address portion of the data; note that this includes escaped backslashes and quotes
                curPnpAddress = curPnpAddress.Split(new String[] { "DeviceID=" }, 2, StringSplitOptions.None)[1];

                usbDeviceAddresses.Add(curPnpAddress);
            }

            return usbDeviceAddresses;
        }

        // run a query against Windows Management Infrastructure (MI) and return the resulting collection
        public static ManagementObjectCollection QueryMi(string query)
        {
            ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(query);
            ManagementObjectCollection result = managementObjectSearcher.Get();

            managementObjectSearcher.Dispose();
            return result;
        }

    }

}

You'll need to add exception handling if you want it. Consult Daniel's answer if you want to figure out the device tree and such.

Disable sorting for a particular column in jQuery DataTables

If you already have to hide Some columns, like I hide last name column. I just had to concatenate fname , lname , So i made query but hide that column from front end. The modifications in Disable sorting in such situation are :

    "aoColumnDefs": [
        { 'bSortable': false, 'aTargets': [ 3 ] },
        {
            "targets": [ 4 ],
            "visible": false,
            "searchable": true
        }
    ],

Notice that I had Hiding functionality here

    "columnDefs": [
            {
                "targets": [ 4 ],
                "visible": false,
                "searchable": true
            }
        ],

Then I merged it into "aoColumnDefs"

How to list branches that contain a given commit?

The answer for git branch -r --contains <commit> works well for normal remote branches, but if the commit is only in the hidden head namespace that GitHub creates for PRs, you'll need a few more steps.

Say, if PR #42 was from deleted branch and that PR thread has the only reference to the commit on the repo, git branch -r doesn't know about PR #42 because refs like refs/pull/42/head aren't listed as a remote branch by default.

In .git/config for the [remote "origin"] section add a new line:

fetch = +refs/pull/*/head:refs/remotes/origin/pr/*

(This gist has more context.)

Then when you git fetch you'll get all the PR branches, and when you run git branch -r --contains <commit> you'll see origin/pr/42 contains the commit.

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

One liner to check if element is in the list

In JDK7:

if ({"a", "b", "c"}.contains("a")) {

Assuming the Project Coin collections literals project goes through.

Edit: It didn't.

Efficient way of having a function only execute once in a loop

I would use a decorator on the function to handle keeping track of how many times it runs.

def run_once(f):
    def wrapper(*args, **kwargs):
        if not wrapper.has_run:
            wrapper.has_run = True
            return f(*args, **kwargs)
    wrapper.has_run = False
    return wrapper


@run_once
def my_function(foo, bar):
    return foo+bar

Now my_function will only run once. Other calls to it will return None. Just add an else clause to the if if you want it to return something else. From your example, it doesn't need to return anything ever.

If you don't control the creation of the function, or the function needs to be used normally in other contexts, you can just apply the decorator manually as well.

action = run_once(my_function)
while 1:
    if predicate:
        action()

This will leave my_function available for other uses.

Finally, if you need to only run it once twice, then you can just do

action = run_once(my_function)
action() # run once the first time

action.has_run = False
action() # run once the second time

Getting time difference between two times in PHP

You can also use DateTime class:

$time1 = new DateTime('09:00:59');
$time2 = new DateTime('09:01:00');
$interval = $time1->diff($time2);
echo $interval->format('%s second(s)');

Result:

1 second(s)

CSV parsing in Java - working example..?

I would recommend that you start by pulling your task apart into it's component parts.

  1. Read string data from a CSV
  2. Convert string data to appropriate format

Once you do that, it should be fairly trivial to use one of the libraries you link to (which most certainly will handle task #1). Then iterate through the returned values, and cast/convert each String value to the value you want.

If the question is how to convert strings to different objects, it's going to depend on what format you are starting with, and what format you want to wind up with.

DateFormat.parse(), for example, will parse dates from strings. See SimpleDateFormat for quickly constructing a DateFormat for a certain string representation. Integer.parseInt() will prase integers from strings.

Currency, you'll have to decide how you want to capture it. If you want to just capture as a float, then Float.parseFloat() will do the trick (just use String.replace() to remove all $ and commas before you parse it). Or you can parse into a BigDecimal (so you don't have rounding problems). There may be a better class for currency handling (I don't do much of that, so am not familiar with that area of the JDK).

VB6 IDE cannot load MSCOMCTL.OCX after update KB 2687323

For me, this solution worked like a charm: http://home.pacific.net.hk/~edx/bin/readmeocx.txt

Fix these two lines like that:

Object={F9043C88-F6F2-101A-A3C9-08002B2F49FB}#1.2#0; COMDLG32.OCX
Object={831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.0#0; MSCOMCTL.OCX

Search the files (.vbp and .frm) for lines like this:

Begin ComctlLib.ImageList ILTree
Begin ComctlLib.StatusBar StatusBar1 
Begin ComctlLib.Toolbar Toolbar1` 

The lines may be like this:

Begin MSComctlLib.ImageList ILTree 
Begin MSComctlLib.StatusBar StatusBar1
Begin MSComctlLib.Toolbar Toolbar1` 

Angular: date filter adds timezone, how to output UTC?

Since version 1.3.0 AngularJS introduced extra filter parameter timezone, like following:

{{ date_expression | date : format : timezone}}

But in versions 1.3.x only supported timezone is UTC, which can be used as following:

{{ someDate | date: 'MMM d, y H:mm:ss' : 'UTC' }}

Since version 1.4.0-rc.0 AngularJS supports other timezones too. I was not testing all possible timezones, but here's for example how you can get date in Japan Standard Time (JSP, GMT +9):

{{ clock | date: 'MMM d, y H:mm:ss' : '+0900' }}

Here you can find documentation of AngularJS date filters.

NOTE: this is working only with Angular 1.x

Here's working example

JSONP call showing "Uncaught SyntaxError: Unexpected token : "

You're trying to access a JSON, not JSONP.

Notice the difference between your source:

https://api.flightstats.com/flex/schedules/rest/v1/json/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59&callback=?

And actual JSONP (a wrapping function):

http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=processJSON&tags=monkey&tagmode=any&format=json

Search for JSON + CORS/Cross-domain policy and you will find hundreds of SO threads on this very topic.

Differences between hard real-time, soft real-time, and firm real-time?

After reading the Wikipedia page and other pages on real-time computing. I made the following inferences:

1> For a Hard real-time system, if the system fails to meet the deadline even once the system is considered to have Failed.

2> For a Firm real-time system, even if the system fails to meet the deadline, possibly more than once (i.e. for multiple requests), the system is not considered to have failed. Also, the responses for the requests (replies to a query, result of a task, etc.) are worthless once the deadline for that particular request has passed (The usefulness of a result is zero after its deadline). A hypothetical example can be a storm forecast system (if a storm is predicted before arrival, then the system has done its job, prediction after the event has already happened or when it is happening is of no value).

3> For a Soft real-time system, even if the system fails to meet the deadline, possibly more than once (i.e. for multiple requests), the system is not considered to have failed. But, in this case the results of the requests are not worthless value for a result after its deadline, is not zero, rather it degrades as time passes after the deadline. Eg.: Streaming audio-video.

Here is a link to a resource that was very helpful.

How to send a compressed archive that contains executables so that Google's attachment filter won't reject it

Another easy way to circumvent google's check is to use another compression algorithm with tar, like bz2:

tar -cvjf my.tar.bz2 dir/

Note that 'j' (for bz2 compression) is used above instead of 'z' (gzip compression).

Call another rest api from my server in Spring-Boot

Instead of String you are trying to get custom POJO object details as output by calling another API/URI, try the this solution. I hope it will be clear and helpful for how to use RestTemplate also,

In Spring Boot, first we need to create Bean for RestTemplate under the @Configuration annotated class. You can even write a separate class and annotate with @Configuration like below.

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
       return builder.build();
    }
}

Then, you have to define RestTemplate with @Autowired or @Injected under your service/Controller, whereever you are trying to use RestTemplate. Use the below code,

@Autowired
private RestTemplate restTemplate;

Now, will see the part of how to call another api from my application using above created RestTemplate. For this we can use multiple methods like execute(), getForEntity(), getForObject() and etc. Here I am placing the code with example of execute(). I have even tried other two, I faced problem of converting returned LinkedHashMap into expected POJO object. The below, execute() method solved my problem.

ResponseEntity<List<POJO>> responseEntity = restTemplate.exchange(
    URL, 
    HttpMethod.GET, 
    null, 
    new ParameterizedTypeReference<List<POJO>>() {
    });
List<POJO> pojoObjList = responseEntity.getBody();

Happy Coding :)

What is a callback in java

Callbacks are most easily described in terms of the telephone system. A function call is analogous to calling someone on a telephone, asking her a question, getting an answer, and hanging up; adding a callback changes the analogy so that after asking her a question, you also give her your name and number so she can call you back with the answer.

Paul Jakubik, Callback Implementations in C++.

How to declare empty list and then add string in scala?

As everyone already mentioned, this is not the best way of using lists in Scala...

scala> val list = scala.collection.mutable.MutableList[String]()
list: scala.collection.mutable.MutableList[String] = MutableList()

scala> list += "hello"
res0: list.type = MutableList(hello)

scala> list += "world"
res1: list.type = MutableList(hello, world)

scala> list mkString " "
res2: String = hello world

Bootstrap Modal immediately disappearing

Same symptom, in the context of a Rails application with Bootstrap provided by the bootstrap-sass gem, and @merv's answer put me on the right track.

My application.js file had the following:

//= require bootstrap
//= require bootstrap-sprockets

The fix was to remove one of the two lines. Indeed, the gem's readme warns you about this error. My bad.

Linking static libraries to other static libraries

On Linux or MingW, with GNU toolchain:

ar -M <<EOM
    CREATE libab.a
    ADDLIB liba.a
    ADDLIB libb.a
    SAVE
    END
EOM
ranlib libab.a

Of if you do not delete liba.a and libb.a, you can make a "thin archive":

ar crsT libab.a liba.a libb.a

On Windows, with MSVC toolchain:

lib.exe /OUT:libab.lib liba.lib libb.lib

Learning Ruby on Rails

A lot of good opinions here. I'll add what's not here. My experience:

  • Rails on Windows is easy to get going with RailsInstaller, especially if you're using SQLite.
  • If you want to use Ruby gems which need C extensions (e.g. RMagick), installation is difficult and unpredictable.
  • PostgreSQL is a pain to install on Windows, and a pain to hook up to Rails.
  • git doesn't work quite right on Windows.
  • IDEs are bulky (Aptana). Notepad++ is good enough.
  • Rails on Ubuntu is easy, and gems requiring C libraries just work.
  • If your computer is powerful enough, use VirtualBox or VMWare Player, and use an Ubuntu Virtual Machine.

Setup Resources

  • This page shows, start to finish how to set up Ruby/Rails/PostgreSQL on Ubuntu 11.10.
  • If you don't like RVM (I don't), use rbenv. RVM and rbenv are tools for managing multiple versions of Ruby, including JRuby, Rubinius, etc.

Live Deployment for Development/Testing

  • Live deployment lets your friends try out your app. It also makes it easier to interact with web services which need to make callbacks to your Rails server (such as PayPal IPN or Twilio).
  • Heroku.com is my favourite place to deploy.
  • localtunnel.com is a good utility to point a publicly visible URL to your local Rails server. (I have only used it for Windows-based Rails servers).

Learning

  • Try out tutorials on the web.
  • Use stackoverflow.com to ask questions.
  • Use "raise Exception, params.to_s " in your Controllers to stop the app print out all the parameters which are driving your controllers. This gave me the greatest insight on how data is schlepped back and forth in a Rails app.
  • Use the Rails console ("rails console") to inspect data, and try out code snippets before you embed them in your models or controllers.

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

r is a numpy (rec)array. So r["dt"] >= startdate is also a (boolean) array. For numpy arrays the & operation returns the elementwise-and of the two boolean arrays.

The NumPy developers felt there was no one commonly understood way to evaluate an array in boolean context: it could mean True if any element is True, or it could mean True if all elements are True, or True if the array has non-zero length, just to name three possibilities.

Since different users might have different needs and different assumptions, the NumPy developers refused to guess and instead decided to raise a ValueError whenever one tries to evaluate an array in boolean context. Applying and to two numpy arrays causes the two arrays to be evaluated in boolean context (by calling __bool__ in Python3 or __nonzero__ in Python2).

Your original code

mask = ((r["dt"] >= startdate) & (r["dt"] <= enddate))
selected = r[mask]

looks correct. However, if you do want and, then instead of a and b use (a-b).any() or (a-b).all().

onKeyDown event not working on divs in React

You're missing the binding of the method in the constructor. This is how React suggests that you do it:

class Whatever {
  constructor() {
    super();
    this.onKeyPressed = this.onKeyPressed.bind(this);
  }

  onKeyPressed(e) {
    // your code ...
  }

  render() {
    return (<div onKeyDown={this.onKeyPressed} />);
  }
}

There are other ways of doing this, but this will be the most efficient at runtime.

Razor HtmlHelper Extensions (or other namespaces for views) Not Found

As the accepted answer suggests you can add "using" to all views by adding to section of config file.

But for a single view you could just use

@using SomeNamespace.Extensions

Fastest way to iterate over all the chars in a String

This is just micro-optimisation that you shouldn't worry about.

char[] chars = str.toCharArray();

returns you a copy of str character arrays (in JDK, it returns a copy of characters by calling System.arrayCopy).

Other than that, str.charAt() only checks if the index is indeed in bounds and returns a character within the array index.

The first one doesn't create additional memory in JVM.

Why do people hate SQL cursors so much?

Cursors make people overly apply a procedural mindset to a set-based environment.

And they are SLOW!!!

From SQLTeam:

Please note that cursors are the SLOWEST way to access data inside SQL Server. The should only be used when you truly need to access one row at a time. The only reason I can think of for that is to call a stored procedure on each row. In the Cursor Performance article I discovered that cursors are over thirty times slower than set based alternatives.

How to call MVC Action using Jquery AJAX and then submit form in MVC?

Assuming that your button is in a form, you are not preventing the default behaviour of the button click from happening i.e. Your AJAX call is made in addition to the form submission; what you're very likely seeing is one of

  1. the form submission happens faster than the AJAX call returns
  2. the form submission causes the browser to abort the AJAX request and continues with submitting the form.

So you should prevent the default behaviour of the button click

$('#btnSave').click(function (e) {

    // prevent the default event behaviour    
    e.preventDefault();

    $.ajax({
        url: "/Home/SaveDetailedInfo",
        type: "POST",
        data: JSON.stringify({ 'Options': someData}),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {

            // perform your save call here

            if (data.status == "Success") {
                alert("Done");
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occured!!!");
        }
    });
});

jQuery select change event get selected option

I find this shorter and cleaner. Besides, you can iterate through selected items if there are more than one;

$('select').on('change', function () {
     var selectedValue = this.selectedOptions[0].value;
     var selectedText  = this.selectedOptions[0].text;
});

What's the right way to decode a string that has special HTML entities in it?

jQuery will encode and decode for you.

_x000D_
_x000D_
function htmlDecode(value) {_x000D_
  return $("<textarea/>").html(value).text();_x000D_
}_x000D_
_x000D_
function htmlEncode(value) {_x000D_
  return $('<textarea/>').text(value).html();_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(document).ready(function() {_x000D_
   $("#encoded")_x000D_
  .text(htmlEncode("<img src onerror='alert(0)'>"));_x000D_
   $("#decoded")_x000D_
  .text(htmlDecode("&lt;img src onerror='alert(0)'&gt;"));_x000D_
});_x000D_
</script>_x000D_
_x000D_
<span>htmlEncode() result:</span><br/>_x000D_
<div id="encoded"></div>_x000D_
<br/>_x000D_
<span>htmlDecode() result:</span><br/>_x000D_
<div id="decoded"></div>
_x000D_
_x000D_
_x000D_

Merge/flatten an array of arrays

That's not hard, just iterate over the arrays and merge them:

var result = [], input = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"]];

for (var i = 0; i < input.length; ++i) {
    result = result.concat(input[i]);
}

AngularJS : Initialize service with asynchronous data

Based on Martin Atkins' solution, here is a complete, concise pure-Angular solution:

(function() {
  var initInjector = angular.injector(['ng']);
  var $http = initInjector.get('$http');
  $http.get('/config.json').then(
    function (response) {
      angular.module('config', []).constant('CONFIG', response.data);

      angular.element(document).ready(function() {
          angular.bootstrap(document, ['myApp']);
        });
    }
  );
})();

This solution uses a self-executing anonymous function to get the $http service, request the config, and inject it into a constant called CONFIG when it becomes available.

Once completely, we wait until the document is ready and then bootstrap the Angular app.

This is a slight enhancement over Martin's solution, which deferred fetching the config until after the document is ready. As far as I know, there is no reason to delay the $http call for that.

Unit Testing

Note: I have discovered this solution does not work well when unit-testing when the code is included in your app.js file. The reason for this is that the above code runs immediately when the JS file is loaded. This means the test framework (Jasmine in my case) doesn't have a chance to provide a mock implementation of $http.

My solution, which I'm not completely satisfied with, was to move this code to our index.html file, so the Grunt/Karma/Jasmine unit test infrastructure does not see it.

How to stop mongo DB in one command

Kindly take advantage of the Task Manager provided by your OS for a quick and easy solution. Below is the screengrab from/for Windows 10. Right-click on the highlighted process and select stop. Select start, if already stopped.

enter image description here

Please Note: Internally the commands are doing the same thing which you have to do manually using a GUI (Task Manager), provided by Windows/your OS. Though, this approach to be used for study/practice purpose to get started and you won't be blocked due to this.

How can I make robocopy silent in the command line except for progress?

In PowerShell, I like to use:

robocopy src dest | Out-Null

It avoids having to remember all the command line switches.

python numpy ValueError: operands could not be broadcast together with shapes

dot is matrix multiplication, but * does something else.

We have two arrays:

  • X, shape (97,2)
  • y, shape (2,1)

With Numpy arrays, the operation

X * y

is done element-wise, but one or both of the values can be expanded in one or more dimensions to make them compatible. This operation is called broadcasting. Dimensions, where size is 1 or which are missing, can be used in broadcasting.

In the example above the dimensions are incompatible, because:

97   2
 2   1

Here there are conflicting numbers in the first dimension (97 and 2). That is what the ValueError above is complaining about. The second dimension would be ok, as number 1 does not conflict with anything.

For more information on broadcasting rules: http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html

(Please note that if X and y are of type numpy.matrix, then asterisk can be used as matrix multiplication. My recommendation is to keep away from numpy.matrix, it tends to complicate more than simplifying things.)

Your arrays should be fine with numpy.dot; if you get an error on numpy.dot, you must have some other bug. If the shapes are wrong for numpy.dot, you get a different exception:

ValueError: matrices are not aligned

If you still get this error, please post a minimal example of the problem. An example multiplication with arrays shaped like yours succeeds:

In [1]: import numpy

In [2]: numpy.dot(numpy.ones([97, 2]), numpy.ones([2, 1])).shape
Out[2]: (97, 1)

How to execute XPath one-liners from shell?

One package that is very likely to be installed on a system already is python-lxml. If so, this is possible without installing any extra package:

python -c "from lxml.etree import parse; from sys import stdin; print('\n'.join(parse(stdin).xpath('//element/@attribute')))"

jquery find class and get the value

Class selectors are prefixed with a dot. Your .find() is missing that so jQuery thinks you're looking for <myClass> elements.

var myVar = $("#start").find('.myClass').val();

What is the difference between DSA and RSA?

And in addition to the above nice answers.

  • DSA uses Discrete logarithm.
  • RSA uses Integer Factorization.

RSA stands for Ron Rivest, Adi Shamir and Leonard Adleman.

The correct way to read a data file into an array

Just reading the file into an array, one line per element, is trivial:

open my $handle, '<', $path_to_file;
chomp(my @lines = <$handle>);
close $handle;

Now the lines of the file are in the array @lines.

If you want to make sure there is error handling for open and close, do something like this (in the snipped below, we open the file in UTF-8 mode, too):

my $handle;
unless (open $handle, "<:encoding(utf8)", $path_to_file) {
   print STDERR "Could not open file '$path_to_file': $!\n";
   # we return 'undefined', we could also 'die' or 'croak'
   return undef
}
chomp(my @lines = <$handle>);
unless (close $handle) {
   # what does it mean if close yields an error and you are just reading?
   print STDERR "Don't care error while closing '$path_to_file': $!\n";
} 

Kotlin Ternary Conditional Operator

when replaces the switch operator of C-like languages. In the simplest form it looks like this

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> {
        print("x is neither 1 nor 2")
    }
}

Java generics - ArrayList initialization

ArrayList<Integer> a = new ArrayList<Number>(); 

Does not work because the fact that Number is a super class of Integer does not mean that List<Number> is a super class of List<Integer>. Generics are removed during compilation and do not exist on runtime, so parent-child relationship of collections cannot be be implemented: the information about element type is simply removed.

ArrayList<? extends Object> a1 = new ArrayList<Object>();
a1.add(3);

I cannot explain why it does not work. It is really strange but it is a fact. Really syntax <? extends Object> is mostly used for return values of methods. Even in this example Object o = a1.get(0) is valid.

ArrayList<?> a = new ArrayList<?>()

This does not work because you cannot instantiate list of unknown type...

How to dismiss keyboard iOS programmatically when pressing return

IN Swift 3

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

OR

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField == yourtextfieldName
        {
            self.resignFirstResponder()
            self.view.endEditing(true)
        }
    }

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

You need to do the following:

public class CountryInfoResponse {

   @JsonProperty("geonames")
   private List<Country> countries; 

   //getter - setter
}

RestTemplate restTemplate = new RestTemplate();
List<Country> countries = restTemplate.getForObject("http://api.geonames.org/countryInfoJSON?username=volodiaL",CountryInfoResponse.class).getCountries();

It would be great if you could use some kind of annotation to allow you to skip levels, but it's not yet possible (see this and this)

Delete last char of string

What about doing it this way

strgroupids = string.Join( ",", groupIds );

A lot cleaner.

It will append all elements inside groupIds with a ',' between each, but it will not put a ',' at the end.

Is it possible to use jQuery to read meta tags

I just tried this, and this could be a jQuery version-specific error, but

$("meta[property=twitter:image]").attr("content");

resulted in the following syntax error for me:

Error: Syntax error, unrecognized expression: meta[property=twitter:image]

Apparently it doesn't like the colon. I was able to fix it by using double and single quotes like this:

$("meta[property='twitter:image']").attr("content");

(jQuery version 1.8.3 -- sorry, I would have made this a comment to @Danilo, but it won't let me comment yet)

Jquery and HTML FormData returns "Uncaught TypeError: Illegal invocation"

jQuery processes the data attribute and converts the values into strings.

Adding processData: false to your options object fixes the error, but I'm not sure if it fixes the problem.

Demo: http://jsfiddle.net/eHmSr/1/

Chrome - ERR_CACHE_MISS

If you are using WebView in Android developing the problem is that you didn't add uses permission

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

Question mark and colon in statement. What does it mean?

In the particular case you've provided, it's a conditional assignment. The part before the question mark (?) is a boolean condition, and the parts either side of the colon (:) are the values to assign based on the result of the condition (left side of the colon is the value for true, right side is the value for false).

Advantages of using display:inline-block vs float:left in CSS

If you want to align the div with pixel accurate, then use float. inline-block seems to always requires you to chop off a few pixels (at least in IE)

invalid multibyte char (US-ASCII) with Rails and Ruby 1.9

Those slanted double quotes are not ASCII characters. The error message is misleading about them being 'multi-byte'.

Download multiple files as a zip-file using php

You can use the ZipArchive class to create a ZIP file and stream it to the client. Something like:

$files = array('readme.txt', 'test.html', 'image.gif');
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
  $zip->addFile($file);
}
$zip->close();

and to stream it:

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

The second line forces the browser to present a download box to the user and prompts the name filename.zip. The third line is optional but certain (mainly older) browsers have issues in certain cases without the content size being specified.

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

(9.61 + "").replace('.',':')

Or if your 9.61 is already a string:

"9.61".replace('.',':')

Create a Maven project in Eclipse complains "Could not resolve archetype"

It is also possible that your settings.xml file defined in maven/conf folder defines a location that it cannot access

How to generate service reference with only physical wsdl file

This may be the easiest method

  • Right click on the project and select "Add Service Reference..."
  • In the Address: box, enter the physical path (C:\test\project....) of the downloaded/Modified wsdl.
  • Hit Go

How to set the timeout for a TcpClient?

As Simon Mourier mentioned, it's possible to use ConnectAsync TcpClient's method with Task in addition and stop operation as soon as possible.
For example:

// ...
client = new TcpClient(); // Initialization of TcpClient
CancellationToken ct = new CancellationToken(); // Required for "*.Task()" method
if (client.ConnectAsync(this.ip, this.port).Wait(1000, ct)) // Connect with timeout of 1 second
{

    // ... transfer

    if (client != null) {
        client.Close(); // Close the connection and dispose a TcpClient object
        Console.WriteLine("Success");
        ct.ThrowIfCancellationRequested(); // Stop asynchronous operation after successull connection(...and transfer(in needed))
    }
}
else
{
    Console.WriteLine("Connetion timed out");
}
// ...

Also, I would recommended checking the AsyncTcpClient C# library with some examples provided like Server <> Client.

Java collections maintaining insertion order

When you use a HashSet (or a HashMap) data are stored in "buckets" based on the hash of your object. This way your data is easier to access because you don't have to look for this particular data in the whole Set, you just have to look in the right bucket.

This way you can increase performances on specific points.

Each Collection implementation have its particularity to make it better to use in a certain condition. Each of those particularities have a cost. So if you don't really need it (for example the insertion order) you better use an implementation which doesn't offer it and fits better to your requirements.

How do I list all files of a directory?

import os
os.listdir("somedirectory")

will return a list of all files and directories in "somedirectory".

Get class labels from Keras functional model

To map predicted classes and filenames using ImageDataGenerator, I use:

# Data generator and prediction
test_datagen = ImageDataGenerator(rescale=1./255)
test_generator = test_datagen.flow_from_directory(
        inputpath,
        target_size=(150, 150),
        batch_size=20,
        class_mode='categorical',
        shuffle=False)
pred = model.predict_generator(test_generator, steps=len(test_generator), verbose=0)
# Get classes by max element in np (as a list)
classes = list(np.argmax(pred, axis=1))
# Get filenames (set shuffle=false in generator is important)
filenames = test_generator.filenames

I can loop over predicted classes and the associated filename using:

for f in zip(classes, filenames):
    ...

Fatal error: Cannot use object of type stdClass as array in

Sorry.Though it is a bit late but hope it would help others as well . Always use the stdClass object.e.g

 $getvidids = $ci->db->query("SELECT * FROM videogroupids WHERE videogroupid='$videogroup'   AND used='0' LIMIT 10");

foreach($getvidids->result() as $key=>$myids)
{

  $vidid[$key] = $myids->videoid;  // better methodology to retrieve and store multiple records in arrays in loop
 }

PHP shorthand for isset()?

PHP 7.4+; with the null coalescing assignment operator

$var ??= '';

PHP 7.0+; with the null coalescing operator

$var = $var ?? '';

PHP 5.3+; with the ternary operator shorthand

isset($var) ?: $var = '';

Or for all/older versions with isset:

$var = isset($var) ? $var : '';

or

!isset($var) && $var = '';

Execute function after Ajax call is complete

You should set async = false in head. Use post/get instead of ajax.

jQuery.ajaxSetup({ async: false });

    $.post({
        url: 'api.php',
        data: 'id1=' + q + '',
        dataType: 'json',
        success: function (data) {

            id = data[0];
            vname = data[1];

        }
    });

List all files in one directory PHP

You are looking for the command scandir.

$path    = '/tmp';
$files = scandir($path);

Following code will remove . and .. from the returned array from scandir:

$files = array_diff(scandir($path), array('.', '..'));

C++ program converts fahrenheit to celsius

Best way would be

#include <iostream>                        
using namespace std;                       

int main() {                               
    float celsius;                         
    float fahrenheit;

    cout << "Enter Celsius temperature: "; 
    cin >> celsius;
    fahrenheit = (celsius * 1.8) + 32;// removing division for the confusion
    cout << "Fahrenheit = " << fahrenheit << endl;

    return 0;                             
}

:)

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

Capturing count from an SQL query

Complementing in C# with SQL:

SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open();
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
Int32 count = Convert.ToInt32(comm.ExecuteScalar());
if (count > 0)
{
    lblCount.Text = Convert.ToString(count.ToString()); //For example a Label
}
else
{
    lblCount.Text = "0";
}
conn.Close(); //Remember close the connection

Getting absolute URLs using ASP.NET Core

This is a variation of the anwser by Muhammad Rehan Saeed, with the class getting parasitically attached to the existing .net core MVC class of the same name, so that everything just works.

namespace Microsoft.AspNetCore.Mvc
{
    /// <summary>
    /// <see cref="IUrlHelper"/> extension methods.
    /// </summary>
    public static partial class UrlHelperExtensions
    {
        /// <summary>
        /// Generates a fully qualified URL to an action method by using the specified action name, controller name and
        /// route values.
        /// </summary>
        /// <param name="url">The URL helper.</param>
        /// <param name="actionName">The name of the action method.</param>
        /// <param name="controllerName">The name of the controller.</param>
        /// <param name="routeValues">The route values.</param>
        /// <returns>The absolute URL.</returns>
        public static string AbsoluteAction(
            this IUrlHelper url,
            string actionName,
            string controllerName,
            object routeValues = null)
        {
            return url.Action(actionName, controllerName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
        }

        /// <summary>
        /// Generates a fully qualified URL to the specified content by using the specified content path. Converts a
        /// virtual (relative) path to an application absolute path.
        /// </summary>
        /// <param name="url">The URL helper.</param>
        /// <param name="contentPath">The content path.</param>
        /// <returns>The absolute URL.</returns>
        public static string AbsoluteContent(
            this IUrlHelper url,
            string contentPath)
        {
            HttpRequest request = url.ActionContext.HttpContext.Request;
            return new Uri(new Uri(request.Scheme + "://" + request.Host.Value), url.Content(contentPath)).ToString();
        }

        /// <summary>
        /// Generates a fully qualified URL to the specified route by using the route name and route values.
        /// </summary>
        /// <param name="url">The URL helper.</param>
        /// <param name="routeName">Name of the route.</param>
        /// <param name="routeValues">The route values.</param>
        /// <returns>The absolute URL.</returns>
        public static string AbsoluteRouteUrl(
            this IUrlHelper url,
            string routeName,
            object routeValues = null)
        {
            return url.RouteUrl(routeName, routeValues, url.ActionContext.HttpContext.Request.Scheme);
        }
    }
}

jQuery Button.click() event is triggered twice

If you use

$( document ).ready({ })

or

$(function() { });

more than once, the click function will trigger as many times as it is used.

How to use router.navigateByUrl and router.navigate in Angular

In addition to the provided answer, there are more details to navigate. From the function's comments:

/**
 * Navigate based on the provided array of commands and a starting point.
 * If no starting route is provided, the navigation is absolute.
 *
 * Returns a promise that:
 * - resolves to 'true' when navigation succeeds,
 * - resolves to 'false' when navigation fails,
 * - is rejected when an error happens.
 *
 * ### Usage
 *
 * ```
 * router.navigate(['team', 33, 'user', 11], {relativeTo: route});
 *
 * // Navigate without updating the URL
 * router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true});
 * ```
 *
 * In opposite to `navigateByUrl`, `navigate` always takes a delta that is applied to the current
 * URL.
 */

The Router Guide has more details on programmatic navigation.

Inline CSS styles in React: how to implement a:hover?

The simple way is using ternary operator

var Link = React.createClass({
  getInitialState: function(){
    return {hover: false}
  },
  toggleHover: function(){
    this.setState({hover: !this.state.hover})
  },
  render: function() {
    var linkStyle;
    if (this.state.hover) {
      linkStyle = {backgroundColor: 'red'}
    } else {
      linkStyle = {backgroundColor: 'blue'}
    }
    return(
      <div>
        <a style={this.state.hover ? {"backgroundColor": 'red'}: {"backgroundColor": 'blue'}} onMouseEnter={this.toggleHover} onMouseLeave={this.toggleHover}>Link</a>
      </div>
    )
  }

Regex date format validation on Java

The following regex will accept YYYY-MM-DD (within the range 1600-2999 year) formatted dates taking into consideration leap years:

 ^((?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:(?:0[13578]|1[02])(-)31)|((0[1,3-9]|1[0-2])(-)(29|30))))$|^(?:(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(-)02(-)29)$|^(?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:0[1-9])|(?:1[0-2]))(-)(?:0[1-9]|1\d|2[0-8])$

Examples:

Date regex examples

You can test it here.

Note: if you want to accept one digit as month or day you can use:

 ^((?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:(?:0?[13578]|1[02])(-)31)|((0?[1,3-9]|1[0-2])(-)(29|30))))$|^(?:(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(-)0?2(-)29)$|^(?:(?:1[6-9]|2[0-9])\d{2})(-)(?:(?:0?[1-9])|(?:1[0-2]))(-)(?:0?[1-9]|1\d|2[0-8])$

I have created the above regex starting from this solution

Best way to get whole number part of a Decimal number

You just need to cast it, as such:

int intPart = (int)343564564.4342

If you still want to use it as a decimal in later calculations, then Math.Truncate (or possibly Math.Floor if you want a certain behaviour for negative numbers) is the function you want.

Create SQL script that create database and tables

Although Clayton's answer will get you there (eventually), in SQL2005/2008/R2/2012 you have a far easier option:

Right-click on the Database, select Tasks and then Generate Scripts, which will launch the Script Wizard. This allows you to generate a single script that can recreate the full database including table/indexes & constraints/stored procedures/functions/users/etc. There are a multitude of options that you can configure to customise the output, but most of it is self explanatory.

If you are happy with the default options, you can do the whole job in a matter of seconds.

If you want to recreate the data in the database (as a series of INSERTS) I'd also recommend SSMS Tools Pack (Free for SQL 2008 version, Paid for SQL 2012 version).

How/When does Execute Shell mark a build as failure in Jenkins?

Simple and short answer to your question is

Please add following line into your "Execute shell" Build step.

#!/bin/sh

Now let me explain you the reason why we require this line for "Execute Shell" build job.

By default Jenkins take /bin/sh -xe and this means -x will print each and every command.And the other option -e, which causes shell to stop running a script immediately when any command exits with non-zero (when any command fails) exit code.

So by adding the #!/bin/sh will allow you to execute with no option.

How to reload current page?

import { DOCUMENT } from '@angular/common';
import { Component, Inject } from '@angular/core';

@Component({
  selector: 'app-refresh-banner-notification',
  templateUrl: './refresh-banner-notification.component.html',
  styleUrls: ['./refresh-banner-notification.component.scss']
})

export class RefreshBannerNotificationComponent {

  constructor(
    @Inject(DOCUMENT) private _document: Document
  ) {}

  refreshPage() {
    this._document.defaultView.location.reload();
  }
}

How to transform array to comma separated words string?

Make your array a variable and use implode.

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

http://php.net/manual/en/function.implode.php

"Use of undeclared type" in Swift, even though type is internal, and exists in same module

In my case, this was caused by a subclass name being used in the very next line as a variable name with a different type:

var binGlow: pipGlow = pipGlow(style: "Bin")
var pipGlow: PipGlowSprite = PipGlowSprite()

Notice that in line 1, pipGlow is the name of the subclass (of SKShapeNode), but in line two, I was using pipGlow as a variable name. This was not only bad coding style, but apparently an outright no-no as well! Once I change the second line to:

var binGlow: pipGlow = pipGlow(style: "Bin")
var pipGlowSprite: PipGlowSprite = PipGlowSprite()

I no longer received the error. I hope this helps someone!

New lines (\r\n) are not working in email body

OP's problem was related with HTML coding. But if you are using plain text, please use "\n" and not "\r\n".

My personal use case: using mailx mailer, simply replacing "\r\n" into "\n" fixed my issue, related with wrong automatic Content-Type setting.

Wrong header:

User-Agent: Heirloom mailx 12.4 7/29/08
MIME-Version: 1.0
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64

Correct header:

User-Agent: Heirloom mailx 12.4 7/29/08
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

I'm not saying that "application/octet-stream" and "base64" are always wrong/unwanted, but they where in my case.

XML Schema (XSD) validation tool?

one great visual tool to validate and generate XSD from XML is IntelliJ IDEA, intuitive and simple.

OpenCV - Apply mask to a color image

The other methods described assume a binary mask. If you want to use a real-valued single-channel grayscale image as a mask (e.g. from an alpha channel), you can expand it to three channels and then use it for interpolation:

assert len(mask.shape) == 2 and issubclass(mask.dtype.type, np.floating)
assert len(foreground_rgb.shape) == 3
assert len(background_rgb.shape) == 3

alpha3 = np.stack([mask]*3, axis=2)
blended = alpha3 * foreground_rgb + (1. - alpha3) * background_rgb

Note that mask needs to be in range 0..1 for the operation to succeed. It is also assumed that 1.0 encodes keeping the foreground only, while 0.0 means keeping only the background.

If the mask may have the shape (h, w, 1), this helps:

alpha3 = np.squeeze(np.stack([np.atleast_3d(mask)]*3, axis=2))

Here np.atleast_3d(mask) makes the mask (h, w, 1) if it is (h, w) and np.squeeze(...) reshapes the result from (h, w, 3, 1) to (h, w, 3).

How to center a WPF app on screen?

You don't need to reference the System.Windows.Forms assembly from your application. Instead, you can use System.Windows.SystemParameters.WorkArea. This is equivalent to the System.Windows.Forms.Screen.PrimaryScreen.WorkingArea!

How do I get the list of keys in a Dictionary?

List<string> keyList = new List<string>(this.yourDictionary.Keys);

How do I use the nohup command without getting nohup.out?

If you have a BASH shell on your mac/linux in-front of you, you try out the below steps to understand the redirection practically :

Create a 2 line script called zz.sh

#!/bin/bash
echo "Hello. This is a proper command"
junk_errorcommand
  • The echo command's output goes into STDOUT filestream (file descriptor 1).
  • The error command's output goes into STDERR filestream (file descriptor 2)

Currently, simply executing the script sends both STDOUT and STDERR to the screen.

./zz.sh

Now start with the standard redirection :

zz.sh > zfile.txt

In the above, "echo" (STDOUT) goes into the zfile.txt. Whereas "error" (STDERR) is displayed on the screen.

The above is the same as :

zz.sh 1> zfile.txt

Now you can try the opposite, and redirect "error" STDERR into the file. The STDOUT from "echo" command goes to the screen.

zz.sh 2> zfile.txt

Combining the above two, you get:

zz.sh 1> zfile.txt 2>&1

Explanation:

  • FIRST, send STDOUT 1 to zfile.txt
  • THEN, send STDERR 2 to STDOUT 1 itself (by using &1 pointer).
  • Therefore, both 1 and 2 goes into the same file (zfile.txt)

Eventually, you can pack the whole thing inside nohup command & to run it in the background:

nohup zz.sh 1> zfile.txt 2>&1&

When is it acceptable to call GC.Collect?

You can call GC.Collect() when you know something about the nature of the app the garbage collector doesn't. It's tempting to think that, as the author, this is very likely. However, the truth is the GC amounts to a pretty well-written and tested expert system, and it's rare you'll know something about the low level code paths it doesn't.

The best example I can think of where you might have some extra information is a app that cycles between idle periods and very busy periods. You want the best performance possible for the busy periods and therefore want to use the idle time to do some clean up.

However, most of the time the GC is smart enough to do this anyway.

How to diff a commit with its parent?

Use git show $COMMIT. It'll show you the log message for the commit, and the diff of that particular commit.

How do you perform a left outer join using linq extension methods

Improving on Ocelot20's answer, if you have a table you're left outer joining with where you just want 0 or 1 rows out of it, but it could have multiple, you need to Order your joined table:

var qry = Foos.GroupJoin(
      Bars.OrderByDescending(b => b.Id),
      foo => foo.Foo_Id,
      bar => bar.Foo_Id,
      (f, bs) => new { Foo = f, Bar = bs.FirstOrDefault() });

Otherwise which row you get in the join is going to be random (or more specifically, whichever the db happens to find first).

CORS: credentials mode is 'include'

Just add Axios.defaults.withCredentials=true instead of ({credentials: true}) in client side, and change app.use(cors()) to

app.use(cors(
  {origin: ['your client side server'],
  methods: ['GET', 'POST'],
  credentials:true,
}
))

importing external ".txt" file in python

This answer is modified from infrared's answer at Splitting large text file by a delimiter in Python

with open('words.txt') as fp:
    contents = fp.read()
    for entry in contents:
        # do something with entry  

Local storage in Angular 2

We can easily use the localStorage for setting the data and receiving the data.

Note: it works with both angular2 and angular 4

//set the data
localStorage.setItem(key, value);   //syntax example
localStorage.setItem('tokenKey', response.json().token);

//get the data
localStorage.getItem('tokenKey')

//confirm if token is exist or not
return localStorage.getItem('tokenKey') != null;

Git refusing to merge unrelated histories on rebase

For this, enter the command:

git pull origin branchname --allow-unrelated-histories

For example,

git pull origin master --allow-unrelated-histories

Reference:

GitHub unrelated histories issue

maxlength ignored for input type="number" in Chrome

You can try this as well for numeric input with length restriction

<input type="tel" maxlength="4" />

How can I sort a std::map first by value, then by key?

std::map already sorts the values using a predicate you define or std::less if you don't provide one. std::set will also store items in order of the of a define comparator. However neither set nor map allow you to have multiple keys. I would suggest defining a std::map<int,std::set<string> if you want to accomplish this using your data structure alone. You should also realize that std::less for string will sort lexicographically not alphabetically.

How to prevent the "Confirm Form Resubmission" dialog?

I had a situation where I could not use any of the above answers. My case involved working with search page where users would get "confirm form resubmission" if the clicked back after navigating to any of the search results. I wrote the following javascript which worked around the issue. It isn't a great fix as it is a bit blinky, and it doesn't work on IE8 or earlier. Still, though this might be useful or interesting for someone dealing with this issue.

jQuery(document).ready(function () {

//feature test
if (!history)
    return;

var searchBox = jQuery("#searchfield");

    //This occurs when the user get here using the back button
if (history.state && history.state.searchTerm != null && history.state.searchTerm != "" && history.state.loaded != null && history.state.loaded == 0) {

    searchBox.val(history.state.searchTerm);

    //don't chain reloads
    history.replaceState({ searchTerm: history.state.searchTerm, page: history.state.page, loaded: 1 }, "", document.URL);

    //perform POST
    document.getElementById("myForm").submit();

    return;
}

    //This occurs the first time the user hits this page.
history.replaceState({ searchTerm: searchBox.val(), page: pageNumber, loaded: 0 }, "", document.URL);

});

intellij incorrectly saying no beans of type found for autowired repository

Surprisingly, A Feign oriented project that successfully ran with Eclipse could not run in InteliJ. When started the application, InteliJ complained about the Feign client I tried to inject to the serviceImpl layer saying: field personRestClient (my Feign client) in ... required a bean of type ... that could not be found. Consider defining a bean of type '....' in your configuration.

I wasted a long time trying to understand what is wrong. I found a solution (for InteliJ) which I do not completely understand:

  1. Alt Shift F10 (or run menu)
  2. Select 'Edit configuration'
  3. In configuration window, Check the checkbox 'include dependencies with "Provided" scope'
  4. Run your application

Or choose Eclipse :)

Set element width or height in Standards Mode

Try declaring the unit of width:

e1.style.width = "400px"; // width in PIXELS

Get visible items in RecyclerView

Addendum:

The proposed functions findLast...Position() do not work correctly in a scenario with a collapsing toolbar while the toolbar is expanded.

It seems that the recycler view has a fixed height, and while the toolbar is expanded, the recycler is moved down, partially out of the screen. As a consequence the results of the proposed functions are too high. Example: The last visible item is told to be #9, but in fact item #7 is the last one that is on screen.

This behaviour is also the reason why my view often failed to scroll to the correct position, i.e. scrollToPosition() did not work correctly (I finally collapsed the toolbar programmatically).

Intercept and override HTTP requests from WebView

As far as I know, shouldOverrideUrlLoading is not called for images but rather for hyperlinks... I think the appropriate method is

@Override public void onLoadResource(WebView view, String url)

This method is called for every resource (image, styleesheet, script) that's loaded by the webview, but since it's a void, I haven't found a way to change that url and replace it so that it loads a local resource ...

How to create a inset box-shadow only on one side?

Literally you can't do such a thing, but you should try this CSS trick:

box-shadow: inset 0 3vw 6vw rgba(0,0,0,0.6), inset 0 -3vw 6vw rgba(0,0,0,0.6);

How to convert strings into integers in Python?

I would rather prefer using only comprehension lists:

[[int(y) for y in x] for x in T1]

How to get UTC value for SYSDATE on Oracle

Usually, I work with DATE columns, not the larger but more precise TIMESTAMP used by some answers.

The following will return the current UTC date as just that -- a DATE.

CAST(sys_extract_utc(SYSTIMESTAMP) AS DATE)

I often store dates like this, usually with the field name ending in _UTC to make it clear for the developer. This allows me to avoid the complexity of time zones until last-minute conversion by the user's client. Oracle can store time zone detail with some data types, but those types require more table space than DATE, and knowledge of the original time zone is not always required.

Why do table names in SQL Server start with "dbo"?

It's new to SQL 2005 and offers a simplified way to group objects, especially for the purpose of securing the objects in that "group".

The following link offers a more in depth explanation as to what it is, why we would use it:

Understanding the Difference between Owners and Schemas in SQL Server

MySQL: update a field only if condition is met

Try this:

UPDATE test
SET
   field = 1
WHERE id = 123 and condition

How do I escape double quotes in attributes in an XML String in T-SQL?

In Jelly.core to test a literal string one would use:

&lt;core:when test="${ name == 'ABC' }"&gt; 

But if I have to check for string "Toy's R Us":

&lt;core:when test="${ name == &amp;quot;Toy&apos;s R Us&amp;quot; }"&gt;

It would be like this, if the double quotes were allowed inside:

&lt;core:when test="${ name == "Toy's R Us" }"&gt; 

Python Traceback (most recent call last)

You are using Python 2 for which the input() function tries to evaluate the expression entered. Because you enter a string, Python treats it as a name and tries to evaluate it. If there is no variable defined with that name you will get a NameError exception.

To fix the problem, in Python 2, you can use raw_input(). This returns the string entered by the user and does not attempt to evaluate it.

Note that if you were using Python 3, input() behaves the same as raw_input() does in Python 2.

How do I delete multiple rows with different IDs?

Delete from BA_CITY_MASTER where CITY_NAME in (select CITY_NAME from BA_CITY_MASTER group by CITY_NAME having count(CITY_NAME)>1);

Prevent text selection after double click

For those looking for a solution for Angular 2+.

You can use the mousedown output of the table cell.

<td *ngFor="..."
    (mousedown)="onMouseDown($event)"
    (dblclick) ="onDblClick($event)">
  ...
</td>

And prevent if the detail > 1.

public onMouseDown(mouseEvent: MouseEvent) {
  // prevent text selection for dbl clicks.
  if (mouseEvent.detail > 1) mouseEvent.preventDefault();
}

public onDblClick(mouseEvent: MouseEvent) {
 // todo: do what you really want to do ...
}

The dblclick output continues to work as expected.

How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

    def wordCount(mystring):  
        tempcount = 0  
        count = 1  

        try:  
            for character in mystring:  
                if character == " ":  
                    tempcount +=1  
                    if tempcount ==1:  
                        count +=1  

                    else:  
                        tempcount +=1
                 else:
                     tempcount=0

             return count  

         except Exception:  
             error = "Not a string"  
             return error  

    mystring = "I   am having   a    very nice 23!@$      day."           

    print(wordCount(mystring))  

output is 8

Get the name of an object's type

Say you have var obj;

If you just want the name of obj's type, like "Object", "Array", or "String", you can use this:

Object.prototype.toString.call(obj).split(' ')[1].replace(']', '');

Kill python interpeter in linux from the terminal

pgrep -f youAppFile.py | xargs kill -9

pgrep returns the PID of the specific file will only kill the specific application.

How do I create a batch file timer to execute / call another batch throughout the day

I did it by writing a little C# app that just wakes up to launch periodic tasks -- don't know if it is doable from a batch file without downloading extensions to support a sleep command. (For my purposes the Windows scheduler didn't work because the apps launched had no graphics context available.)

Why Maven uses JDK 1.6 but my java -version is 1.7

add the following to your ~/.mavenrc:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/{jdk-version}/Contents/Home

Second Solution:

echo export "JAVA_HOME=\$(/usr/libexec/java_home)" >> ~/.bash_profile

Rendering HTML inside textarea

Since you only said render, yes you can. You could do something along the lines of this:

_x000D_
_x000D_
function render(){_x000D_
 var inp     = document.getElementById("box");_x000D_
 var data = `_x000D_
<svg xmlns="http://www.w3.org/2000/svg" width="${inp.offsetWidth}" height="${inp.offsetHeight}">_x000D_
<foreignObject width="100%" height="100%">_x000D_
<div xmlns="http://www.w3.org/1999/xhtml" _x000D_
style="font-family:monospace;font-style: normal; font-variant: normal; font-size:13.3px;padding:2px;;">_x000D_
${inp.value} <i style="color:red">cant touch this</i>_x000D_
</div>_x000D_
</foreignObject>_x000D_
</svg>`;_x000D_
 var blob = new Blob( [data], {type:'image/svg+xml'} );_x000D_
 var url=URL.createObjectURL(blob);_x000D_
 inp.style.backgroundImage="url("+URL.createObjectURL(blob)+")";_x000D_
 }_x000D_
 onload=function(){_x000D_
  render();_x000D_
  ro = new ResizeObserver(render);_x000D_
 ro.observe(document.getElementById("box"));_x000D_
 }
_x000D_
#box{_x000D_
  color:transparent;_x000D_
  caret-color: black;_x000D_
  font-style: normal;/*must be same as in the svg for caret to align*/_x000D_
  font-variant: normal; _x000D_
  font-size:13.3px;_x000D_
  padding:2px;_x000D_
  font-family:monospace;_x000D_
}
_x000D_
<textarea id="box" oninput="render()">you can edit me!</textarea>
_x000D_
_x000D_
_x000D_ This makes it so that a textarea will render html! Besides the flashing when resizing, inability to directly use classes and having to make sure that the div in the svg has the same format as the textarea for the caret to align correctly, it's works!

What is the difference between Hibernate and Spring Data JPA

Hibernate is implementation of "JPA" which is a specification for Java objects in Database.

I would recommend to use w.r.t JPA as you can switch between different ORMS.

When you use JDBC then you need to use SQL Queries, so if you are proficient in SQL then go for JDBC.

Fixing "Lock wait timeout exceeded; try restarting transaction" for a 'stuck" Mysql table?

I ran into the same problem with an "update"-statement. My solution was simply to run through the operations available in phpMyAdmin for the table. I optimized, flushed and defragmented the table (not in that order). No need to drop the table and restore it from backup for me. :)

Is there a need for range(len(a))?

Sometimes matplotlib requires range(len(y)), e.g., while y=array([1,2,5,6]), plot(y) works fine, scatter(y) does not. One has to write scatter(range(len(y)),y). (Personally, I think this is a bug in scatter; plot and its friends scatter and stem should use the same calling sequences as much as possible.)

How to convert an Array to a Set in Java

After you do Arrays.asList(array) you can execute Set set = new HashSet(list);

Here is a sample method, you can write:

public <T> Set<T> GetSetFromArray(T[] array) {
    return new HashSet<T>(Arrays.asList(array));
}

How to get current class name including package name in Java?

There is a class, Class, that can do this:

Class c = Class.forName("MyClass"); // if you want to specify a class
Class c = this.getClass();          // if you want to use the current class

System.out.println("Package: "+c.getPackage()+"\nClass: "+c.getSimpleName()+"\nFull Identifier: "+c.getName());

If c represented the class MyClass in the package mypackage, the above code would print:

Package: mypackage
Class: MyClass
Full Identifier: mypackage.MyClass

You can take this information and modify it for whatever you need, or go check the API for more information.

How to open remote files in sublime text 3

On server

Install rsub:

wget -O /usr/local/bin/rsub \https://raw.github.com/aurora/rmate/master/rmate
chmod a+x /usr/local/bin/rsub

On local

  1. Install rsub Sublime3 package:

On Sublime Text 3, open Package Manager (Ctrl-Shift-P on Linux/Win, Cmd-Shift-P on Mac, Install Package), and search for rsub and install it

  1. Open command line and connect to remote server:

ssh -R 52698:localhost:52698 server_user@server_address

  1. after connect to server run this command on server:

rsub path_to_file/file.txt

  1. File opening auto in Sublime 3

As of today (2018/09/05) you should use : https://github.com/randy3k/RemoteSubl because you can find it in packagecontrol.io while "rsub" is not present.

How to upload a file in Django?

Not sure if there any disadvantages to this approach but even more minimal, in views.py:

entry = form.save()

# save uploaded file
if request.FILES['myfile']:
    entry.myfile.save(request.FILES['myfile']._name, request.FILES['myfile'], True)

IOS: verify if a point is inside a rect

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

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

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

You can also use this method in bellow UITouch Method :

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

Creating a very simple linked list

Here is a good implementation.

  1. It is short, but implemented Add(x), Delete(x), Contain(x) and Print().
  2. It avoid special process when add to empty list or delete the first element. While most of other examples did special process when delete the first element.
  3. The list can contain any data type.

    using System;
    
    class Node<Type> : LinkedList<Type>
    {   // Why inherit from LinkedList? A: We need to use polymorphism.
        public Type value;
        public Node(Type value) { this.value = value; }
    }
    class LinkedList<Type>
    {   
        Node<Type> next;  // This member is treated as head in class LinkedList, but treated as next element in class Node.
        /// <summary> if x is in list, return previos pointer of x. (We can see any class variable as a pointer.)
        /// if not found, return the tail of the list. </summary>
        protected LinkedList<Type> Previos(Type x)
        {
            LinkedList<Type> p = this;      // point to head
            for (; p.next != null; p = p.next)
                if (p.next.value.Equals(x))
                    return p;               // find x, return the previos pointer.
            return p;                       // not found, p is the tail.
        }
        /// <summary> return value: true = success ; false = x not exist </summary>
        public bool Contain(Type x) { return Previos(x).next != null ? true : false; }
        /// <summary> return value: true = success ; false = fail to add. Because x already exist. 
        /// </summary> // why return value? If caller want to know the result, they don't need to call Contain(x) before, the action waste time.
        public bool Add(Type x)
        {
            LinkedList<Type> p = Previos(x);
            if (p.next != null)             // Find x already in list
                return false;
            p.next = new Node<Type>(x);
            return true;
        }
        /// <summary> return value: true = success ; false = x not exist </summary>
        public bool Delete(Type x)
        {
            LinkedList<Type> p = Previos(x);
            if (p.next == null)
                return false;
            //Node<Type> node = p.next;
            p.next = p.next.next;
            //node.Dispose();       // GC dispose automatically.
            return true;
        }
        public void Print()
        {
            Console.Write("List: ");
            for (Node<Type> node = next; node != null; node = node.next)
                Console.Write(node.value.ToString() + " ");
            Console.WriteLine();
        }
    }
    class Test
    {
        static void Main()
        {
            LinkedList<int> LL = new LinkedList<int>();
            if (!LL.Contain(0)) // Empty list
                Console.WriteLine("0 is not exist.");
            LL.Print();
            LL.Add(0);      // Add to empty list
            LL.Add(1); LL.Add(2); // attach to tail
            LL.Add(2);      // duplicate add, 2 is tail.
            if (LL.Contain(0))// Find existed element which is head
                Console.WriteLine("0 is exist.");
            LL.Print();
            LL.Delete(0);   // Delete head
            LL.Delete(2);   // Delete tail
            if (!LL.Delete(0)) // Delete non-exist element
                Console.WriteLine("0 is not exist.");
            LL.Print();
            Console.ReadLine();
        }
    }
    

By the way, the implementation in http://www.functionx.com/csharp1/examples/linkedlist.htm have some problem:

  1. Delete() will fail when there is only 1 element. (Throw exception at line "Head.Next = Current.Next;" because Current is null.)
  2. Delete(position) will fail when deleting first element, In other words, call Delete(0) will fail.

CSS: Set a background color which is 50% of the width of the window

You can make a hard distinction instead of linear gradient by putting the second color to 0%

For instance,

Gradient - background: linear-gradient(80deg, #ff0000 20%, #0000ff 80%);

Hard distinction - background: linear-gradient(80deg, #ff0000 20%, #0000ff 0%);

How to compare two object variables in EL expression language?

Not sure if I get you right, but the simplest way would be something like:

<c:if test="${languageBean.locale == 'en'">
  <f:selectItems value="#{customerBean.selectableCommands_limited_en}" />
</c:if>

Just a quick copy and paste from an app of mine...

HTH

how to set default method argument values?

You can't declare default values for the parameters like C# (I believe) lets you, but you could simply just create an overload.

public int doSomething(int arg1, int arg2) {
    //some logic here
    return 0;
}

//overload supplies default values of 1 and 2
public int doSomething() {
    return doSomething(1, 2);
}

If you are going to do something like this please do everyone else who works with your code a favor and make sure you mention in Javadoc comments what the default values you are using are!

What is the difference between a Relational and Non-Relational Database?

The relational database uses a formal system of predicates to address data. The underlying physical implementation is of no substance and can vary to optimize for certain operations, but it must always assume the relational model. In layman's terms, that's just saying I know exactly how many values (attributes) each row (tuple) in my table (relation) has and now I want to exploit the fact accordingly, thoroughly and to it's extreme. That's the true nature of the beast. 

Since we're obviously the generation that has had a relational upbringing, if you look at NoSQL database models from the perspective of the relational model, again in layman's terms, the first obvious difference is that no assumptions about the number of values a row can contain is ever made. This is really oversimplifying the matter and does not cleanly apply to the intricacies of the physical models of every NoSQL database, but it's the pinnacle of the relational model and the first assumption we have to leave behind or, if you'd rather, the biggest leap we have to make.

We can agree to two things that are true for every DBMS: it can store any kind of data and has enough mathematical underpinnings to make it possible to manage the data in any way imaginable. The reality is that you'll never want to make the mistake of putting any of the two points to the test, but rather just stick with what the actual DBMS was really made for. In layman's terms: respect the beast within!

(Please note that I've avoided comparing the (obviously) well founded standards revolving around the relational model against the many flavors provided by NoSQL databases. If you'd like, consider NoSQL databases as an umbrella term for any DBMS that does not completely assume the relational model, in exclusion to everything else. The differences are too many, but that's the principal difference and the one I think would be of most use to you to understand the two.)

Allow anything through CORS Policy

Have a look at the rack-cors middleware. It will handle CORS headers in a configurable manner.

Javascript can't find element by id?

The problem is that you are trying to access the element before it exists. You need to wait for the page to be fully loaded. A possible approach is to use the onload handler:

window.onload = function () {
    var e = document.getElementById("db_info");
    e.innerHTML='Found you';
};

Most common JavaScript libraries provide a DOM-ready event, though. This is better, since window.onload waits for all images, too. You do not need that in most cases.

Another approach is to place the script tag right before your closing </body>-tag, since everything in front of it is loaded at the time of execution, then.

Gerrit error when Change-Id in commit messages are missing

under my .git/hooks folder, some sample files were missing. like commit-msg,post-commit.sample,post-update.sample...adding these files resolved my change id missing issue.

Execute script after specific delay using JavaScript

You need to use setTimeout and pass it a callback function. The reason you can't use sleep in javascript is because you'd block the entire page from doing anything in the meantime. Not a good plan. Use Javascript's event model and stay happy. Don't fight it!

jQuery: Test if checkbox is NOT checked

if($("#checkbox1").prop('checked') == false){
    alert('checkbox is not checked');
    //do something
}
else
{ 
    alert('checkbox is checked');
}

Font Awesome not working, icons showing as squares

Double check the fontawesome-all.css file - at the very bottom there will be a path to the webfonts folder. Mine had "../webfonts" format in it, which meant that the css file would be looking 1 level up from where it is. As all of my css files were in css folder and I added the fonts to the same folder, this was not working.

Just move your fonts folder up a level and all should be well :)

Tested with Font Awesome 5.0

What is the preferred Bash shebang?

/bin/sh is usually a link to the system's default shell, which is often bash but on, e.g., Debian systems is the lighter weight dash. Either way, the original Bourne shell is sh, so if your script uses some bash (2nd generation, "Bourne Again sh") specific features ([[ ]] tests, arrays, various sugary things, etc.), then you should be more specific and use the later. This way, on systems where bash is not installed, your script won't run. I understand there may be an exciting trilogy of films about this evolution...but that could be hearsay.

Also note that when evoked as sh, bash to some extent behaves as POSIX standard sh (see also the GNU docs about this).

How to avoid Sql Query Timeout

Although there is clearly some kind of network instability or something interfering with your connection (15 minutes is possible that you could be crossing a NAT boundary or something in your network is dropping the session), I would think you want such a simple?) query to return well within any anticipated timeoue (like 1s).

I would talk to your DBA and get an index created on the underlying tables on MemberType, Status. If there isn't a single underlying table or these are more complex and created by the view or UDF, and you are running SQL Server 2005 or above, have him consider indexing the view (basically materializing the view in an indexed fashion).

How to mark a build unstable in Jenkins when running shell scripts

You can just call "exit 1", and the build will fail at that point and not continue. I wound up making a passthrough make function to handle it for me, and call safemake instead of make for building:

function safemake {
  make "$@"
  if [ "$?" -ne 0 ]; then
    echo "ERROR: BUILD FAILED"
    exit 1
  else
    echo "BUILD SUCCEEDED"
  fi
}

Override valueof() and toString() in Java enum

You can use a static Map in your enum that maps Strings to enum constants. Use it in a 'getEnum' static method. This skips the need to iterate through the enums each time you want to get one from its String value.

public enum RandomEnum {

    StartHere("Start Here"),
    StopHere("Stop Here");

    private final String strVal;
    private RandomEnum(String strVal) {
        this.strVal = strVal;
    }

    public static RandomEnum getEnum(String strVal) {
        if(!strValMap.containsKey(strVal)) {
            throw new IllegalArgumentException("Unknown String Value: " + strVal);
        }
        return strValMap.get(strVal);
    }

    private static final Map<String, RandomEnum> strValMap;
    static {
        final Map<String, RandomEnum> tmpMap = Maps.newHashMap();
        for(final RandomEnum en : RandomEnum.values()) {
            tmpMap.put(en.strVal, en);
        }
        strValMap = ImmutableMap.copyOf(tmpMap);
    }

    @Override
    public String toString() {
        return strVal;
    }
}

Just make sure the static initialization of the map occurs below the declaration of the enum constants.

BTW - that 'ImmutableMap' type is from the Google guava API, and I definitely recommend it in cases like this.


EDIT - Per the comments:

  1. This solution assumes that each assigned string value is unique and non-null. Given that the creator of the enum can control this, and that the string corresponds to the unique & non-null enum value, this seems like a safe restriction.
  2. I added the 'toSTring()' method as asked for in the question

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

I also had the same problem. I used next way:

1.Added settings.xml file (~/.m2/settings.xml) with next content

<proxies>
   <proxy>
      <active>true</active>
      <protocol>http</protocol>
      <host>qq-proxya</host>
      <port>8080</port>
      <username>user</username>
      <password>passw</password>
      <nonProxyHosts>www.google.com|*.example.com</nonProxyHosts>
    </proxy>
  </proxies>

3. Using cmd go to folder with my project and wrote mvn clean and after that mvn install !

  1. After that updated project in the Eclipse(Alt + F5) or right click on project -> Maven -> Update project

P.S. after that, when I add new dependency to my project I have to compile project using cmd(mvn compile). Because if I do it using eclipse plugin, I get error connecting with proxy connection.

Copy array by value

You can use array spreads ... to copy arrays.

const itemsCopy = [...items];

Also if want to create a new array with the existing one being part of it:

var parts = ['shoulders', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes'];

Array spreads are now supported in all major browsers but if you need older support use typescript or babel and compile to ES5.

More info on spreads

PHP: merge two arrays while keeping keys instead of reindexing?

Try array_replace_recursive or array_replace functions

$a = array('userID' => 1, 'username'=> 2);
array (
  userID => 1,
  username => 2
)
$b = array('userID' => 1, 'companyID' => 3);
array (
  'userID' => 1,
  'companyID' => 3
)
$c = array_replace_recursive($a,$b);
array (
  userID => 1,
  username => 2,
  companyID => 3
)

http://php.net/manual/en/function.array-replace-recursive.php

Taskkill /f doesn't kill a process

NirSoft's NirCmd did the job for me:

nircmd killprocess "process name.exe"

killprocess man page is here.

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
FROM
(
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

How to insert a text at the beginning of a file?

echo -n "text to insert " ;tac filename.txt| tac > newfilename.txt

The first tac pipes the file backwards (last line first) so the "text to insert" appears last. The 2nd tac wraps it once again so the inserted line is at the beginning and the original file is in its original order.

How to destroy a DOM element with jQuery?

Is $target.remove(); what you're looking for?

https://api.jquery.com/remove/

What happened to the .pull-left and .pull-right classes in Bootstrap 4?

I was able to do this with the following classes in my project

d-flex justify-content-end

<div class="col-lg-6 d-flex justify-content-end">

How to use the divide function in the query?

Try something like this

select Cast((SPGI09_EARLY_OVER_T – (SPGI09_OVER_WK_EARLY_ADJUST_T) / (SPGI09_EARLY_OVER_T + SPGR99_LATE_CM_T  + SPGR99_ON_TIME_Q)) as varchar(20) + '%' as percentageAmount
from CSPGI09_OVERSHIPMENT

I presume the value is a representation in percentage - if not convert it to a valid percentage total, then add the % sign and convert the column to varchar.

HTML5: Slider with two inputs possible?

Coming late, but noUiSlider avoids having a jQuery-ui dependency, which the accepted answer does not. Its only "caveat" is IE support is for IE9 and newer, if legacy IE is a deal breaker for you.

It's also free, open source and can be used in commercial projects without restrictions.

Installation: Download noUiSlider, extract the CSS and JS file somewhere in your site file system, and then link to the CSS from head and to JS from body:

<!-- In <head> -->
<link href="nouislider.min.css" rel="stylesheet">

<!-- In <body> -->
<script src="nouislider.min.js"></script>

Example usage: Creates a slider which goes from 0 to 100, and starts set to 20-80.

HTML:

<div id="slider">
</div>

JS:

var slider = document.getElementById('slider');

noUiSlider.create(slider, {
    start: [20, 80],
    connect: true,
    range: {
        'min': 0,
        'max': 100
    }
});

Find and Replace string in all files recursive using grep and sed

grep -rl $oldstring . | xargs sed -i "s/$oldstring/$newstring/g"

How to display my application's errors in JSF?

In case anyone was curious, I was able to figure this out based on all of your responses combined!

This is in the Facelet:

<h:form id="myform">
  <h:inputSecret value="#{createNewPassword.newPassword1}" id="newPassword1" />
  <h:message class="error" for="newPassword1" id="newPassword1Error" />
  <h:inputSecret value="#{createNewPassword.newPassword2}" id="newPassword2" />
  <h:message class="error" for="newPassword2" id="newPassword2Error" />
  <h:commandButton value="Continue" action="#{createNewPassword.continueButton}" />
</h:form>

This is in the continueButton() method:

FacesContext.getCurrentInstance().addMessage("myForm:newPassword1", new FacesMessage(PASSWORDS_DONT_MATCH, PASSWORDS_DONT_MATCH));

And it works! Thanks for the help!

How to check ASP.NET Version loaded on a system?

You can use

<%
Response.Write("Version: " + System.Environment.Version.ToString());
%>

That will get the currently running version. You can check the registry for all installed versions at:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP

Injecting Mockito mocks into a Spring bean

For the record, all my tests correctly work by just making the fixture lazy-initialized, e.g.:

<bean id="fixture"
      class="it.tidalwave.northernwind.rca.embeddedserver.impl.DefaultEmbeddedServer"
      lazy-init="true" /> <!-- To solve Mockito + Spring problems -->

<bean class="it.tidalwave.messagebus.aspect.spring.MessageBusAdapterFactory" />

<bean id="applicationMessageBus"
      class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="it.tidalwave.messagebus.MessageBus" />
</bean>

<bean class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="javax.servlet.ServletContext" />
</bean>

I suppose the rationale is the one Mattias explains here (at the bottom of the post), that a workaround is changing the order the beans are declared - lazy initialization is "sort of" having the fixture declared at the end.

In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric

The error happens because of you are trying to map a numeric vector to data in geom_errorbar: GVW[1:64,3]. ggplot only works with data.frame.

In general, you shouldn't subset inside ggplot calls. You are doing so because your standard errors are stored in four separate objects. Add them to your original data.frame and you will be able to plot everything in one call.

Here with a dplyr solution to summarise the data and compute the standard error beforehand.

library(dplyr)
d <- GVW %>% group_by(Genotype,variable) %>%
    summarise(mean = mean(value),se = sd(value) / sqrt(n()))

ggplot(d, aes(x = variable, y = mean, fill = Genotype)) + 
  geom_bar(position = position_dodge(), stat = "identity", 
      colour="black", size=.3) +
  geom_errorbar(aes(ymin = mean - se, ymax = mean + se), 
      size=.3, width=.2, position=position_dodge(.9)) +
  xlab("Time") +
  ylab("Weight [g]") +
  scale_fill_hue(name = "Genotype", breaks = c("KO", "WT"), 
      labels = c("Knock-out", "Wild type")) +
  ggtitle("Effect of genotype on weight-gain") +
  scale_y_continuous(breaks = 0:20*4) +
  theme_bw()

variable is not declared it may be inaccessible due to its protection level

This error occurred for me when I mistakenly added a comment following a line continuation character in VB.Net. I removed the comment and the problem went away.

Get Substring between two characters using javascript

Get string between two substrings (contains more than 1 character)

function substrInBetween(whole_str, str1, str2){
   if (whole_str.indexOf(str1) === -1 || whole_str.indexOf(str2) === -1) {
       return undefined; // or ""
  }
  strlength1 = str1.length;
  return whole_str.substring(
                whole_str.indexOf(str1) + strlength1, 
                whole_str.indexOf(str2)
               );

   }

Note I use indexOf() instead of lastIndexOf() so it will check for first occurences of those strings

java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why?

add these dependecies to your .pom file:

<dependency>
  <groupId>org.hsqldb</groupId>
  <artifactId>hsqldb</artifactId>
  <version>2.5.0</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>com.healthmarketscience.jackcess</groupId>
  <artifactId>jackcess-encrypt</artifactId>
  <version>3.0.0</version>
</dependency>

<dependency>
  <groupId>net.sf.ucanaccess</groupId>
  <artifactId>ucanaccess</artifactId>
  <version>5.0.0</version>
</dependency>

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.9</version>
</dependency>

<dependency>
  <groupId>commons-logging</groupId>
  <artifactId>commons-logging</artifactId>
  <version>1.2</version>
</dependency>

and add to your code to call a driver:

Connection conn = DriverManager.getConnection("jdbc:ucanaccess://{file_location}/{accessdb_file_name.mdb};memory=false");

How to add items to a combobox in a form in excel VBA?

Here is another answer:

With DinnerComboBox
.AddItem "Italian"
.AddItem "Chinese"
.AddItem "Frites and Meat"
End With 

Source: Show the

How can I get the named parameters from a URL using Flask?

The URL parameters are available in request.args, which is an ImmutableMultiDict that has a get method, with optional parameters for default value (default) and type (type) - which is a callable that converts the input value to the desired format. (See the documentation of the method for more details.)

from flask import request

@app.route('/my-route')
def my_route():
  page = request.args.get('page', default = 1, type = int)
  filter = request.args.get('filter', default = '*', type = str)

Examples with the code above:

/my-route?page=34               -> page: 34  filter: '*'
/my-route                       -> page:  1  filter: '*'
/my-route?page=10&filter=test   -> page: 10  filter: 'test'
/my-route?page=10&filter=10     -> page: 10  filter: '10'
/my-route?page=*&filter=*       -> page:  1  filter: '*'

Update value of a nested dictionary of varying depth

I made a simple function, in which you give the key, the new value and the dictionary as input, and it recursively updates it with the value:

def update(key,value,dictionary):
    if key in dictionary.keys():
        dictionary[key] = value
        return
    dic_aux = []
    for val_aux in dictionary.values():
        if isinstance(val_aux,dict):
            dic_aux.append(val_aux)
    for i in dic_aux:
        update(key,value,i)
    for [key2,val_aux2] in dictionary.items():
        if isinstance(val_aux2,dict):
            dictionary[key2] = val_aux2

dictionary1={'level1':{'level2':{'levelA':0,'levelB':1}}}
update('levelB',10,dictionary1)
print(dictionary1)

#output: {'level1': {'level2': {'levelA': 0, 'levelB': 10}}}

Hope it answers.

SQL Query with Join, Count and Where

You have to use GROUP BY so you will have multiple records returned,

SELECT  COUNT(*) TotalCount, 
        b.category_id, 
        b.category_name 
FROM    table1 a
        INNER JOIN table2 b
            ON a.category_id = b.category_id 
WHERE   a.colour <> 'red'
GROUP   BY b.category_id, b.category_name

Java: Check if enum contains a given string?

  Set.of(CustomType.values())
     .contains(customTypevalue) 

How to use WebRequest to POST some data and read response?

Below is the code that read the data from the text file and sends it to the handler for processing and receive the response data from the handler and read it and store the data in the string builder class

 //Get the data from text file that needs to be sent.
                FileStream fileStream = new FileStream(@"G:\Papertest.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                byte[] buffer = new byte[fileStream.Length];
                int count = fileStream.Read(buffer, 0, buffer.Length);

                //This is a handler would recieve the data and process it and sends back response.
                WebRequest myWebRequest = WebRequest.Create(@"http://localhost/Provider/ProcessorHandler.ashx");

                myWebRequest.ContentLength = buffer.Length;
                myWebRequest.ContentType = "application/octet-stream";
                myWebRequest.Method = "POST";
                // get the stream object that holds request stream.
                Stream stream = myWebRequest.GetRequestStream();
                       stream.Write(buffer, 0, buffer.Length);
                       stream.Close();

                //Sends a web request and wait for response.
                try
                {
                    WebResponse webResponse = myWebRequest.GetResponse();
                    //get Stream Data from the response
                    Stream respData = webResponse.GetResponseStream();
                    //read the response from stream.
                    StreamReader streamReader = new StreamReader(respData);
                    string name;
                    StringBuilder str = new StringBuilder();
                    while ((name = streamReader.ReadLine()) != null)
                    {
                        str.Append(name); // Add to stringbuider when response contains multple lines data
                   }
                }
                catch (Exception ex)
                {
                    throw ex;
                }

How to call execl() in C with the proper arguments?

If you need just to execute your VLC playback process and only give control back to your application process when it is done and nothing more complex, then i suppose you can use just:

system("The same thing you type into console");

The module ".dll" was loaded but the entry-point was not found

The error indicates that the DLL is either not a COM DLL or it's corrupt. If it's not a COM DLL and not being used as a COM DLL by an application then there is no need to register it.
From what you say in your question (the service is not registered) it seems that we are talking about a service not correctly installed. I will try to reinstall the application.

ASP.NET MVC on IIS 7.5

In my case .NET CRL Version in Application pool prppertires was set to No managed code (do not know why). Setting it to .NET CRL Version v4.0.30319 solved the problem.

Bootstrap carousel multiple frames at once

Can this be done with bootstrap 3's carousel? I'm hoping I won't have to go hunting for yet another jQuery plugin

As of 2013-12-08 the answer is no. The effect you are looking for is not possible using Bootstrap 3's generic carousel plugin. However, here's a simple jQuery plugin that seems to do exactly what you want http://sorgalla.com/jcarousel/

Getting URL hash location, and using it in jQuery

Editor's note: the approach below has serious security implications and, depending upon the version of jQuery you are using, may expose your users to XSS attacks. For more detail, see the discussion of the possible attack in the comments on this answer or this explanation on Security Stack Exchange.

You can use the location.hash property to grab the hash of the current page:

var hash = window.location.hash;
$('ul'+hash+':first').show();

Note that this property already contains the # symbol at the beginning.

Actually you don't need the :first pseudo-selector since you are using the ID selector, is assumed that IDs are unique within the DOM.

In case you want to get the hash from an URL string, you can use the String.substring method:

var url = "http://example.com/file.htm#foo";
var hash = url.substring(url.indexOf('#')); // '#foo'

Advice: Be aware that the user can change the hash as he wants, injecting anything to your selector, you should check the hash before using it.

Best Practices for securing a REST API / web service

There is a great checklist found on Github:

Authentication

  • Don't reinvent the wheel in Authentication, token generation, password storage. Use the standards.

  • Use Max Retry and jail features in Login.

  • Use encryption on all sensitive data.

JWT (JSON Web Token)

  • Use a random complicated key (JWT Secret) to make brute forcing the token very hard.

  • Don't extract the algorithm from the payload. Force the algorithm in the backend (HS256 or RS256).

  • Make token expiration (TTL, RTTL) as short as possible.

  • Don't store sensitive data in the JWT payload, it can be decoded easily.

OAuth

  • Always validate redirect_uri server-side to allow only whitelisted URLs.

  • Always try to exchange for code and not tokens (don't allow response_type=token).

  • Use state parameter with a random hash to prevent CSRF on the OAuth authentication process.

  • Define the default scope, and validate scope parameters for each application.

Access

  • Limit requests (Throttling) to avoid DDoS / brute-force attacks.

  • Use HTTPS on server side to avoid MITM (Man In The Middle Attack)

  • Use HSTS header with SSL to avoid SSL Strip attack.

Input

  • Use the proper HTTP method according to the operation: GET (read), POST (create), PUT/PATCH (replace/update), and DELETE (to delete a record), and respond with 405 Method Not Allowed if the requested method isn't appropriate for the requested resource.

  • Validate content-type on request Accept header (Content Negotiation) to allow only your supported format (e.g. application/xml, application/json, etc) and respond with 406 Not Acceptable response if not matched.

  • Validate content-type of posted data as you accept (e.g. application/x-www-form-urlencoded, multipart/form-data, application/json, etc).

  • Validate User input to avoid common vulnerabilities (e.g. XSS, SQL-Injection, Remote Code Execution, etc).

  • Don't use any sensitive data (credentials, Passwords, security tokens, or API keys) in the URL, but use standard Authorization header.

  • Use an API Gateway service to enable caching, Rate Limit policies (e.g. Quota, Spike Arrest, Concurrent Rate Limit) and deploy APIs resources dynamically.

Processing

  • Check if all the endpoints are protected behind authentication to avoid broken authentication process.

  • User own resource ID should be avoided. Use /me/orders instead of /user/654321/orders.

  • Don't auto-increment IDs. Use UUID instead.

  • If you are parsing XML files, make sure entity parsing is not enabled to avoid XXE (XML external entity attack).

  • If you are parsing XML files, make sure entity expansion is not enabled to avoid Billion Laughs/XML bomb via exponential entity expansion attack.

  • Use a CDN for file uploads.

  • If you are dealing with huge amount of data, use Workers and Queues to process as much as possible in background and return response fast to avoid HTTP Blocking.

  • Do not forget to turn the DEBUG mode OFF.

Output

  • Send X-Content-Type-Options: nosniff header.

  • Send X-Frame-Options: deny header.

  • Send Content-Security-Policy: default-src 'none' header.

  • Remove fingerprinting headers - X-Powered-By, Server, X-AspNet-Version etc.

  • Force content-type for your response, if you return application/json then your response content-type is application/json.

  • Don't return sensitive data like credentials, Passwords, security tokens.

  • Return the proper status code according to the operation completed. (e.g. 200 OK, 400 Bad Request, 401 Unauthorized, 405 Method Not Allowed, etc).

Calculate time difference in minutes in SQL Server

Please try as below to get the time difference in hh:mm:ss format

Select StartTime, EndTime, CAST((EndTime - StartTime) as time(0)) 'TotalTime' from [TableName]

ImportError: Couldn't import Django

if you don't want to deactivate or activate the already installed venv just ensure you have set the pythonpath set

set pythonpath=C:\software\venv\include;C:\software\venv\lib;C:\software\venv\scripts;C:\software\venv\tcl;C:\software\venv\Lib\site-packages;

and then execute

"%pythonpath%" %venvpath%Scripts\mytestsite\manage.py runserver "%ipaddress%":8000

Where to place $PATH variable assertions in zsh?

I had similar problem (in bash terminal command was working correctly but zsh showed command not found error)

Solution:


just paste whatever you were earlier pasting in ~/.bashrc to:

~/.zshrc

How to check if number is divisible by a certain number?

package lecture3;

import java.util.Scanner;

public class divisibleBy2and5 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("Enter an integer number:");
        Scanner input = new Scanner(System.in);
        int x;
        x = input.nextInt();
         if (x % 2==0){
             System.out.println("The integer number you entered is divisible by 2");
         }
         else{
             System.out.println("The integer number you entered is not divisible by 2");
             if(x % 5==0){
                 System.out.println("The integer number you entered is divisible by 5");
             } 
             else{
                 System.out.println("The interger number you entered is not divisible by 5");
             }
        }

    }
}

Vertical align text in block element

DO NOT USE THE 4th solution from top if you are using ag-grid. It will fix the issue for aligning the element in middle but it might break the thing in ag-grid (for me i was not able to select checkbox after some row). Problem is not with the solution or ag-grid but somehow the combination is not good.

DO NOT USE THIS SOLUTION FOR AG-GRID

li a {
    width: 300px;
    height: 100px;
    margin: auto 0;
    display: inline-block;
    vertical-align: middle;
    background: red;  
}

li a:after {
    content:"";
    display: inline-block;
    width: 1px solid transparent;
    height: 100%;
    vertical-align: middle;
}

Explicitly set column value to null SQL Developer

You'll have to write the SQL DML yourself explicitly. i.e.

UPDATE <table>
   SET <column> = NULL;

Once it has completed you'll need to commit your updates

commit;

If you only want to set certain records to NULL use a WHERE clause in your UPDATE statement.

As your original question is pretty vague I hope this covers what you want.

Setting up SSL on a local xampp/apache server

Apache part - enabling you to open https://localhost/xyz

There is the config file xampp/apache/conf/extra/httpd-ssl.conf which contains all the ssl specific configuration. It's fairly well documented, so have a read of the comments and take look at http://httpd.apache.org/docs/2.2/ssl/. The files starts with <IfModule ssl_module>, so it only has an effect if the apache has been started with its mod_ssl module.

Open the file xampp/apache/conf/httpd.conf in an editor and search for the line

#LoadModule ssl_module modules/mod_ssl.so

remove the hashmark, save the file and re-start the apache. The webserver should now start with xampp's basic/default ssl confguration; good enough for testing but you might want to read up a bit more about mod_ssl in the apache documentation.


PHP part - enabling adldap to use ldap over ssl

adldap needs php's openssl extension to use "ldap over ssl" connections. The openssl extension ships as a dll with xampp. You must "tell" php to load this dll, e.g. by having an extension=nameofmodule.dll in your php.ini
Run

echo 'ini: ', get_cfg_var('cfg_file_path');

It should show you which ini file your php installation uses (may differ between the php-apache-module and the php-cli version).
Open this file in an editor and search for

;extension=php_openssl.dll

remove the semicolon, save the file and re-start the apache.

see also: http://docs.php.net/install.windows.extensions

Laravel 5 How to switch from Production mode

Laravel 5 uses .env file to configure your app. .env should not be committed on your repository, like github or bitbucket. On your local environment your .env will look like the following:

# .env
APP_ENV=local

For your production server, you might have the following config:

# .env
APP_ENV=production

AngularJS ui-router login authentication

I Created this module to help make this process piece of cake

You can do things like:

$routeProvider
  .state('secret',
    {
      ...
      permissions: {
        only: ['admin', 'god']
      }
    });

Or also

$routeProvider
  .state('userpanel',
    {
      ...
      permissions: {
        except: ['not-logged-in']
      }
    });

It's brand new but worth checking out!

https://github.com/Narzerus/angular-permission

Decimal number regular expression, where digit after decimal is optional

try this. ^[0-9]\d{0,9}(\.\d{1,3})?%?$ it is tested and worked for me.

Create a unique number with javascript time

let now = new Date();
let timestamp = now.getFullYear().toString();
let month = now.getMonth() + 1;
timestamp += (month < 10 ? '0' : '') + month.toString();
timestamp += (now.getDate() < 10 ? '0' : '') + now.getDate().toString();
timestamp += (now.getHours() < 10 ? '0' : '') + now.getHours().toString();
timestamp += (now.getMinutes() < 10 ? '0' : '') + now.getMinutes().toString();
timestamp += (now.getSeconds() < 10 ? '0' : '') + now.getSeconds().toString();
timestamp += (now.getMilliseconds() < 100 ? '0' : '') + now.getMilliseconds().toString();

What is unit testing and how do you do it?

What is unittesting? It is tricky to define. On a technical level, you build functions that call functions in your codebase and validate the results. Basically, you get a bunch of things like "assert(5+3) == 8", just more complicated (as in DataLayer(MockDatabase()).getUser().name == "Dilbert"). On a tool-view-level, you add an automated, project-specific check if everything still works like you assumed things worked. This is very, very helpful if you refactor and if you implement complicated algorithms. The result generally is a bunch of documentation and a lot less bugs, because the behaviour of the code is pinned down.

I build test cases for all the edge cases and run them similar to the workings of a generational garbage collector. While I implement a class, I only run the test cases that involve the class. Once I am done with working on that class, I run all unittests in order to see if everything still works.

You should test as much as possible, as long as the test code is easy enough to stay untested. Given that, no, not everything is testable in a sane way. Think User interfaces. Think a driver for a space shuttle or a nuclear bomb (at least not with pure JUnit-tests ;) ). However, lots and lots of code is testable. Datastructures are. Algorithms are. Most Applicationlogic-classes are. So test it!

HTH. tetha

ORDER BY using Criteria API

You can add join type as well:

Criteria c2 = c.createCriteria("mother", "mother", CriteriaSpecification.LEFT_JOIN);
Criteria c3 = c2.createCriteria("kind", "kind", CriteriaSpecification.LEFT_JOIN);

Device not detected in Eclipse when connected with USB cable

I solve this problem by updating PC portable device drivers:

Go to : Settings -> Applications -> Development to enable USB debugging

  1. Plug in device USB
  2. Desktop "My Computer" right click -> "Manager"
  3. Choose "Device Manager"
  4. Portable Device
  5. right click on your device -> "Update Driver software" -> Search automatically (wait about 3-5min, )
  6. Done

How do I pull my project from github?

Since you have wiped out your computer and want to checkout your project again, you could start by doing the below initial settings:

git config --global user.name "Your Name"
git config --global user.email [email protected]

Login to your github account, go to the repository you want to clone, and copy the URL under "Clone with HTTPS".

You can clone the remote repository by using HTTPS, even if you had setup SSH the last time:

git clone https://github.com/username/repo-name.git

NOTE:

If you had setup SSH for your remote repository previously, you will have to add that key to the known hosts ssh file on your PC; if you don't and try to do git clone [email protected]:username/repo-name.git, you will see an error similar to the one below:

Cloning into 'repo-name'...
The authenticity of host 'github.com (192.30.255.112)' can't be established.
RSA key fingerprint is SHA256:nThbg6kXDoJWGl7E1IGOCspZomTxdCARLviMw6E5SY8.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'github.com,192.30.255.112' (RSA) to the list of known hosts.
[email protected]: Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Using HTTPS is a easier than SSH in this case.

Can an ASP.NET MVC controller return an Image?

You could use the HttpContext.Response and directly write the content to it (WriteFile() might work for you) and then return ContentResult from your action instead of ActionResult.

Disclaimer: I have not tried this, it's based on looking at the available APIs. :-)

How to get the last characters in a String in Java, regardless of String size

StringUtils.substringAfterLast("abcd: efg: 1006746", ": ") = "1006746";

As long as the format of the string is fixed you can use substringAfterLast.

Loop through the rows of a particular DataTable

Dim row As DataRow
For Each row In dtDataTable.Rows
    Dim strDetail As String
    strDetail = row("Detail")
    Console.WriteLine("Processing Detail {0}", strDetail)
Next row

How to call a function after a div is ready?

inside your <div></div> element you can call the $(document).ready(function(){}); execute a command, something like

<div id="div1">
    <script>
        $(document).ready(function(){
         //do something
        });
    </script>
</div>

and you can do the same to other divs that you have. this was suitable if you loading your div via partial view

Get selected row item in DataGrid WPF

Just discovered this one after i tried Fara's answer but it didn't work on my project. Just drag the column from the Data Sources window, and drop to the Label or TextBox.

Android: How to handle right to left swipe gestures

@Mirek Rusin answeir is very good. But, there is small bug, and fix is requried -

public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;
            try {
                float diffY = e2.getY() - e1.getY();
                float diffX = e2.getX() - e1.getX();
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            if (getOnSwipeListener() != null) {
                                getOnSwipeListener().onSwipeRight();
                            }
                        } else {
                            if (getOnSwipeListener() != null) {
                                getOnSwipeListener().onSwipeLeft();
                            }
                        }
                        result = true;
                    }
                }
                else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffY > 0) {
                        if (getOnSwipeListener() != null) {
                            getOnSwipeListener().onSwipeBottom();
                        }
                    } else {
                        if (getOnSwipeListener() != null) {
                            getOnSwipeListener().onSwipeTop();
                        }
                    }
                    result = true;
                }

What the difference? We set result = true, only if we have checked that all requrinments (both SWIPE_THRESHOLD and SWIPE_VELOCITY_THRESHOLD are Ok ). This is important if we discard swipe if some of requrinments are not achieved, and we have to do smth in onTouchEvent method of OnSwipeTouchListener!

Excel concatenation quotes

Try this:

CONCATENATE(""""; B2 ;"""")

@widor provided a nice solution alternative too - integrated with mine:

CONCATENATE(char(34); B2 ;char(34))

How to Query Database Name in Oracle SQL Developer?

Edit: Whoops, didn't check your question tags before answering.

Check that you can actually connect to DB (have the driver placed? tested the conn when creating it?).

If so, try runnung those queries with F5

How can I remove a specific item from an array?

Underscore.js can be used to solve issues with multiple browsers. It uses in-build browser methods if present. If they are absent like in the case of older Internet Explorer versions it uses its own custom methods.

A simple example to remove elements from array (from the website):

_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); // => [2, 3, 4]

Make Adobe fonts work with CSS3 @font-face in IE9

I was getting the following error:

CSS3114: @font-face failed OpenType embedding permission check. Permission must be Installable.
fontname.ttf

After using the below code my issue got resolved....

src: url('fontname.ttf') format('embedded-opentype')

Thank you guys for helping me!
Cheers,
Renjith.

Multiple cases in switch statement

I think this one is better in C# 7 or above.

switch (value)
{
    case var s when new[] { 1,2 }.Contains(s):
    // Do something
     break;

    default:
    // Do the default
    break;
 }

You can also check Range in C# switch case: Switch case: can I use a range instead of a one number Or if you want to understand basics of C# switch case

WhatsApp API (java/python)

Yowsup provide best solution with example.you can download api from https://github.com/tgalal/yowsup let me know if you have any issue.

Angular.js and HTML5 date input value -- how to get Firefox to show a readable date value in a date input?

Check this fully functional directive for MEAN.JS (Angular.js, bootstrap, Express.js and MongoDb)

Based on @Blackhole ´s response, we just finished it to be used with mongodb and express.

It will allow you to save and load dates from a mongoose connector

Hope it Helps!!

angular.module('myApp')
.directive(
  'dateInput',
  function(dateFilter) {
    return {
      require: 'ngModel',
      template: '<input type="date" class="form-control"></input>',
      replace: true,
      link: function(scope, elm, attrs, ngModelCtrl) {
        ngModelCtrl.$formatters.unshift(function (modelValue) {
          return dateFilter(modelValue, 'yyyy-MM-dd');
        });

        ngModelCtrl.$parsers.push(function(modelValue){
           return angular.toJson(modelValue,true)
          .substring(1,angular.toJson(modelValue).length-1);
        })

      }
    };
  });

The JADE/HTML:

div(date-input, ng-model="modelDate")

SQL Server Express 2008 Install Side-by-side w/ SQL 2005 Express Fails

I'am trying to install SQL SERVER developer 2008 R2 alongside SQL SERVER 2005 EXPRESS,

i went to program features, clicked on unistall SQL SERVER 2005 EXPRESS, and only checked, WORKSTATION COMPONENTS, it unistalled: support files, sql mngmt studio

After that installation of sql 2008 r2 developer went ok....

Hopes this helps somebody

Fully change package name including company domain

I found another solution for renaming a package in the entire project:

Open a file in the package. IntelliJ displays the breadcrumbs of the file, above the opened file. On the package you want renamed: Right click > Refactor > Rename. This renames the package/directory throughout the entire project.

What's your most controversial programming opinion?

Opinion: There should not be any compiler warnings, only errors. Or, formulated differently You should always compile your code with -Werror.

Reason: Either the compiler thinks it is something which should be corrected, in case it should be an error, or it is not necessary to fix, in which case the compiler should just shut up.

Touch move getting stuck Ignored attempt to cancel a touchmove

I had this problem and all I had to do is return true from touchend and the warning went away.

Spring profiles and testing

public class LoginTest extends BaseTest {
    @Test
    public void exampleTest( ){ 
        // Test
    }
}

Inherits from a base test class (this example is testng rather than jUnit, but the ActiveProfiles is the same):

@ContextConfiguration(locations = { "classpath:spring-test-config.xml" })
@ActiveProfiles(resolver = MyActiveProfileResolver.class)
public class BaseTest extends AbstractTestNGSpringContextTests { }

MyActiveProfileResolver can contain any logic required to determine which profile to use:

public class MyActiveProfileResolver implements ActiveProfilesResolver {
    @Override
    public String[] resolve(Class<?> aClass) {
        // This can contain any custom logic to determine which profiles to use
        return new String[] { "exampleProfile" };
    }
}

This sets the profile which is then used to resolve dependencies required by the test.

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

Set HTML dropdown selected option using JSTL

In Servlet do:

String selectedRole = "rat"; // Or "cat" or whatever you'd like.
request.setAttribute("selectedRole", selectedRole);

Then in JSP do:

<select name="roleName">
    <c:forEach items="${roleNames}" var="role">
        <option value="${role}" ${role == selectedRole ? 'selected' : ''}>${role}</option>
    </c:forEach>
</select>

It will print the selected attribute of the HTML <option> element so that you end up like:

<select name="roleName">
    <option value="cat">cat</option>
    <option value="rat" selected>rat</option>
    <option value="unicorn">unicorn</option>
</select>

Apart from the problem: this is not a combo box. This is a dropdown. A combo box is an editable dropdown.