Programs & Examples On #Dynamic pivot

The PIVOT syntax converts row data into columnar data. A dynamic PIVOT is needed when there are an unknown number of row values that need to be converted to columns.

Java Web Service client basic authentication

The JAX-WS way for basic authentication is

Service s = new Service();
Port port = s.getPort();

BindingProvider prov = (BindingProvider)port;
prov.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "myusername");
prov.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "mypassword");;

Best practice for Django project working directory structure

My answer is inspired on my own working experience, and mostly in the book Two Scoops of Django which I highly recommend, and where you can find a more detailed explanation of everything. I just will answer some of the points, and any improvement or correction will be welcomed. But there also can be more correct manners to achieve the same purpose.

I have a main folder in my personal directory where I maintain all the projects where I am working on.

Source Files
I personally use the django project root as repository root of my projects. But in the book is recommended to separate both things. I think that this is a better approach, so I hope to start making the change progressively on my projects.


Git or Mercurial seem to be the most popular version control systems among Django developers. And the most popular hosting services for backups GitHub and Bitbucket.

Virtual Environment
I use virtualenv and virtualenvwrapper. After installing the second one, you need to set up your working directory. Mine is on my /home/envs directory, as it is recommended on virtualenvwrapper installation guide. But I don't think the most important thing is where is it placed. The most important thing when working with virtual environments is keeping requirements.txt file up to date.

pip freeze -l > requirements.txt 

Static Root
Project folder

Media Root
Project folder

Repository root

Repository root

Repository root. This python packages can help you making easier mantaining your documentation:




Specifying onClick event type with Typescript and React.Konva

You're probably out of luck without some hack-y workarounds

You could try

onClick={(event: React.MouseEvent<HTMLElement>) => {
 makeMove(ownMark, ( as any).index)

I'm not sure how strict your linter is - that might shut it up just a little bit

I played around with it for a bit, and couldn't figure it out, but you can also look into writing your own augmented definitions:

edit: please use the implementation in this reply it is the proper way to solve this issue (and also upvote him, while you're at it).

How to create a Java cron job

You can use TimerTask for Cronjobs.

public class Main{
   public static void main(String[] args){

     Timer t = new Timer();
     MyTask mTask = new MyTask();
     // This task is scheduled to run every 10 seconds

     t.scheduleAtFixedRate(mTask, 0, 10000);


class MyTask extends TimerTask{

   public MyTask(){
     //Some stuffs

   public void run() {
     System.out.println("Hi see you after 10 seconds");


Alternative You can also use ScheduledExecutorService.

The meaning of NoInitialContextException error

Specifically, I got this issue when attempting to retrieve the default (no-args) InitialContext within an embedded Tomcat7 instance, in SpringBoot.

The solution for me, was to tell Tomcat to enableNaming.


public TomcatEmbeddedServletContainerFactory tomcatFactory() {
    return new TomcatEmbeddedServletContainerFactory() {
        protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(
                Tomcat tomcat) {
            return super.getTomcatEmbeddedServletContainer(tomcat);

How to combine 2 plots (ggplot) into one plot?

Creating a single combined plot with your current data set up would look something like this

p <- ggplot() +
      # blue plot
      geom_point(data=visual1, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual1, aes(x=ISSUE_DATE, y=COUNTED), fill="blue",
        colour="darkblue", size=1) +
      # red plot
      geom_point(data=visual2, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual2, aes(x=ISSUE_DATE, y=COUNTED), fill="red",
        colour="red", size=1)

however if you could combine the data sets before plotting then ggplot will automatically give you a legend, and in general the code looks a bit cleaner

visual1$group <- 1
visual2$group <- 2

visual12 <- rbind(visual1, visual2)

p <- ggplot(visual12, aes(x=ISSUE_DATE, y=COUNTED, group=group, col=group, fill=group)) +
      geom_point() +

Disable autocomplete via CSS

I solved the problem by adding an fake autocomplete name for all inputs.

$("input").attr("autocomplete", "fake-name-disable-autofill");

Can scripts be inserted with innerHTML?

You can create script and then inject the content.

var g = document.createElement('script');
var s = document.getElementsByTagName('script')[0];
g.text = "alert(\"hi\");"
s.parentNode.insertBefore(g, s);

This works in all browsers :)

Enterprise app deployment doesn't work on iOS 7.1

ingconti is right.

  1. Upload your app.plist to dropbox.
  2. Get shared link of app.plist, like
  3. replace with in the link, like
  4. Remove any parameters on the dropbox shareable link such as "?dl=0t" (as per Carlos Aguirre Tradeco at Enterprise app deployment doesn't work on iOS 7.1 and my own experience).
  5. Create a download.html file with a link formatted as <a href="itms-services://?action=download-manifest&url=">INSTALL!!</a>
  6. Upload your download.html to dropbox
  7. Again, get a shared link of download.html, like, and remove any parameters.
  8. Replace with in the second link as well, like

Now, visit in your device, you can install the app like before.


How to remove outliers from a dataset

I looked up for packages related to removing outliers, and found this package (surprisingly called "outliers"!):
if you go through it you see different ways of removing outliers and among them I found rm.outlier most convenient one to use and as it says in the link above: "If the outlier is detected and confirmed by statistical tests, this function can remove it or replace by sample mean or median" and also here is the usage part from the same source:

rm.outlier(x, fill = FALSE, median = FALSE, opposite = FALSE)

x a dataset, most frequently a vector. If argument is a dataframe, then outlier is removed from each column by sapply. The same behavior is applied by apply when the matrix is given.
fill If set to TRUE, the median or mean is placed instead of outlier. Otherwise, the outlier(s) is/are simply removed.
median If set to TRUE, median is used instead of mean in outlier replacement. opposite if set to TRUE, gives opposite value (if largest value has maximum difference from the mean, it gives smallest and vice versa) "

Diff files present in two different directories

You can use the diff command for that:

diff -bur folder1/ folder2/

This will output a recursive diff that ignore spaces, with a unified context:

  • b flag means ignoring whitespace
  • u flag means a unified context (3 lines before and after)
  • r flag means recursive

Calculating distance between two geographic locations

Look into distanceTo

Returns the approximate distance in meters between this location and the given location. Distance is defined using the WGS84 ellipsoid.

or distanceBetween

Computes the approximate distance in meters between two locations, and optionally the initial and final bearings of the shortest path between them. Distance and bearing are defined using the WGS84 ellipsoid.

You can create a Location object from a latitude and longitude:

Location locationA = new Location("point A");


Location locationB = new Location("point B");


float distance = locationA.distanceTo(locationB);


private double meterDistanceBetweenPoints(float lat_a, float lng_a, float lat_b, float lng_b) {
    float pk = (float) (180.f/Math.PI);

    float a1 = lat_a / pk;
    float a2 = lng_a / pk;
    float b1 = lat_b / pk;
    float b2 = lng_b / pk;

    double t1 = Math.cos(a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2);
    double t2 = Math.cos(a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2);
    double t3 = Math.sin(a1) * Math.sin(b1);
    double tt = Math.acos(t1 + t2 + t3);
    return 6366000 * tt;

How can I issue a single command from the command line through sql plus?

sqlplus user/password@sid < sqlfile.sql

This will also work from the DOS command line. In this case the file sqlfile.sql contains the SQL you wish to execute.

Convert milliseconds to date (in Excel)

Converting your value in milliseconds to days is simply (MsValue / 86,400,000)

We can get 1/1/1970 as numeric value by DATE(1970,1,1)

= (MsValueCellReference / 86400000) + DATE(1970,1,1)

Using your value of 1271664970687 and formatting it as dd/mm/yyyy hh:mm:ss gives me a date and time of 19/04/2010 08:16:11

Substring with reverse index

var str = "xxx_456";
var str_sub = str.substr(str.lastIndexOf("_")+1);

If it is not always three digits at the end (and seperated by an underscore). If the end delimiter is not always an underscore, then you could use regex:

var pat = /([0-9]{1,})$/;
var m = str.match(pat);

Code for printf function in C

Here's the GNU version of printf... you can see it passing in stdout to vfprintf:

__printf (const char *format, ...)
   va_list arg;
   int done;

   va_start (arg, format);
   done = vfprintf (stdout, format, arg);
   va_end (arg);

   return done;

See here.

Here's a link to vfprintf... all the formatting 'magic' happens here.

The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)

Determine a string's encoding in C#

Check out Utf8Checker it is simple class that does exactly this in pure managed code.

Notice: as already pointed out "determine encoding" makes sense only for byte streams. If you have a string it is already encoded from someone along the way who already knew or guessed the encoding to get the string in the first place.

How to detect Windows 64-bit platform with .NET?

Quickest way:

if(IntPtr.Size == 8) {
    // 64 bit machine
} else if(IntPtr.Size == 4)  {
    // 32 bit machine

Note: this is very direct and works correctly on 64-bit only if the program does not force execution as a 32-bit process (e.g. through <Prefer32Bit>true</Prefer32Bit> in the project settings).

How do I find an element that contains specific text in Selenium WebDriver (Python)?

You could try an XPath expression like:

'//div[contains(text(), "{0}") and @class="inner"]'.format(text)

CSS: how to get scrollbars for div inside container of fixed height

setting the overflow should take care of it, but you need to set the height of Content also. If the height attribute is not set, the div will grow vertically as tall as it needs to, and scrollbars wont be needed.

See Example:

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

Responding because this answer came up first for search when I was having the same issue:

[08S01][unixODBC][FreeTDS][SQL Server]Unable to connect: Adaptive Server is unavailable or does not exist

MSSQL named instances have to be configured properly without setting the port. (documentation on the freetds config says set instance or port NOT BOTH)


host =
instance = instance_name
#port = port is found automatically, don't define explicitly
tds version = 8.0
client charset = UTF-8

And in odbc.ini just because you can set Port, DON'T when you are using a named instance.

How to style HTML5 range input to have different color before and after slider?

While the accepted answer is good in theory, it ignores the fact that the thumb then cannot be bigger than size of the track without being chopped off by the overflow: hidden. See this example of how to handle this with just a tiny bit of JS.

// .chrome styling Vanilla JS

document.getElementById("myinput").oninput = function() {
  var value = (this.value-this.min)/(this.max-this.min)*100 = 'linear-gradient(to right, #82CFD0 0%, #82CFD0 ' + value + '%, #fff ' + value + '%, white 100%)'
#myinput {
  background: linear-gradient(to right, #82CFD0 0%, #82CFD0 50%, #fff 50%, #fff 100%);
  border: solid 1px #82CFD0;
  border-radius: 8px;
  height: 7px;
  width: 356px;
  outline: none;
  transition: background 450ms ease-in;
  -webkit-appearance: none;
<div class="chrome">
  <input id="myinput" min="0" max="60" type="range" value="30" />

Use a cell value in VBA function with a variable

No need to activate or selection sheets or cells if you're using VBA. You can access it all directly. The code:

Dim rng As Range
For Each rng In Sheets("Feuil2").Range("A1:A333")
    Sheets("Classeur2.csv").Cells(rng.Value, rng.Offset(, 1).Value) = "1"
Next rng

is producing the same result as Joe's code.

If you need to switch sheets for some reasons, use Application.ScreenUpdating = False at the beginning of your macro (and Application.ScreenUpdating=True at the end). This will remove the screenflickering - and speed up the execution.

SQL Row_Number() function in Where Clause

Using CTE (SQL Server 2005+):

WITH employee_rows AS (
  SELECT t.employee_id,
         ROW_NUMBER() OVER ( ORDER BY t.employee_id ) 'rownum'
SELECT er.employee_id
  FROM employee_rows er
 WHERE er.rownum > 1

Using Inline view/Non-CTE Equivalent Alternative:

SELECT er.employee_id
  FROM (SELECT t.employee_id,
               ROW_NUMBER() OVER ( ORDER BY t.employee_id ) 'rownum'
          FROM V_EMPLOYEE t) er
 WHERE er.rownum > 1

Using NotNull Annotation in method argument

@Nullable and @NotNull do nothing on their own. They are supposed to act as Documentation tools.

The @Nullable Annotation reminds you about the necessity to introduce an NPE check when:

  1. Calling methods that can return null.
  2. Dereferencing variables (fields, local variables, parameters) that can be null.

The @NotNull Annotation is, actually, an explicit contract declaring the following:

  1. A method should not return null.
  2. A variable (like fields, local variables, and parameters) cannot should not hold null value.

For example, instead of writing:

 * @param aX should not be null
public void setX(final Object aX ) {
    // some code

You can use:

public void setX(@NotNull final Object aX ) {
    // some code

Additionally, @NotNull is often checked by ConstraintValidators (eg. in spring and hibernate).

The @NotNull annotation doesn't do any validation on its own because the annotation definition does not provide any ConstraintValidator type reference.

For more info see:

  1. Bean validation

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

What worked for me, is registering it on the Page while specifying the type as that of the UpdatePanel, like so:

ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel) Guid.NewGuid().ToString(), myScript, true);

bootstrap responsive table content wrapping

Add your new class "tableresp" with table-responisve class and then add below code in your js file

$(".tableresp").on('click', '.dropdown-toggle', function(event) {

    if ($('.dropdown-menu').length) {
        var elm = $('.dropdown-menu'),
            docHeight = $(document).height(),
            docWidth = $(document).width(),
            btn_offset = $(this).offset(),
            btn_width = $(this).outerWidth(),
            btn_height = $(this).outerHeight(),
            elm_width = elm.outerWidth(),
            elm_height = elm.outerHeight(),
            table_offset = $(".tableresp").offset(),
            table_width = $(".tableresp").width(),
            table_height = $(".tableresp").height(),

            tableoffright = table_width + table_offset.left,
            tableoffbottom = table_height +,
            rem_tablewidth = docWidth - tableoffright,
            rem_tableheight = docHeight - tableoffbottom,
            elm_offsetleft = btn_offset.left,
            elm_offsetright = btn_offset.left + btn_width,
            elm_offsettop = + btn_height,
            btn_offsetbottom = elm_offsettop,

            left_edge = (elm_offsetleft - table_offset.left) < elm_width,
            top_edge = < elm_height,
            right_edge = (table_width - elm_offsetleft) < elm_width,
            bottom_edge = (tableoffbottom - btn_offsetbottom) < elm_height;

        console.log((tableoffbottom - btn_offsetbottom) + "|| " + elm_height);

        var table_offset_bottom = docHeight - ( + table_height);

        var touchTableBottom = ( + btn_height + (elm_height * 2)) -;

        var bottomedge = touchTableBottom > table_offset_bottom;

        if (left_edge) {
        } else {
        if (bottom_edge) {
        } else {

var table_smallheight = $('.tableresp'),
    positioning = table_smallheight.parent();

if (table_smallheight.height() < 320) {
    $('.tableresp .dropdown,.tableresp .adropup').css('position', 'static');

} else {
    $('.tableresp .dropdown,.tableresp .dropup').css('position', 'relative');


How to make VS Code to treat other file extensions as certain language?

This works for me.

enter image description here

"files.associations": {"*.bitesize": "yaml"}

Chart.js v2 hide dataset labels

Replace options with this snippet, will fix for Vanilla JavaScript Developers

options: {
            title: {
                text: 'Hello',
                display: true
            scales: {
                xAxes: [{
                    ticks: {
                        display: false
            legend: {
                display: false

regex error - nothing to repeat

regular expression normally uses * and + in theory of language. I encounter the same bug while executing the line code


to solve it, it needs to include \ before * and +


MySQL add days to a date


will give the Date after adjusting the INTERVAL


DATE_ADD(NOW(), INTERVAL -1 DAY) for deducting 1 DAY from current Day
DATE_ADD(NOW(), INTERVAL 2 DAY)  for adding 2 Days

You can use like

UPDATE classes WHERE date=(DATE_ADD(date, INTERVAL 1 DAY)) WHERE id=161

What does ECU units, CPU core and memory mean when I launch a instance

ECU = EC2 Compute Unit. More from here:

Amazon EC2 uses a variety of measures to provide each instance with a consistent and predictable amount of CPU capacity. In order to make it easy for developers to compare CPU capacity between different instance types, we have defined an Amazon EC2 Compute Unit. The amount of CPU that is allocated to a particular instance is expressed in terms of these EC2 Compute Units. We use several benchmarks and tests to manage the consistency and predictability of the performance from an EC2 Compute Unit. One EC2 Compute Unit provides the equivalent CPU capacity of a 1.0-1.2 GHz 2007 Opteron or 2007 Xeon processor. This is also the equivalent to an early-2006 1.7 GHz Xeon processor referenced in our original documentation. Over time, we may add or substitute measures that go into the definition of an EC2 Compute Unit, if we find metrics that will give you a clearer picture of compute capacity.

how can I copy a conditional formatting in Excel 2010 to other cells, which is based on a other cells content?

I, too, have need for this! My situation involves comparing actuals with budget for cost centers, where expenses may have been mis-applied and therefore need to be re-allocated to the correct cost center so as to match how they were budgeted. It is very time consuming to try and scan row-by-row to see if each expense item has been correctly allocated. I decided that I should apply conditional formatting to highlight any cells where the actuals did not match the budget. I set up the conditional formatting to change the background color if the actual amount under the cost center did not match the budgeted amount.

Here's what I did:

Start in cell A1 (or the first cell you want to have the formatting). Open the Conditional Formatting dialogue box and select Apply formatting based on a formula. Then, I wrote a formula to compare one cell to another to see if they match:


If the contents of cells A1 and A50 are equal, the conditional formatting will be applied. NOTICE: no $$, so the cell references are RELATIVE! Therefore, you can copy the formula from cell A1 and PasteSpecial (format). If you only click on the cells that you reference as you write your conditional formatting formula, the cells are by default locked, so then you wouldn't be able to apply them anywhere else (you would have to write out a new rule for each line- YUK!)

What is really cool about this is that if you insert rows under the conditionally formatted cell, the conditional formatting will be applied to the inserted rows as well!

Something else you could also do with this: Use ISBLANK if the amounts are not going to be exact matches, but you want to see if there are expenses showing up in columns where there are no budgeted amounts (i.e., BLANK) .

This has been a real time-saver for me. Give it a try and enjoy!

Jquery Ajax, return success/error from controller

When you return value from server to jQuery's Ajax call you can also use the below code to indicate a server error:

return StatusCode(500, "My error");


return StatusCode((int)HttpStatusCode.InternalServerError, "My error");


Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new { responseText = "my error" });

Codes other than Http Success codes (e.g. 200[OK]) will trigger the function in front of error: in client side (ajax).

you can have ajax call like:

        type: "POST",
        url: "/General/ContactRequestPartial",
        data: {
            HashId: id
       success: function (response)  {
            console.log("Custom message : " + response.responseText);
        }, //Is Called when Status Code is 200[OK] or other Http success code
        error: function (jqXHR, textStatus, errorThrown)  {
            console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
        }, //Is Called when Status Code is 500[InternalServerError] or other Http Error code

Additionally you can handle different HTTP errors from jQuery side like:

        type: "POST",
        url: "/General/ContactRequestPartial",
        data: {
            HashId: id
        statusCode: {
            500: function (jqXHR, textStatus, errorThrown)  {
                console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
            501: function (jqXHR, textStatus, errorThrown)  {
                console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);

statusCode: is useful when you want to call different functions for different status codes that you return from server.

You can see list of different Http Status codes here:Wikipedia

Additional resources:

  1. Returning Server-Side Errors from AJAX Calls
  2. Returning a JsonResult within the Error function of JQuery Ajax
  3. Handling Ajax errors with jQuery

Read XLSX file in Java

I'm not very happy with any of the options so I ended up requesting the file in Excel 97 formate. The POI works great for that. Thanks everyone for the help.

How to add a where clause in a MySQL Insert statement?

INSERT INTO users (id,username, password) 
VALUES ('1','Jack','123')
ON DUPLICATE KEY UPDATE username='Jack',password='123'

This will work only if the id field is unique/pk (not composite PK though) Also, this will insert if no id of value 1 is found and update otherwise the record with id 1 if it does exists.

How to insert new cell into UITableView in Swift

For Swift 5

Remove Cell

    let indexPath = [NSIndexPath(row: yourArray-1, section: 0)]
    yourArray.remove(at: buttonTag)

    self.tableView.deleteRows(at: indexPath as [IndexPath] , with: .fade)
    self.tableView.reloadData()// Not mendatory, But In my case its requires

Add new cell


    tableView.insertRows(at: [
        (NSIndexPath(row: yourArray.count-1, section: 0) as IndexPath)], with: .automatic)

how to rotate a bitmap 90 degrees

In case your goal is to have a rotated image in an imageView or file you can use Exif to achieve that. The support library now offers that:

Below is its usage but to achieve your goal you have to check the library api documentation for that. I just wanted to give a hint that rotating the bitmap isn't always the best way.

Uri uri; // the URI you've received from the other app
InputStream in;
try {
  in = getContentResolver().openInputStream(uri);
  ExifInterface exifInterface = new ExifInterface(in);
  // Now you can extract any Exif tag you want
  // Assuming the image is a JPEG or supported raw format
} catch (IOException e) {
  // Handle any errors
} finally {
  if (in != null) {
    try {
    } catch (IOException ignored) {}

int rotation = 0;
int orientation = exifInterface.getAttributeInt(
switch (orientation) {
  case ExifInterface.ORIENTATION_ROTATE_90:
    rotation = 90;
  case ExifInterface.ORIENTATION_ROTATE_180:
    rotation = 180;
  case ExifInterface.ORIENTATION_ROTATE_270:
    rotation = 270;


compile ""

Automatically set appsettings.json for dev and release environments in core?

In ASP.NET Core you should rather use Environment Variables instead of build configuration for proper appsettings.json

  1. Right click on you project > Properties > Debug > Environment Variables

    environment variables

  2. ASP.NET Core will use the appropriate appsettings.json file:

    example of appsettings files in solution explorer

  3. Now you can use that Environment Variable like this:

    public Startup(IHostingEnvironment env)
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        Configuration = builder.Build();

Note: If you use @Dmitry's answer, you can run into problems eg. when overriding appsettings.json values on Azure.

How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?

You need to use a global regular expression for this. Try it this way:

str.replace(/"/g, '\\"');

Check out regex syntax and options for the replace function in Using Regular Expressions with JavaScript.

How do you roll back (reset) a Git repository to a particular commit?

When you say the 'GUI Tool', I assume you're using Git For Windows.

IMPORTANT, I would highly recommend creating a new branch to do this on if you haven't already. That way your master can remain the same while you test out your changes.

With the GUI you need to 'roll back this commit' like you have with the history on the right of your view. Then you will notice you have all the unwanted files as changes to commit on the left. Now you need to right click on the grey title above all the uncommited files and select 'disregard changes'. This will set your files back to how they were in this version.

Converting byte array to String (Java)

I suggest Arrays.toString(byte_array);

It depends on your purpose. For example, I wanted to save a byte array exactly like the format you can see at time of debug that is something like this : [1, 2, 3] If you want to save exactly same value without converting the bytes to character format, Arrays.toString (byte_array) does this,. But if you want to save characters instead of bytes, you should use String s = new String(byte_array). In this case, s is equal to equivalent of [1, 2, 3] in format of character.

xlrd.biffh.XLRDError: Excel xlsx file; not supported

The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:

pip install xlrd==1.2.0

Does adding a duplicate value to a HashSet/HashMap replace the previous value

HashMap basically contains Entry which subsequently contains Key(Object) and Value(Object).Internally HashSet are HashMap and HashMap do replace values as some of you already pointed..but does it really replaces the keys???No ..and that is the trick here. HashMap keeps its value as key in the underlying HashMap and value is just a dummy object.So if u try to reinsert same Value in HashMap(Key in underlying Map).It just replaces the dummy value and not the Key(Value for HashSet).

Look at the below code for HashSet Class:

public boolean  [More ...] add(E e) {

   return map.put(e, PRESENT)==null;

Here e is the value for HashSet but key for underlying map.and key is never replaced. Hope i am able to clear the confusion.

CSS: How to change colour of active navigation page menu

I think you are getting confused about what the a:active CSS selector does. This will only change the colour of your link when you click it (and only for the duration of the click i.e. how long your mouse button stays down). What you need to do is introduce a new class e.g. .selected into your CSS and when you select a link, update the selected menu item with new class e.g.

<div class="menuBar">
        <li class="selected"><a href="index.php">HOME</a></li>
        <li><a href="two.php">PORTFOLIO</a></li>

// specific CSS for your menu
div.menuBar li.selected a { color: #FF0000; } 
// more general CSS
li.selected a { color: #FF0000; }

You will need to update your template page to take in a selectedPage parameter.

How can I get a file's size in C++?

If you're on Linux, seriously consider just using the g_file_get_contents function from glib. It handles all the code for loading a file, allocating memory, and handling errors.

Iterating through a golang map

You could just write it out in multiline like this,

$ cat dict.go
package main

import "fmt"

func main() {
        items := map[string]interface{}{
                "foo": map[string]int{
                        "strength": 10,
                        "age": 2000,
                "bar": map[string]int{
                        "strength": 20,
                        "age": 1000,
        for key, value := range items {
                fmt.Println("[", key, "] has items:")
                for k,v := range value.(map[string]int) {
                        fmt.Println("\t-->", k, ":", v)


And the output:

$ go run dict.go
[ foo ] has items:
        --> strength : 10
        --> age : 2000
[ bar ] has items:
        --> strength : 20
        --> age : 1000

Preventing SQL injection in Node.js

Mysql-native has been outdated so it became MySQL2 that is a new module created with the help of the original MySQL module's team. This module has more features and I think it has what you want as it has prepared statements(by using.execute()) like in PHP for more security.

It's also very active(the last change was from 2-1 days) I didn't try it before but I think it's what you want and more.

Is there any advantage of using map over unordered_map in case of trivial keys?

If you want to compare the speed of your std::map and std::unordered_map implementations, you could use Google's sparsehash project which has a time_hash_map program to time them. For example, with gcc 4.4.2 on an x86_64 Linux system

$ ./time_hash_map
TR1 UNORDERED_MAP (4 byte objects, 10000000 iterations):
map_grow              126.1 ns  (27427396 hashes, 40000000 copies)  290.9 MB
map_predict/grow       67.4 ns  (10000000 hashes, 40000000 copies)  232.8 MB
map_replace            22.3 ns  (37427396 hashes, 40000000 copies)
map_fetch              16.3 ns  (37427396 hashes, 40000000 copies)
map_fetch_empty         9.8 ns  (10000000 hashes,        0 copies)
map_remove             49.1 ns  (37427396 hashes, 40000000 copies)
map_toggle             86.1 ns  (20000000 hashes, 40000000 copies)

STANDARD MAP (4 byte objects, 10000000 iterations):
map_grow              225.3 ns  (       0 hashes, 20000000 copies)  462.4 MB
map_predict/grow      225.1 ns  (       0 hashes, 20000000 copies)  462.6 MB
map_replace           151.2 ns  (       0 hashes, 20000000 copies)
map_fetch             156.0 ns  (       0 hashes, 20000000 copies)
map_fetch_empty         1.4 ns  (       0 hashes,        0 copies)
map_remove            141.0 ns  (       0 hashes, 20000000 copies)
map_toggle             67.3 ns  (       0 hashes, 20000000 copies)

Replace a value in a data frame based on a conditional (`if`) statement

another useful way to replace values

junk$nm <- revalue(junk$nm, c("B"="b"))

Clicking the back button twice to exit an activity

This is the same of the accepted and most voted response but this snipped used Snackbar instead of Toast.

boolean doubleBackToExitPressedOnce = false;

    public void onBackPressed() {
        if (doubleBackToExitPressedOnce) {

        this.doubleBackToExitPressedOnce = true;
        Snackbar.make(content, "Please click BACK again to exit", Snackbar.LENGTH_SHORT)
                .setAction("Action", null).show();

        new Handler().postDelayed(new Runnable() {

            public void run() {
        }, 2000);

What is event bubbling and capturing?

There's also the Event.eventPhase property which can tell you if the event is at target or comes from somewhere else, and it is fully supported by browsers.

Expanding on the already great snippet from the accepted answer, this is the output using the eventPhase property

var logElement = document.getElementById('log');

function log(msg) {
  if (logElement.innerHTML == "<p>No logs</p>")
    logElement.innerHTML = "";
  logElement.innerHTML += ('<p>' + msg + '</p>');

function humanizeEvent(eventPhase){
    case 1: //Event.CAPTURING_PHASE
      return "Event is being propagated through the target's ancestor objects";
    case 2: //Event.AT_TARGET
      return "The event has arrived at the event's target";
    case 3: //Event.BUBBLING_PHASE
      return "The event is propagating back up through the target's ancestors in reverse order";
function capture(e) {
  log('capture: ' + this.firstChild.nodeValue.trim() + "; " + 

function bubble(e) {
  log('bubble: ' + this.firstChild.nodeValue.trim() + "; " + 

var divs = document.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
  divs[i].addEventListener('click', capture, true);
  divs[i].addEventListener('click', bubble, false);
p {
  line-height: 0;

div {
  padding: 5px;

  background: #fff;
  border: 1px solid #aaa;
  cursor: pointer;

div:hover {
  border: 1px solid #faa;
  background: #fdd;
<button onclick="document.getElementById('log').innerHTML = '<p>No logs</p>';">Clear logs</button>
<section id="log"></section>

What is the difference between SQL and MySQL?

SQL - Structured Query Language. It is declarative computer language aimed at querying relational databases.

MySQL is a relational database - a piece of software optimized for data storage and retrieval. There are many such databases - Oracle, Microsoft SQL Server, SQLite and many others are examples of such.

How to auto resize and adjust Form controls with change in resolution

Use combinations of these to get the desired result:

  1. Set Anchor property to None, the controls will not be resized, they only shift their position.

  2. Set Anchor property to Top+Bottom+Left+Right, the controls will be resized but they don't change their position.

  3. Set the Minimum Size of the form to a proper value.

  4. Set Dock property.

  5. Use Form Resize event to change whatever you want

I don't know how font size (label, textbox, combobox, etc.) will be affected in (1) - (4), but it can be controlled in (5).

msvcr110.dll is missing from computer error while installing PHP

Since link to this question shows up on very top of returned results when you search for "php MSVCR110.dll" (not to mention it got 100k+ views and growing), here're some additional notes that you may find handy in your quest to solve MSVCR110.dll mistery...

The approach described in the answer is valid not only for MSVCR110.dll case but also applies when you are looking for other versions, like newer MSVCR71.dll and I updated the answer to include VC15 even it's beyond scope of the original question.

On you can read:

VC9, VC11 and VC15

More recent versions of PHP are built with VC9, VC11 or VC15 (Visual Studio 2008, 2012 or 2015 compiler respectively) and include improvements in performance and stability.

The VC9 builds require you to have the Visual C++ Redistributable for Visual Studio 2008 SP1 x86 or x64 installed.

The VC11 builds require to have the Visual C++ Redistributable for Visual Studio 2012 x86 or x64 installed.

The VC15 builds require to have the Visual C++ Redistributable for Visual Studio 2015 x86 or x64 installed.

This is quite crucial as you not only need to get Visual C++ Redistributable installed but you also need the right version of it, and which one is right and correct, depends on what PHP build you are actually going to use. Pay attention to what version of PHP for Windows you are fetching, especially pay attention to this "VCxx" suffix, because if you install PHP that requires VC9 while having redistributables VC11 installed it is not going to work as run-time dependency is simply not fulfilled. Contrary to what some may think, you need exactly the version required, as newer (higher) releases does NOT cover older (lower) versions. so i.e. VC11 is not providing VC9 compatibility. Also VC15 is neither fulfilling VC11 nor VC9 dependency. It is just VC15 and NOTHING ELSE. Deal with it :)

For example, archive name php-5.6.4-nts-Win32-VC11-x86 tells us the following

enter image description here

  1. it provides PHP v5.6.4,
  2. PHP build is Non-Thread Safe (nts),
  3. it provides binaries for Windows (Win32),
  4. to run, Visual Studio 2012 redistributable (VC11) is required,
  5. binaries are 32-bit (x86),

Most searches I did lead to VC9 of redistributables, so in case of constant failures to make thing works, if possible, try installing different PHP build, to see if you by any chance do not face mismatching versions.

Download links

Note that you are using 32-bit version of PHP, so you need 32-bit redistributable (x86) even if your version of Windows is 64-bit!

  • VC9: Visual C++ Redistributable for Visual Studio 2008: x86 or x64
  • VC11: Visual C++ Redistributable for Visual Studio 2012: x86 or x64
  • VC15: Visual C++ Redistributable for Visual Studio 2015: x86 or x64
  • VC17: Visual C++ Redistributable for Visual Studio 2017: x86 or x64

How can I know if Object is String type object?

Either use instanceof or method Class.isAssignableFrom(Class<?> cls).

how to prevent adding duplicate keys to a javascript array

The logic is wrong. Consider this:

x = ["a","b","c"]
x[0]     // "a"
x["0"]   // "a"
0 in x   // true
"0" in x // true
x.hasOwnProperty(0)   // true
x.hasOwnProperty("0") // true

There is no reason to loop to check for key (or indices for arrays) existence. Now, values are a different story...

Happy coding

SELECT with a Replace()

To expand on Oded's answer, your conceptual model needs a slight adjustment here. Aliasing of column names (AS clauses in the SELECT list) happens very late in the processing of a SELECT, which is why alias names are not available to WHERE clauses. In fact, the only thing that happens after column aliasing is sorting, which is why (to quote the docs on SELECT):

column_alias can be used in an ORDER BY clause. However, it cannot be used in a WHERE, GROUP BY, or HAVING clause.

If you have a convoluted expression in the SELECT list, you may be worried about it 'being evaluated twice' when it appears in the SELECT list and (say) a WHERE clause - however, the query engine is clever enough to work out what's going on. If you want to avoid having the expression appear twice in your query, you can do something like

SELECT c1, c2, c3, expr1
    ( SELECT c1, c2, c3, some_complicated_expression AS expr1 ) inner
WHERE expr1 = condition

which avoids some_complicated_expression physically appearing twice.

How to prettyprint a JSON file?

Here's a simple example of pretty printing JSON to the console in a nice way in Python, without requiring the JSON to be on your computer as a local file:

import pprint
import json 
from urllib.request import urlopen # (Only used to get this example)

# Getting a JSON example for this example 
r = urlopen("")
text = 

# To print it

How to create EditText with rounded corners?

Try this one,

  1. Create rounded_edittext.xml file in your Drawable

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android=""
        android:shape="rectangle" android:padding="15dp">
        <solid android:color="#FFFFFF" />
            android:topRightRadius="0dp" />
        <stroke android:width="1dip" android:color="#f06060" />
  2. Apply background for your EditText in xml file

        android:inputType="text" />  
  3. You will get output like this

enter image description here

What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

Collections.synchronizedMap() method synchronizes all the methods of the HashMap and effectively reduces it to a data structure where one thread can enter at a time because it locks every method on a common lock.

In ConcurrentHashMap synchronization is done a little differently. Rather than locking every method on a common lock, ConcurrentHashMap uses separate lock for separate buckets thus locking only a portion of the Map. By default there are 16 buckets and also separate locks for separate buckets. So the default concurrency level is 16. That means theoretically any given time 16 threads can access ConcurrentHashMap if they all are going to separate buckets.

How to refresh a Page using react-route Link

I ended up keeping Link and adding the reload to the Link's onClick event with a timeout like this:

function refreshPage() {
    }, 500);
    console.log('page to reload')

<Link to={{pathname:"/"}} onClick={refreshPage}>Home</Link>

without the timeout, the refresh function would run first

Find index of a value in an array

For arrays you can use: Array.FindIndex<T>:

int keyIndex = Array.FindIndex(words, w => w.IsKey);

For lists you can use List<T>.FindIndex:

int keyIndex = words.FindIndex(w => w.IsKey);

You can also write a generic extension method that works for any Enumerable<T>:

///<summary>Finds the index of the first item matching an expression in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="predicate">The expression to test the items against.</param>
///<returns>The index of the first matching item, or -1 if no items match.</returns>
public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate) {
    if (items == null) throw new ArgumentNullException("items");
    if (predicate == null) throw new ArgumentNullException("predicate");

    int retVal = 0;
    foreach (var item in items) {
        if (predicate(item)) return retVal;
    return -1;

And you can use LINQ as well:

int keyIndex = words
    .Select((v, i) => new {Word = v, Index = i})
    .FirstOrDefault(x => x.Word.IsKey)?.Index ?? -1;

Passing data to a bootstrap modal

I think you can make this work using jQuery's .on event handler.

Here's a fiddle you can test; just make sure to expand the HTML frame in the fiddle as much as possible so you can view the modal.


<p>Link 1</p>
<a data-toggle="modal" data-id="ISBN564541" title="Add this item" class="open-AddBookDialog btn btn-primary" href="#addBookDialog">test</a>


<p>Link 2</p>
<a data-toggle="modal" data-id="ISBN-001122" title="Add this item" class="open-AddBookDialog btn btn-primary" href="#addBookDialog">test</a>

<div class="modal hide" id="addBookDialog">
 <div class="modal-header">
    <button class="close" data-dismiss="modal">×</button>
    <h3>Modal header</h3>
    <div class="modal-body">
        <p>some content</p>
        <input type="text" name="bookId" id="bookId" value=""/>


$(document).on("click", ".open-AddBookDialog", function () {
     var myBookId = $(this).data('id');
     $(".modal-body #bookId").val( myBookId );
     // As pointed out in comments, 
     // it is unnecessary to have to manually call the modal.
     // $('#addBookDialog').modal('show');

How do I get the last day of a month?

From DateTimePicker:

First date:

DateTime first_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, 1);

Last date:

DateTime last_date = new DateTime(DateTimePicker.Value.Year, DateTimePicker.Value.Month, DateTime.DaysInMonth(DateTimePicker.Value.Year, DateTimePicker.Value.Month));

SQL Server: What is the difference between CROSS JOIN and FULL OUTER JOIN?

A full outer join combines a left outer join and a right outer join. The result set returns rows from both tables where the conditions are met but returns null columns where there is no match.

A cross join is a Cartesian product that does not require any condition to join tables. The result set contains rows and columns that are a multiplication of both tables.

Android Drawing Separator/Divider Line in Layout?

Just write this :


full example:




What is the difference between signed and unsigned variables?

unsigned is used when ur value must be positive, no negative value here, if signed for int range -32768 to +32767 if unsigned for int range 0 to 65535

Subtracting time.Duration from time in Go

You can negate a time.Duration:

then := now.Add(- dur)

You can even compare a time.Duration against 0:

if dur > 0 {
    dur = - dur

then := now.Add(dur)

You can see a working example at

ORA-01950: no privileges on tablespace 'USERS'

You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run

ALTER USER <user> quota unlimited on <tablespace name>;


ALTER USER <user> quota 100M on <tablespace name>;

as a DBA user (depending on how much space you need / want to grant).

How can I find the maximum value and its index in array in MATLAB?

This will return the maximum value in a matrix


This will return the row and the column of that value


For minimum just swap the word max with min and that's all.

How to Find the Default Charset/Encoding in Java?



it seems to be the same encoding as the one used in your system's command line.

Where are include files stored - Ubuntu Linux, GCC

See here: Search Path


#include <stdio.h>

When the include file is in brackets the preprocessor first searches in paths specified via the -I flag. Then it searches the standard include paths (see the above link, and use the -v flag to test on your system).

#include "myFile.h"

When the include file is in quotes the preprocessor first searches in the current directory, then paths specified by -iquote, then -I paths, then the standard paths.

-nostdinc can be used to prevent the preprocessor from searching the standard paths at all.

Environment variables can also be used to add search paths.

When compiling if you use the -v flag you can see the search paths used.

How to merge lists into a list of tuples?

The output which you showed in problem statement is not the tuple but list

list_c = [(1,5), (2,6), (3,7), (4,8)]

check for


considering you want the result as tuple out of list_a and list_b, do


Android emulator: How to monitor network traffic?

A current release of Android Studio did not correctly apply the -tcpdump argument. I was still able to capture a dump by passing the related parameter to qemu as follows:

tools/emulator -engine classic -tcpdump dump.cap -avd myAvd

Why does JPA have a @Transient annotation?

In laymen's terms, if you use the @Transient annotation on an attribute of an entity: this attribute will be singled out and will not be saved to the database. The rest of the attribute of the object within the entity will still be saved.


Im saving the Object to the database using the jpa repository built in save method as so:;

Auto generate function documentation in Visual Studio

In visual basic, if you create your function/sub first, then on the line above it, you type ' three times, it will auto-generate the relevant xml for documentation. This also shows up when you mouseover in intellisense, and when you are making use of the function.

CSS Div width percentage and padding without breaking layout

Try removing the position from header and add overflow to container:

#container {
#header {

Where to find htdocs in XAMPP Mac

There are two ways to find it:

One way is to open Finder>Applications>XAMPP(FolderNotTheInstaller)>htdocs

Another way is cmd+space and searches for manager-osx,

go to Welcome and click the Open Application Folder.

enter image description here

Persistent invalid graphics state error when using ggplot2

You likely don't need to reinstall ggplot2

Solution: go back to plot that didn't work previously. Take the below console output for example. The figure margins (the window that displays your plots) were too small to display the pairs(MinusInner) plot. Then when I tried to make the next qplot, R was still hung up on previous error.

pairs(MinusInner) Error in : figure margins too large qplot(Sample.Type, BAE,data=MinusInner, geom="boxplot") Error in, .Call(C_palette2, NULL)) : invalid graphics state

I fixed the first error by expanding the plot window and rerunning the pairs(MinusInner) plot. Then blam, it worked.

pairs(MinusInner) qplot(Sample.Type, BAE,data=MinusInner, geom="boxplot")

How do I add a user when I'm using Alpine as a base image?

Alpine uses the command adduser and addgroup for creating users and groups (rather than useradd and usergroup).

FROM alpine:latest

# Create a group and user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

# Tell docker that all future commands should run as the appuser user
USER appuser

The flags for adduser are:

Usage: adduser [OPTIONS] USER [GROUP]

Create new user, or add USER to GROUP

        -h DIR          Home directory
        -g GECOS        GECOS field
        -s SHELL        Login shell
        -G GRP          Group
        -S              Create a system user
        -D              Don't assign a password
        -H              Don't create home directory
        -u UID          User id
        -k SKEL         Skeleton directory (/etc/skel)

Add new user official docs

Set Google Maps Container DIV width and height 100%

If you can't affect your parents elements (like in a nested components situation) you can use height: 100vh which will make it a full window (=view) height;

Pick images of root folder from sub-folder

when you upload your files to the server be careful ,some tomes your images will not appear on the web page and a crashed icon will appear that means your file path is not properly arranged or coded when you have the the following file structure the code should be like this File structure: ->web(main folder) ->images(subfolder)->logo.png(image in the sub folder)the code for the above is below follow this standard

<img src="../images/logo.jpg" alt="image1" width="50px" height="50px">

if you uploaded your files to the web server by neglecting the file structure with out creating the folder web if you directly upload the files then your images will be broken you can't see images,then change the code as following

<img src="images/logo.jpg" alt="image1" width="50px" height="50px">

thank you->vamshi krishnan

ssl_error_rx_record_too_long and Apache SSL

If you have the error after setup a new https vhost and the config seems to be right, remember to link in sites-enabled too.

Input type DateTime - Value format?

That one shows up correctly as HTML5-Tag for those looking for this:

<input type="datetime" name="somedatafield" value="2011-12-21T11:33:23Z" />

Close window automatically after printing dialog closes

I just want to write what I have done and what has worked for me (as nothing else I tried had worked).

I had the problem that IE would close the windows before the print dialog got up.

After a lot of trial and error og testing this is what I got to work:

var w =;
w.document.write($('#data').html()); //only part of the page to print, using jquery
w.document.close(); //this seems to be the thing doing the trick

This seems to work in all browsers.

2 column div layout: right column with fixed width, left fluid

Hey, What you can do is apply a fixed width to both the containers and then use another div class where clear:both, like

div#left {

width: 600px;
float: left;

div#right {

width: 240px;
float: right;


div.clear {



place a the clear div under left and right container.

How to select all instances of a variable and edit variable name in Sublime

The Magic is, you have to start with an empty selection, so put your cursor in front of the word/character you want to multi-select and press Ctrl+D .

Use index in pandas to plot data


monthly_mean.plot(x=df.index, y='A')

Where can I read the Console output in Visual Studio 2015

You can run your program by: Debug -> Start Without Debugging. It will keep a console opened after the program will be finished.

enter image description here

Where does the iPhone Simulator store its data?

For react-native users who don't use Xcode often, you can just use find. Open a terminal and search by with the database name.

$ find ~/Library/Developer -name 'myname.db'

If you don't know the exact name you can use wildcards:

$ find ~/Library/Developer -name 'myname.*'

Excel VBA - Delete empty rows

How about

sub foo()
  dim r As Range, rows As Long, i As Long
  Set r = ActiveSheet.Range("A1:Z50")
  rows = r.rows.Count
  For i = rows To 1 Step (-1)
    If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
End Sub

Try this

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Range("A" & i & ":" & "Z" & i)
                Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
    Application.ScreenUpdating = True

    Exit Sub
    MsgBox Err.Description
    Resume LetsContinue
End Sub

IF you want to delete the entire row then use this code

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Rows(i)
                Set DelRange = Union(DelRange, Rows(i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
    Application.ScreenUpdating = True

    Exit Sub
    MsgBox Err.Description
    Resume LetsContinue
End Sub

How to run single test method with phpunit?

The reason your tests are all being run is that you have the --filter flag after the file name. PHPUnit is not reading the options at all and so is running all the test cases.

From the help screen:

 Usage: phpunit [options] UnitTest [UnitTest.php]
        phpunit [options] <directory>

So move the --filter argument before the test file that you want as mentioned in @Alex and @Ferid Mövsümov answers. And you should only have the test that you want run.

Java 8, Streams to find the duplicate elements

You can get the duplicated like this :

List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 4, 4);
Set<Integer> duplicated = numbers
  .filter(n -> numbers
        .filter(x -> x == n)
        .count() > 1)

Picking a random element from a set

If you want to do it in Java, you should consider copying the elements into some kind of random-access collection (such as an ArrayList). Because, unless your set is small, accessing the selected element will be expensive (O(n) instead of O(1)). [ed: list copy is also O(n)]

Alternatively, you could look for another Set implementation that more closely matches your requirements. The ListOrderedSet from Commons Collections looks promising.

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

Go to phpMyAdmin/ edit the line

$cfg['Servers'][$i]['password'] = '';


$cfg['Servers'][$i]['password'] = 'yourpassword';

This problem might occur due to setting of a password to root, thus phpmyadmin is not able to connect to the mysql database.

And the last thing change

$cfg['Servers'][$i]['extension'] = 'mysql';


$cfg['Servers'][$i]['extension'] = 'mysqli';

Now restart your server. and see.

Django: Redirect to previous page after login

I linked to the login form by passing the current page as a GET parameter and then used 'next' to redirect to that page. Thanks!

How to execute function in SQL Server 2008

I have come to this question and the one below several times.

how to call scalar function in sql server 2008

Each time, I try entering the Function using the syntax shown here in SQL Server Management Studio, or SSMS, to see the results, and each time I get the errors.

For me, that is because my result set is in tabular data format. Therefore, to see the results in SSMS, I have to call it like this:

SELECT * FROM dbo.Afisho_rankimin_TABLE(5);

I understand that the author's question involved a scalar function, so this answer is only to help others who come to StackOverflow often when they have a problem with a query (like me).

I hope this helps others.

Get the Id of current table row with Jquery

First, your jQuery will not work at all unless you enclose all your trs and tds in a table:


Second, your code gets the id of the first tr of the page, since you select all the trs of the page and get the id of the first one (.attr() returns the attribute of the first element in the set of elements it is used on)

Your current code:

  $('input[type=button]' ).click(function() {
   bid = ( ; // button ID 
   trid = $('tr').attr('id'); // ID of the the first TR on the page
                              // $('tr') selects all trs in the DOM

trid is always TEST1 (jsFiddle)

Instead of selecting all trs on the page with $('tr'), you want to select the first ancestor of the clicked upon input that is a tr. Use .closest() for this in the form $(this).closest('tr').

You can reference the clicked on element as this, make a jQuery object out of it with the form $(this), so you have access to all the jQuery methods on it.

What your code should look like:

  // On DOM ready...
$(function() {

      $('input[type=button]' ).click(function() {

          var bid, trid; // Declare variables. If you don't use var 
                         // you will bind bid and trid 
                         // to the window, since you make them global variables.

          bid = ( ; // button ID 

          trid = $(this).closest('tr').attr('id'); // table row ID 

jsFiddle example

Can't use method return value in write context

The issue is this, you want to know if the error is not empty.

public function getError() {
    return $this->error;

Adding a method isErrorSet() will solve the problem.

public function isErrorSet() {
    if (isset($this->error) && !empty($this->error)) {
        return true;
    } else {
        return false;

Now this will work fine with this code with no notice.

if (!($x->isErrorSet())) {
    echo $x->getError();

How can I use JSON data to populate the options of a select box?

Why not just make the server return the names?

["Woodland Hills", "none", "Los Angeles", "Laguna Hills"]

Then create the <option> elements using JavaScript.

    data: 'q=' + str,
    dataType: 'json',
    success: function( json ) {
        $.each(json, function(i, value) {
            $('#myselect').append($('<option>').text(value).attr('value', value));

How to convert JTextField to String and String to JTextField?

JTextField allows us to getText() and setText() these are used to get and set the contents of the text field, for example.

text = texfield.getText();

hope this helps


Like that

var purchCount = (from purchase in myBlaContext.purchases select purchase).Count();

or even easier

var purchCount = myBlaContext.purchases.Count()

Bootstrap - Removing padding or margin when screen size is smaller

The easy solution is to write something like that,



By adding lg, the class will be applied only on large screens

Including jars in classpath on commandline (javac or apt)

Try the following:

java -cp jar1:jar2:jar3:dir1:. HelloWorld

The default classpath (unless there is a CLASSPATH environment variable) is the current directory so if you redefine it, make sure you're adding the current directory (.) to the classpath as I have done.

Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51

I came here because I was getting this error for the quokka.js ext in vscode.

My solution: (on a mac via the terminal)

1- I went to ~/.quokka

2- I ran nano config.json

3- I copied the code from config.json into a separate file

4- I deleted the code in config.json

5- I stopped and restarted Quokka.

6- Once I confirmed that Quokka was working without errors, I deleted the config.json file code.

Return single column from a multi-dimensional array

array_map is a call back function, where you can play with the passed array. this should work.

$str = implode(',', array_map(function($el){ return $el['tag_id']; }, $arr));

How to set shadows in React Native for android?

I had the same problem shadow/elevation not showing on Android with elevation:2. Then i noticed that the view element is fool width, so I added margin:2 to the view element and elevation properly appeared.


    margin: 2,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 1
    shadowOpacity: 0.2,
    shadowRadius: 1.41,
    elevation: 2

Android: enter image description here

iOS: enter image description here

Enable/disable buttons with Angular

Set a property for the current lesson: currentLesson. It will hold, obviously, the 'number' of the choosen lesson. On each button click, set the currentLesson value to 'number'/ order of the button, i.e. for the first button, it will be '1', for the second '2' and so on. Each button now can be disabled with [disabled] attribute, if it the currentLesson is not the same as it's order.


  <button  (click)="currentLesson = '1'"
         [disabled]="currentLesson !== '1'" class="primair">
           Start lesson</button>
  <button (click)="currentLesson = '2'"
         [disabled]="currentLesson !== '2'" class="primair">
           Start lesson</button>
 .....//so on



  classes = [
  name: 'string',
  level: 'string',
  code: 'number',
  currentLesson: '1'



Putting everything in a loop:


<div *ngFor="let class of classes; let i = index">
   <button [disabled]="currentLesson !== i + 1" class="primair">
           Start lesson {{i +  1}}</button>



classes = [
  name: 'Lesson1',
  level: 1,
  code: 1,
  name: 'Lesson2',
  level: 1,
  code: 2,
  name: 'Lesson3',
  level: 2,
  code: 3,


How to change the Content of a <textarea> with JavaScript

If you can use jQuery, and I highly recommend you do, you would simply do


Otherwise, it is browser dependent. Assuming you have

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

In most browsers you do

myTextArea.innerHTML = '';

But in Firefox, you do

myTextArea.innerText = '';

Figuring out what browser the user is using is left as an exercise for the reader. Unless you use jQuery, of course ;)

Edit: I take that back. Looks like support for .innerHTML on textarea's has improved. I tested in Chrome, Firefox and Internet Explorer, all of them cleared the textarea correctly.

Edit 2: And I just checked, if you use .val('') in jQuery, it just sets the .value property for textarea's. So .value should be fine.

Align image in center and middle within div

This worked for me when you have to center align image and your parent div to image has covers whole screen. i.e. height:100% and width:100%


How can I display a pdf document into a Webview?

Actually all of the solutions were pretty complex, and I found a really simple solution (I'm not sure if it is available for all sdk versions). It will open the pdf document in a preview window where the user is able to view and save/share the document:

webView.setDownloadListener(DownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
     val i = Intent(Intent.ACTION_QUICK_VIEW) = Uri.parse(url)
     if (i.resolveActivity(getPackageManager()) != null) {
     } else {
            val i2 = Intent(Intent.ACTION_VIEW)
   = Uri.parse(url)


SQL query, if value is null then return 1

try like below...

WHEN currate.currentrate is null THEN 1
ELSE currate.currentrate
END as currentrate

Newline in string attribute

Code behind solution

private void Button1_Click(object sender, RoutedEventArgs e)
    System.Text.StringBuilder myStringBuilder = new System.Text.StringBuilder();
    TextBox1.Text = myStringBuilder.ToString();

Aligning two divs side-by-side

The HTML code is for three div align side by side and can be used for two also by some changes

<div id="wrapper">
  <div id="first">first</div>
  <div id="second">second</div>
  <div id="third">third</div>

The CSS will be

#wrapper {
#row {
#first {
#second {
#third {

This code will workup towards responsive layout as it will resize the


according to device width. Even one can silent anyone



<!--<div id="third">third</div> --> 

and can use rest two for two


side by side.

.net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible

For me, I had ~6 different Nuget packages to update and when I selected Microsoft.AspNetCore.All first, I got the referenced error.

I started at the bottom and updated others first (EF Core, EF Design Tools, etc), then when the only one that was left was Microsoft.AspNetCore.All it worked fine.

What is an MvcHtmlString and when should I use it?

This is a late answer but if anyone reading this question is using razor, what you should remember is that razor encodes everything by default, but by using MvcHtmlString in your html helpers you can tell razor that it doesn't need to encode it.

If you want razor to not encode a string use


Decompiling Raw(), shows us that it's wrapping the string in a HtmlString

public IHtmlString Raw(string value) {
    return new HtmlString(value); 

"HtmlString only exists in ASP.NET 4.

MvcHtmlString was a compatibility shim added to MVC 2 to support both .NET 3.5 and .NET 4. Now that MVC 3 is .NET 4 only, it's a fairly trivial subclass of HtmlString presumably for MVC 2->3 for source compatibility." source

GROUP BY and COUNT in PostgreSQL

WITH uniq AS (
        SELECT DISTINCT as post_id
        FROM posts
        JOIN votes ON votes.post_id =
        -- GROUP BY not needed anymore
        -- GROUP BY
FROM uniq;

Setting public class variables

You're "setting" the value of that variable/attribute. Not overriding or overloading it. Your code is very, very common and normal.

All of these terms ("set", "override", "overload") have specific meanings. Override and Overload are about polymorphism (subclassing).

From :

Polymorphism allows the programmer to treat derived class members just like their parent class' members. More precisely, Polymorphism in object-oriented programming is the ability of objects belonging to different data types to respond to method calls of methods of the same name, each one according to an appropriate type-specific behavior. One method, or an operator such as +, -, or *, can be abstractly applied in many different situations. If a Dog is commanded to speak(), this may elicit a bark(). However, if a Pig is commanded to speak(), this may elicit an oink(). They both inherit speak() from Animal, but their derived class methods override the methods of the parent class; this is Overriding Polymorphism. Overloading Polymorphism is the use of one method signature, or one operator such as "+", to perform several different functions depending on the implementation. The "+" operator, for example, may be used to perform integer addition, float addition, list concatenation, or string concatenation. Any two subclasses of Number, such as Integer and Double, are expected to add together properly in an OOP language. The language must therefore overload the addition operator, "+", to work this way. This helps improve code readability. How this is implemented varies from language to language, but most OOP languages support at least some level of overloading polymorphism.

Replace NA with 0 in a data frame column

First, here's some sample data:

dat <- data.frame(one = rnorm(15),
                 two = sample(LETTERS, 15),
                 three = rnorm(15),
                 four = runif(15))
dat <- data.frame(lapply(dat, function(x) { x[sample(15, 5)] <- NA; x }))
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677        NA
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA        NA
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Here's our replacement:

dat[["four"]][[["four"]])] <- 0
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677 0.0000000
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA 0.0000000
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Alternatively, you can, of course, write dat$four[$four)] <- 0

Detecting an undefined object property

"propertyName" in obj //-> true | false

SQL Server PRINT SELECT (Print a select query result)?


PRINT 'Hardcoded table name -' + CAST(@@RowCount as varchar(10))

immediately after the query.

Method List in Visual Studio Code

In 2020 version of VSCode

  • # - Find symbol across files
  • @ - Find symbol within file
  • @: - Group symbols within a file

Symbols in a file VS Code v1.44.0

PHPDoc type hinting for array of objects?

To specify a variable is an array of objects:

$needles = getAllNeedles();
/* @var $needles Needle[] */
$needles[1]->...                        //codehinting works

This works in Netbeans 7.2 (I'm using it)

Works also with:

$needles = getAllNeedles();
/* @var $needles Needle[] */
foreach ($needles as $needle) {
    $needle->...                        //codehinting works

Therefore use of declaration inside the foreach is not necessary.

Understanding React-Redux and mapStateToProps()

I would like to re-structure the statement that you mentioned which is:

This means that the state as consumed by your target component can have a wildly different structure from the state as it is stored on your store

You can say that the state consumed by your target component has a small portion of the state that is stored on the redux store. In other words, the state consumed by your component would be the sub-set of the state of the redux store.

As far as understanding the connect() method is concerned, it's fairly simple! connect() method has the power to add new props to your component and even override existing props. It is through this connect method that we can access the state of the redux store as well which is thrown to us by the Provider. A combination of which works in your favor and you get to add the state of your redux store to the props of your component.

Above is some theory and I would suggest you look at this video once to understand the syntax better.

JavaScript: Is there a way to get Chrome to break on all errors?

Unfortunately, it the Developer Tools in Chrome seem to be unable to "stop on all errors", as Firebug does.

How to check compiler log in sql developer?

To see your log in SQL Developer then press:

CTRL+SHIFT + L (or CTRL + CMD + L on macOS)


View -> Log

or by using mysql query

show errors;

Vagrant ssh authentication failure

Make sure your first network interface is NAT. The other second network interface can be anything you want when you're building box. Don't forget the Vagrant user, as discussed in the Google thread.

Good luck.

Uncaught ReferenceError: $ is not defined

The source file jquery-1.2.6.min.js is not called the jQuery command $() is executed earlier than <..src='jquery-1.2.6.min.js'>.

Please run <.. src="/js/jquery-1.2.6.min.js.."> at first and make sure the src path is right, then execute jquery command


Is it possible to cherry-pick a commit from another git repository?

Yes. Fetch the repository and then cherry-pick from the remote branch.

Difference between <? super T> and <? extends T> in Java

Imagine having this hierarchy

enter image description here

1. Extends

By writing

    List<? extends C2> list;

you are saying that list will be able to reference an object of type (for example) ArrayList whose generic type is one of the 7 subtypes of C2 (C2 included):

  1. C2: new ArrayList<C2>();, (an object that can store C2 or subtypes) or
  2. D1: new ArrayList<D1>();, (an object that can store D1 or subtypes) or
  3. D2: new ArrayList<D2>();, (an object that can store D2 or subtypes) or...

and so on. Seven different cases:

    1) new ArrayList<C2>(): can store C2 D1 D2 E1 E2 E3 E4
    2) new ArrayList<D1>(): can store    D1    E1 E2  
    3) new ArrayList<D2>(): can store       D2       E3 E4
    4) new ArrayList<E1>(): can store          E1             
    5) new ArrayList<E2>(): can store             E2             
    6) new ArrayList<E3>(): can store                E3             
    7) new ArrayList<E4>(): can store                   E4             

We have a set of "storable" types for each possible case: 7 (red) sets here graphically represented

enter image description here

As you can see, there is not a safe type that is common to every case:

  • you cannot list.add(new C2(){}); because it could be list = new ArrayList<D1>();
  • you cannot list.add(new D1(){}); because it could be list = new ArrayList<D2>();

and so on.

2. Super

By writing

    List<? super C2> list;

you are saying that list will be able to reference an object of type (for example) ArrayList whose generic type is one of the 7 supertypes of C2 (C2 included):

  • A1: new ArrayList<A1>();, (an object that can store A1 or subtypes) or
  • A2: new ArrayList<A2>();, (an object that can store A2 or subtypes) or
  • A3: new ArrayList<A3>();, (an object that can store A3 or subtypes) or...

and so on. Seven different cases:

    1) new ArrayList<A1>(): can store A1          B1 B2       C1 C2    D1 D2 E1 E2 E3 E4
    2) new ArrayList<A2>(): can store    A2          B2       C1 C2    D1 D2 E1 E2 E3 E4
    3) new ArrayList<A3>(): can store       A3          B3       C2 C3 D1 D2 E1 E2 E3 E4
    4) new ArrayList<A4>(): can store          A4       B3 B4    C2 C3 D1 D2 E1 E2 E3 E4
    5) new ArrayList<B2>(): can store                B2       C1 C2    D1 D2 E1 E2 E3 E4
    6) new ArrayList<B3>(): can store                   B3       C2 C3 D1 D2 E1 E2 E3 E4
    7) new ArrayList<C2>(): can store                            C2    D1 D2 E1 E2 E3 E4

We have a set of "storable" types for each possible case: 7 (red) sets here graphically represented

enter image description here

As you can see, here we have seven safe types that are common to every case: C2, D1, D2, E1, E2, E3, E4.

  • you can list.add(new C2(){}); because, regardless of the kind of List we're referencing, C2 is allowed
  • you can list.add(new D1(){}); because, regardless of the kind of List we're referencing, D1 is allowed

and so on. You probably noticed that these types correspond to the hierarchy starting from type C2.


Here the complete hierarchy if you wish to make some tests

interface A1{}
interface A2{}
interface A3{}
interface A4{}

interface B1 extends A1{}
interface B2 extends A1,A2{}
interface B3 extends A3,A4{}
interface B4 extends A4{}

interface C1 extends B2{}
interface C2 extends B2,B3{}
interface C3 extends B3{}

interface D1 extends C1,C2{}
interface D2 extends C2{}

interface E1 extends D1{}
interface E2 extends D1{}
interface E3 extends D2{}
interface E4 extends D2{}

Python-Requests close http connection

As discussed here, there really isn't such a thing as an HTTP connection and what httplib refers to as the HTTPConnection is really the underlying TCP connection which doesn't really know much about your requests at all. Requests abstracts that away and you won't ever see it.

The newest version of Requests does in fact keep the TCP connection alive after your request.. If you do want your TCP connections to close, you can just configure the requests to not use keep-alive.

s = requests.session()
s.config['keep_alive'] = False

Enable UTF-8 encoding for JavaScript

just add your script like this:

<script src="/js/intlTelInput.min.js" charset="utf-8"></script>

Change Placeholder Text using jQuery

working example of dynamic placeholder using Javascript and Jquery

<input type="text" id="textbox">
 <select id="selection" onchange="changeplh()">

function changeplh(){
 var sel = document.getElementById("selection");
    var textbx = document.getElementById("textbox");
    var indexe = sel.selectedIndex;

    if(indexe == 0) { 
     $("#textbox").attr("placeholder", "age");

       if(indexe == 1) { 
     $("#textbox").attr("placeholder", "name");

Leap year calculation

In Java Below code calculates leap year count between two given year. Determine starting and ending point of the loop.

Then if parameter modulo 4 is equal 0 and parameter modulo 100 not equal 0 or parameter modulo 400 equal zero then it is leap year and increase counter.

static int calculateLeapYearCount(int year, int startingYear) {
        int min = Math.min(year, startingYear);
        int max = Math.max(year, startingYear);
        int counter = 0;
        for (int i = min; i < max; i++) {
            if ((i % 4 == 0 && i % 100 != 0) || i % 400 == 0) {
                counter = counter + 1;
        return counter;

Granting DBA privileges to user in Oracle

You need only to write:


Because this already makes the user a DB Administrator

How to select true/false based on column value?

Use a CASE. I would post the specific code, but need more information than is supplied in the post - such as the data type of EntityProfile and what is usually stored in it. Something like:

CASE WHEN EntityProfile IS NULL THEN 'False' ELSE 'True' END

Edit - the entire SELECT statement, as per the info in the comments:

SELECT EntityID, EntityName, 
       CASE WHEN EntityProfile IS NULL THEN 'False' ELSE 'True' END AS HasProfile
FROM Entity

No LEFT JOIN necessary in this case...

Sending a JSON HTTP POST request from Android

Posting parameters Using POST:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Host", "");
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.flush ();
printout.close ();

The rest of the thing you can do it.

Convert .cer certificate to .jks

Just to be sure that this is really the "conversion" you need, please note that jks files are keystores, a file format used to store more than one certificate and allows you to retrieve them programmatically using the Java security API, it's not a one-to-one conversion between equivalent formats.

So, if you just want to import that certificate in a new ad-hoc keystore you can do it with Keystore Explorer, a graphical tool. You'll be able to modify the keystore and the certificates contained therein like you would have done with the java terminal utilities like keytool (but in a more accessible way).

Named placeholders in string formatting

For very simple cases you can simply use a hardcoded String replace, no need for a library there:

    String url = "There's an incorrect value '%(value)' in column # %(column)";
    url = url.replace("%(value)", x); // 1
    url = url.replace("%(column)", y); // 2

WARNING: I just wanted to show the simplest code possible. Of course DO NOT use this for serious production code where security matters, as stated in the comments: escaping, error handling and security are an issue here. But in the worst case you now know why using a 'good' lib is required :-)

Cloning git repo causes error - Host key verification failed. fatal: The remote end hung up unexpectedly

Well, from sourceTree I couldn't resolve this issue but I created sshkey from bash and at least it works from git-bash.

Maven build Compilation error : Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project Maven

In my case, it was caused from an incompatibility with OpenJDK 9 (which I haven't investigated).

If you don't need JDK 9, a temporary work-around would be to purge it from your machine:

sudo apt-get remove --purge openjdk-9-jdk openjdk-9-jre 
sudo apt-get remove --purge openjdk-9-jdk-headless openjdk-9-jre-headless

how to convert string to numerical values in mongodb

Using MongoDB 4.0 and newer

You have two options i.e. $toInt or $convert. Using $toInt, follow the example below:

filterDateStage = {
    '$match': {
        'Date': {
            '$gt': '2015-04-01', 
            '$lt': '2015-04-05'

groupStage = {
    '$group': {
        '_id': '$PartnerID',
        'total': { '$sum': { '$toInt': '$moop' } }


If the conversion operation encounters an error, the aggregation operation stops and throws an error. To override this behavior, use $convert instead.

Using $convert

groupStage = {
    '$group': {
        '_id': '$PartnerID',
        'total': { 
            '$sum': { 
                '$convert': { 'input': '$moop', 'to': 'int' }

Using Map/Reduce

With map/reduce you can use javascript functions like parseInt() to do the conversion. As an example, you could define the map function to process each input document: In the function, this refers to the document that the map-reduce operation is processing. The function maps the converted moop string value to the PartnerID for each document and emits the PartnerID and converted moop pair. This is where the javascript native function parseInt() can be applied:

var mapper = function () {
    var x = parseInt(this.moop);
    emit(this.PartnerID, x);

Next, define the corresponding reduce function with two arguments keyCustId and valuesMoop. valuesMoop is an array whose elements are the integer moop values emitted by the map function and grouped by keyPartnerID. The function reduces the valuesMoop array to the sum of its elements.

var reducer = function(keyPartnerID, valuesMoop) {
                  return Array.sum(valuesMoop);

        out : "example_results",
        query: { 
            Date: {
                $gt: "2015-04-01", 
                $lt: "2015-04-05"

 db.example_results.find(function (err, docs) {
    if(err) console.log(err);

For example, with the following sample collection of documents:

/* 0 */
    "_id" : ObjectId("550c00f81bcc15211016699b"),
    "Date" : "2015-04-04",
    "PartnerID" : "123456",
    "moop" : "1234"

/* 1 */
    "_id" : ObjectId("550c00f81bcc15211016699c"),
    "Date" : "2015-04-03",
    "PartnerID" : "123456",
    "moop" : "24"

/* 2 */
    "_id" : ObjectId("550c00f81bcc15211016699d"),
    "Date" : "2015-04-02",
    "PartnerID" : "123457",
    "moop" : "21"

/* 3 */
    "_id" : ObjectId("550c00f81bcc15211016699e"),
    "Date" : "2015-04-02",
    "PartnerID" : "123457",
    "moop" : "8"

The above Map/Reduce operation will save the results to the example_results collection and the shell command db.example_results.find() will give:

/* 0 */
    "_id" : "123456",
    "value" : 1258

/* 1 */
    "_id" : "123457",
    "value" : 29

How to use OUTPUT parameter in Stored Procedure

You need to define the output parameter as an output parameter in the code with the ParameterDirection.Output enumeration. There are numerous examples of this out there, but here's one on MSDN.

Doctrine query builder using inner join with conditions

You can explicitly have a join like this:

$qb->innerJoin('c.phones', 'p', Join::ON, ' = p.customerId');

But you need to use the namespace of the class Join from doctrine:

use Doctrine\ORM\Query\Expr\Join;

Or if you prefere like that:

$qb->innerJoin('c.phones', 'p', Doctrine\ORM\Query\Expr\Join::ON, ' = p.customerId');

Otherwise, Join class won't be detected and your script will crash...

Here the constructor of the innerJoin method:

public function innerJoin($join, $alias, $conditionType = null, $condition = null);

You can find other possibilities (not just join "ON", but also "WITH", etc...) here:


Think it should be:

    ->innerJoin('c.phones', 'p', Join::ON, ' = p.customerId')
    ->where('c.username = :username')
    ->andWhere(' = :phone');

        'username' => $username,
        'phone' => $phone->getPhone(),

Otherwise I think you are performing a mix of ON and WITH, perhaps the problem.

(SC) DeleteService FAILED 1072

I had the same error due to a typo in the service name, i was trying to delete the service display name instead of the service name. Once I used the right service name it worked fine

Entity framework left join

If UserGroups has a one to many relationship with UserGroupPrices table, then in EF, once the relationship is defined in code like:

//In UserGroups Model
public List<UserGroupPrices> UserGrpPriceList {get;set;}

//In UserGroupPrices model
public UserGroups UserGrps {get;set;}

You can pull the left joined result set by simply this:

var list = db.UserGroupDbSet.ToList();

assuming your DbSet for the left table is UserGroupDbSet, which will include the UserGrpPriceList, which is a list of all associated records from the right table.

Find the index of a dict within a list, by matching the dict's value

For a given iterable, more_itertools.locate yields positions of items that satisfy a predicate.

import more_itertools as mit

iterable = [
    {"id": "1234", "name": "Jason"},
    {"id": "2345", "name": "Tom"},
    {"id": "3456", "name": "Art"}

list(mit.locate(iterable, pred=lambda d: d["name"] == "Tom"))
# [1]

more_itertools is a third-party library that implements itertools recipes among other useful tools.

How to convert a date string to different format

I assume I have import datetime before running each of the lines of code below

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

prints "01/25/13".

If you can't live with the leading zero, try this:

dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month,, dt.year % 100)

This prints "1/25/13".

EDIT: This may not work on every platform:

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

swift How to remove optional String Character

You can just put ! and it will work:

print(var1) // optional("something")

print(var1!) // "something"

C# Iterating through an enum? (Indexing a System.Array)

What about using a foreach loop, maybe you could work with that?

  int i = 0;
  foreach (var o in values)
    print(names[i], o);

something like that perhaps?

Accessing UI (Main) Thread safely in WPF

The best way to go about it would be to get a SynchronizationContext from the UI thread and use it. This class abstracts marshalling calls to other threads, and makes testing easier (in contrast to using WPF's Dispatcher directly). For example:

class MyViewModel
    private readonly SynchronizationContext _syncContext;

    public MyViewModel()
        // we assume this ctor is called from the UI thread!
        _syncContext = SynchronizationContext.Current;

    // ...

    private void watcher_Changed(object sender, FileSystemEventArgs e)
         _syncContext.Post(o => DGAddRow(crp.Protocol, ft), null);

Pipenv: Command Not Found

For me, what worked on Windows was running Command Prompt as administrator and then installing pipenv globally: python -m pip install pipenv.

Oracle: SQL query to find all the triggers belonging to the tables?

Another table that is useful is:

SELECT * FROM user_objects WHERE object_type='TRIGGER';

You can also use this to query views, indexes etc etc

laravel Eloquent ORM delete() method

Before delete , there are several methods in laravel.

User::find(1) and User::first() return an instance.

User::where('id',1)->get and User::all() return a collection of instance.

call delete on an model instance will returns true/false

$user->delete(); //returns true/false

call delete on a collection of instance will returns a number which represents the number of the records had been deleted

//assume you have 10 users, id from 1 to 10;
$result=User::where('id','<',11)->delete(); //returns 11 (the number of the records had been deleted)

//lets call delete again
$result2=User::where('id','<',11)->delete(); //returns 0 (we have already delete the id<11 users, so this time we delete nothing, the result should be the number of the records had been deleted(0)  ) 

Also there are other delete methods, you can call destroy as a model static method like below

$result=User::destroy(collect([1, 2, 3]));
//these 3 statement do the same thing, delete id =1,2,3 users, returns the number of the records had been deleted

One more thing ,if you are new to laravel ,you can use php artisan tinker to see the result, which is more efficient and then dd($result) , print_r($result);

SQL Case Expression Syntax?

Here you can find a complete guide for MySQL case statements in SQL.

     WHEN some_condition THEN return_some_value
     ELSE return_some_other_value

Python requests library how to pass Authorization header with single token

This worked for me:

access_token = #yourAccessTokenHere#

result =,
               'Authorization': 'Bearer {}'.format(access_token)})

How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message

I've been to this post about 10 times now and I just wanted to leave my two cents here. You can just unmount it conditionally.

if (renderMyComponent) {
  <MyComponent props={...} />

All you have to do is remove it from the DOM in order to unmount it.

As long as renderMyComponent = true, the component will render. If you set renderMyComponent = false, it will unmount from the DOM.

Matplotlib figure facecolor (background color)

savefig has its own parameter for facecolor. I think an even easier way than the accepted answer is to set them globally just once, instead of putting facecolor=fig.get_facecolor() every time:


The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

I fixed this error by upgrading the app from .Net Framework 4.5 to 4.6.2.

TLS-1.2 was correctly installed on the server, and older versions like TLS-1.1 were disabled. However, .Net 4.5 does not support TLS-1.2.

Return in Scala

Don't write if statements without a corresponding else. Once you add the else to your fragment you'll see that your true and false are in fact the last expressions of the function.

def balanceMain(elem: List[Char]): Boolean =
    if (elem.isEmpty)
      if (count == 0)
      if (elem.head == '(')
        balanceMain(elem.tail, open, count + 1)

Javascript how to parse JSON array

Something more to the point for me..

var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';  
var contact = JSON.parse(jsontext);  
document.write(contact.surname + ", " + contact.firstname);  
// Output:  
// Aaberg, Jesper  
// 555-0100


Fluid width with equally spaced DIVs

This worked for me with 5 images in diferent sizes.

  1. Create a container div
  2. An Unordered list for the images
  3. On css the unordened must be displayed vertically and without bullets
  4. Justify content of container div

This works because of justify-content:space-between, and it's on a list, displayed horizontally.


 #container {
            display: flex;
            justify-content: space-between;
    #container ul li{ display:inline; list-style-type:none;

On html

<div id="container"> 
        <li><img src="box1.png"><li>
        <li><img src="box2.png"><li>
        <li><img src="box3.png"><li>
        <li><img src="box4.png"><li>
        <li><img src="box5.png"><li>

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.

(How) can I count the items in an enum?

Add a entry, at the end of your enum, called Folders_MAX or something similar and use this value when initializing your arrays.

ContainerClass* m_containers[Folders_MAX];

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 2: ordinal not in range(128)

For Python 3 users:

changing the encoding from 'ascii' to 'latin1' works.

Also, you can try finding the encoding automatically by reading the top 10000 bytes using the below snippet:

import chardet  
with open("dataset_path", 'rb') as rawdata:  
            result = chardet.detect(  

Best way to remove the last character from a string built with stringbuilder

The simplest and most efficient way is to perform this command:


by doing this you move the pointer (i.e. last index) back one character but you don't change the mutability of the object. In fact, clearing a StringBuilder is best done with Length as well (but do actually use the Clear() method for clarity instead because that's what its implementation looks like):

data.Length = 0;

again, because it doesn't change the allocation table. Think of it like saying, I don't want to recognize these bytes anymore. Now, even when calling ToString(), it won't recognize anything past its Length, well, it can't. It's a mutable object that allocates more space than what you provide it, it's simply built this way.

How to upload a file to directory in S3 bucket using boto

Using boto3

import logging
import boto3
from botocore.exceptions import ClientError

def upload_file(file_name, bucket, object_name=None):
    """Upload a file to an S3 bucket

    :param file_name: File to upload
    :param bucket: Bucket to upload to
    :param object_name: S3 object name. If not specified then file_name is used
    :return: True if file was uploaded, else False

    # If S3 object_name was not specified, use file_name
    if object_name is None:
        object_name = file_name

    # Upload the file
    s3_client = boto3.client('s3')
        response = s3_client.upload_file(file_name, bucket, object_name)
    except ClientError as e:
        return False
    return True

For more:-

Why is Visual Studio 2010 not able to find/open PDB files?

I had the same problem. It turns out that, compiling a project I got from someone else, I haven't set the correct StartUp project (right click on the desired startup project in the solution explorer and pick "set as StartUp Project"). Maybe this will help, cheers.

Python Matplotlib figure title overlaps axes label when using twiny

Forget using plt.title and place the text directly with plt.text. An over-exaggerated example is given below:

import pylab as plt

fig = plt.figure(figsize=(5,10))

figure_title = "Normal title"
ax1  = plt.subplot(1,2,1)

plt.title(figure_title, fontsize = 20)

figure_title = "Raised title"
ax2  = plt.subplot(1,2,2)

plt.text(0.5, 1.08, figure_title,
         transform = ax2.transAxes)

enter image description here

Where can I get Google developer key

First activate Google+ API, then you will get "Simple API access" box, from there you can get developer key as API key or read this:

How to check if a file exists in Documents folder?

check if file exist in side the document/catchimage path :

NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *tempName = [NSString stringWithFormat:@"%@/catchimage/%@.png",stringPath,@"file name"];
if([[NSFileManager defaultManager] fileExistsAtPath:temName]){
    // ur code here
} else {
    // ur code here** 

Convert NVARCHAR to DATETIME in SQL Server 2008

what about this

DECLARE @date DATETIME = (SELECT convert(DATETIME, '2013-08-29 13:55:48', 120))
--// Convert DATETIME to custom NVARCHAR FORMAT
RIGHT('00'+ CAST(DAY(@date) AS NVARCHAR),2) + '-' +
RIGHT('00'+ CAST(MONTH(@date) AS NVARCHAR),2) + '-' + 
CAST(YEAR(@date) AS NVARCHAR) + ' ' + 

result: '29-08-2013 13:55:48.0000000'

Logcat not displaying my log calls

I needed to restart the adb service with the command adb usb

Prior to this I was getting all logging and able to debug, but wasn't getting my own log lines (yes, I was getting system logging associated with my application).

InputStream from a URL

Your original code uses FileInputStream, which is for accessing file system hosted files.

The constructor you used will attempt to locate a file named a.txt in the subfolder of the current working directory (the value of system property user.dir). The name you provide is resolved to a file using the File class.

URL objects are the generic way to solve this. You can use URLs to access local files but also network hosted resources. The URL class supports the file:// protocol besides http:// or https:// so you're good to go.

Use Expect in a Bash script to provide a password to an SSH command

The easiest way is to use sshpass. This is available in Ubuntu/Debian repositories and you don't have to deal with integrating expect with Bash.

An example:

sshpass -p<password> ssh <arguments>
sshpass -ptest1324 ssh [email protected] ls -l /tmp

The above command can be easily integrated with a Bash script.

Note: Please read the Security Considerations section in man sshpass for a full understanding of the security implications.

prevent refresh of page when button inside form clicked

If your button is default "button" make sure you explicity set the type attribute, otherwise the WebForm will treat it as submit by default.

if you use js do like this

<form method="POST">
   <button name="data"  type="button" id="btnData" onclick="getData()">Click</button>

**If you use jquery use like this**

<form method="POST">
   <button name="data"  type="button" id="btnData">Click</button>

   // Code goes here
getData(); // your onclick function call here


Is there a foreach loop in Go?

You can in fact use range without referencing it's return values by using for range against your type:

arr := make([]uint8, 5)
i,j := 0,0
for range arr {
    fmt.Println("Array Loop",i)

for range "bytes" {
    fmt.Println("String Loop",j)

How to define Gradle's home in IDEA?

You can write a simple gradle script to print your GRADLE_HOME directory.

task getHomeDir {
    doLast {
        println gradle.gradleHomeDir

and name it build.gradle.

Then run it with:

gradle getHomeDir

If you installed with homebrew, use brew info gradle to find the base path (i.e. /usr/local/Cellar/gradle/1.10/), and just append libexec.

The same task in Kotlin in case you use build.gradle.kts:

tasks.register("getHomeDir") {
    println("Gradle home dir: ${gradle.gradleHomeDir}")

insert datetime value in sql database with c#

 DateTime time = DateTime.Now;              // Use current time
 string format = "yyyy-MM-dd HH:mm:ss";    // modify the format depending upon input required in the column in database 
 string insert = @" insert into Table(DateTime Column) values ('" + time.ToString(format) + "')"; 

and execute the query. DateTime.Now is to insert current Datetime..

Make .gitignore ignore everything except a few files

A little more specific:

Example: Ignore everything in webroot/cache - but keep webroot/cache/.htaccess.

Notice the slash (/) after the cache folder:





og:type and valid values : constantly being parsed as og:type=website

bar is deprecated. Please check for the current docs.

"static const" vs "#define" vs "enum"

Although the question was about integers, it's worth noting that #define and enums are useless if you need a constant structure or string. These are both usually passed to functions as pointers. (With strings it's required; with structures it's much more efficient.)

As for integers, if you're in an embedded environment with very limited memory, you might need to worry about where the constant is stored and how accesses to it are compiled. The compiler might add two consts at run time, but add two #defines at compile time. A #define constant may be converted into one or more MOV [immediate] instructions, which means the constant is effectively stored in program memory. A const constant will be stored in the .const section in data memory. In systems with a Harvard architecture, there could be differences in performance and memory usage, although they'd likely be small. They might matter for hard-core optimization of inner loops.

Uncaught TypeError: .indexOf is not a function

I was getting is not a function error, after debugging it, I found that it was actually a TypeError, which meant, indexOf() being a function is applicable to strings, so I typecasted the data like the following and then used the indexOf() method to make it work'<stringToBeMatchedToPosition>')

Not sure if my answer was accurate to the question, but yes shared my opinion as i faced a similar kind of situation.

What does 'URI has an authority component' mean?

An authority is a portion of a URI. Your error suggests that it was not expecting one. The authority section is shown below, it is what is known as the website part of the url.

From RFC3986 on URIs:

The following is an example URI and its component parts:

     \_/   \______________/\_________/ \_________/ \__/
      |           |            |            |        |
   scheme     authority       path        query   fragment
      |   _____________________|__
     / \ /                        \

So there are two formats, one with an authority and one not. Regarding slashes:

"When authority is not present, the path cannot begin with two slash
characters ("//")."

Source: (search for text 'authority is not present, the path cannot begin with two slash')

Why is vertical-align:text-top; not working in CSS

You could apply position: relative; to the div and then position: absolute; top: 0; to a paragraph or span inside of it containing the text.

How to make (link)button function as hyperlink?

You can use OnClientClick event to call a JavaScript function:

<asp:Button ID="Button1" runat="server" Text="Button" onclientclick='redirect()' />

JavaScript code:

function redirect() {
  location.href = 'page.aspx';

But i think the best would be to style a hyperlink with css.

Example :

.button {
  display: block;
  height: 25px;
  background: #f1f1f1;
  padding: 10px;
  text-align: center;
  border-radius: 5px;
  border: 1px solid #e1e1e2;
  color: #000;
  font-weight: bold;

Converting string to title case

You can directly change text or string to proper using this simple method, after checking for null or empty string values in order to eliminate errors:

public string textToProper(string text)
    string ProperText = string.Empty;
    if (!string.IsNullOrEmpty(text))
        ProperText = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(text);
        ProperText = string.Empty;
    return ProperText;

Two div blocks on same line

What I would first is make the following CSS code:

#bloc1 {
   float: left

This will make #bloc2 be inline with #bloc1.

To make it central, I would add #bloc1 and #bloc2 in a separate div. For example:

<style type="text/css">
    #wrapper { margin: 0 auto; }
<div id="wrapper">
    <div id="bloc1"> ... </div>
    <div id="bloc2"> ... </div>

Truncate to three decimals in Python

I believe using the format function is a bad idea. Please see the below. It rounds the value. I use Python 3.6.

>>> '%.3f'%(1.9999999)

Use a regular expression instead:

>>> re.match(r'\d+.\d{3}', str(1.999999)).group(0)

.mp4 file not playing in chrome

This started out as an attempt to cast video from my pc to a tv (with subtitles) eventually using Chromecast. And I ended up in this "does not play mp4" situation. However I seemed to have proved that Chrome will play (exactly the same) mp4 as long as it isn't wrapped in html(5) So here is what I have constructed. I have made a webpage under localhost and in there is a default.htm which contains:-

<!DOCTYPE html>
<video  controls >
 <source src="sample.mp4" type="video/mp4">
 <track kind="subtitles" src="sample.vtt" label="gcsubs" srclang="eng">

the video and subtitle files are stored in the same folder as default.htm

I have the very latest version of Chrome (just updated this morning)

When I type the appropriate localhost... into my Chrome browser a black square appears with a "GO" arrow and an elapsed time bar, a mute button and an icon which says "CC". If I hit the go arrow, nothing happens (it doesn't change to "pause", the elapsed time doesn't move, and the timer sticks at 0:00. There are no error messages - nothing!

(note that if I input localhost.. to IE11 the video plays!!!!

In Chrome if I enter the disc address of sample.mp4 (i.e. C:\webstore\sample.mp4 then Chrome will play the video fine?.

This last bit is probably a working solution for Chromecast except that I cannot see any subtitles. I really want a solution with working subtitles. I just don't understand what is different in Chrome between the two methods of playing mp4

Slide up/down effect with ng-show and ng-animate

This can actually be done in CSS and very minimal JS just by adding a CSS class (don't set styles directly in JS!) with e.g. a ng-clickevent. The principle is that one can't animate height: 0; to height: auto; but this can be tricked by animating the max-height property. The container will expand to it's "auto-height" value when .foo-open is set - no need for fixed height or positioning.

.foo {
    max-height: 0;

.foo--open {
    max-height: 1000px; /* some arbitrary big value */
    transition: ...

see this fiddle by the excellent Lea Verou

As a concern raised in the comments, note that while this animation works perfectly with linear easing, any exponential easing will produce a behaviour different from what could be expected - due to the fact that the animated property is max-height and not height itself; specifically, only the height fraction of the easing curve of max-height will be displayed.

What is JavaScript's highest integer value that a number can go to without losing precision?

The short answer is “it depends.”

If you’re using bitwise operators anywhere (or if you’re referring to the length of an Array), the ranges are:

Unsigned: 0…(-1>>>0)

Signed: (-(-1>>>1)-1)…(-1>>>1)

(It so happens that the bitwise operators and the maximum length of an array are restricted to 32-bit integers.)

If you’re not using bitwise operators or working with array lengths:

Signed: (-Math.pow(2,53))…(+Math.pow(2,53))

These limitations are imposed by the internal representation of the “Number” type, which generally corresponds to IEEE 754 double-precision floating-point representation. (Note that unlike typical signed integers, the magnitude of the negative limit is the same as the magnitude of the positive limit, due to characteristics of the internal representation, which actually includes a negative 0!)

What is the right way to populate a DropDownList from a database?

You could bind the DropDownList to a data source (DataTable, List, DataSet, SqlDataSource, etc).

For example, if you wanted to use a DataTable:

ddlSubject.DataSource = subjectsTable;
ddlSubject.DataTextField = "SubjectNamne";
ddlSubject.DataValueField = "SubjectID";

EDIT - More complete example

private void LoadSubjects()

    DataTable subjects = new DataTable();

    using (SqlConnection con = new SqlConnection(connectionString))

            SqlDataAdapter adapter = new SqlDataAdapter("SELECT SubjectID, SubjectName FROM Students.dbo.Subjects", con);

            ddlSubject.DataSource = subjects;
            ddlSubject.DataTextField = "SubjectNamne";
            ddlSubject.DataValueField = "SubjectID";
        catch (Exception ex)
            // Handle the error


    // Add the initial item - you can add this even if the options from the
    // db were not successfully loaded
    ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));


To set an initial value via the markup, rather than code-behind, specify the option(s) and set the AppendDataBoundItems attribute to true:

<asp:DropDownList ID="ddlSubject" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Text="<Select Subject>" Value="0" />

You could then bind the DropDownList to a DataSource in the code-behind (just remember to remove:

ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));

from the code-behind, or you'll have two "" items.

How do I enter a multi-line comment in Perl?

POD is the official way to do multi line comments in Perl,


The quick-and-dirty way to comment out more than one line of Perl is to surround those lines with Pod directives. You have to put these directives at the beginning of the line and somewhere where Perl expects a new statement (so not in the middle of statements like the # comments). You end the comment with =cut, ending the Pod section:


my $object = NotGonnaHappen->new();


$wont_be_assigned = 37;


The quick-and-dirty method only works well when you don't plan to leave the commented code in the source. If a Pod parser comes along, your multiline comment is going to show up in the Pod translation. A better way hides it from Pod parsers as well.

The =begin directive can mark a section for a particular purpose. If the Pod parser doesn't want to handle it, it just ignores it. Label the comments with comment. End the comment using =end with the same label. You still need the =cut to go back to Perl code from the Pod comment:

=begin comment

my $object = NotGonnaHappen->new();


$wont_be_assigned = 37;

=end comment


Hyper-V: Create shared folder between host and guest with internal network

  • Open Hyper-V Manager
  • Create a new internal virtual switch (e.g. "Internal Network Connection")
  • Go to your Virtual Machine and create a new Network Adapter -> choose "Internal Network Connection" as virtual switch
  • Start the VM
  • Assign both your host as well as guest an IP address as well as a Subnet mask (IP4, e.g. (host) / (guest) and
  • Open cmd both on host and guest and check via "ping" if host and guest can reach each other (if this does not work disable/enable the network adapter via the network settings in the control panel, restart...)
  • If successfull create a folder in the VM (e.g. "VMShare"), right-click on it -> Properties -> Sharing -> Advanced Sharing -> checkmark "Share this folder" -> Permissions -> Allow "Full Control" -> Apply
  • Now you should be able to reach the folder via the host -> to do so: open Windows Explorer -> enter the path to the guest (\192.168.1.xx...) in the address line -> enter the credentials of the guest (Choose "Other User" - it can be necessary to change the domain therefore enter ".\"[username] and [password])

There is also an easy way for copying via the clipboard:

  • If you start your VM and go to "View" you can enable "Enhanced Session". If you do it is not possible to drag and drop but to copy and paste.

Enhanced Session

CSS Image size, how to fill, but not stretch?

after reading StackOverflow answers the simple solution I got is

.profilePosts div {

background: url("xyz");
background-size: contain;
background-repeat: no-repeat;
width: x;
height: y;