Programs & Examples On #Quartz composer

Quartz Composer is a node-based visual programming language freely available to registered Apple developers for realtime processing and rendering animated 2D and 3D graphics with JavaScript scripting.

Python foreach equivalent

For an updated answer you can build a forEach function in Python easily:

def forEach(list, function):
    for i, v in enumerate(list):
        function(v, i, list)

You could also adapt this to map, reduce, filter, and any other array functions from other languages or precedence you'd want to bring over. For loops are fast enough, but the boiler plate is longer than forEach or the other functions. You could also extend list to have these functions with a local pointer to a class so you could call them directly on lists as well.

Reliable way to convert a file to a byte[]

Others have noted that you can use the built-in File.ReadAllBytes. The built-in method is fine, but it's worth noting that the code you post above is fragile for two reasons:

  1. Stream is IDisposable - you should place the FileStream fs = new FileStream(filename, FileMode.Open,FileAccess.Read) initialization in a using clause to ensure the file is closed. Failure to do this may mean that the stream remains open if a failure occurs, which will mean the file remains locked - and that can cause other problems later on.
  2. fs.Read may read fewer bytes than you request. In general, the .Read method of a Stream instance will read at least one byte, but not necessarily all bytes you ask for. You'll need to write a loop that retries reading until all bytes are read. This page explains this in more detail.

mysqli_fetch_array while loop columns

Try this :

   $i = 0;    
    while($row = mysqli_fetch_array($result)) {  

            $posts['post_id'] = $row[$i]['post_id'];
            $posts['post_title'] = $row[$i]['post_title'];
            $posts['type'] = $row[$i]['type'];
            $posts['author'] = $row[$i]['author'];  

        }   
    $i++;
    }

print_r($posts);

Sequelize OR condition object

Use Sequelize.or:

var condition = {
  where: Sequelize.and(
    { name: 'a project' },
    Sequelize.or(
      { id: [1,2,3] },
      { id: { lt: 10 } }
    )
  )
};

Reference (search for Sequelize.or)

Edit: Also, this has been modified and for the latest method see Morio's answer,

Sending a file over TCP sockets in Python

You can send some flag to stop while loop in server

for example

Server side:

import socket
s = socket.socket()
s.bind(("localhost", 5000))
s.listen(1)
c,a = s.accept()
filetodown = open("img.png", "wb")
while True:
   print("Receiving....")
   data = c.recv(1024)
   if data == b"DONE":
           print("Done Receiving.")
           break
   filetodown.write(data)
filetodown.close()
c.send("Thank you for connecting.")
c.shutdown(2)
c.close()
s.close()
#Done :)

Client side:

import socket
s = socket.socket()
s.connect(("localhost", 5000))
filetosend = open("img.png", "rb")
data = filetosend.read(1024)
while data:
    print("Sending...")
    s.send(data)
    data = filetosend.read(1024)
filetosend.close()
s.send(b"DONE")
print("Done Sending.")
print(s.recv(1024))
s.shutdown(2)
s.close()
#Done :)

Get list from pandas dataframe column or row?

This returns a numpy array:

arr = df["cluster"].to_numpy()

This returns a numpy array of unique values:

unique_arr = df["cluster"].unique()

You can also use numpy to get the unique values, although there are differences between the two methods:

arr = df["cluster"].to_numpy()
unique_arr = np.unique(arr)

NameError: uninitialized constant (rails)

I started having this issue after upgrading from Rails 5.1 to 5.2
It got solved with:

spring stop
spring binstub --all
spring start
rails s

Case Function Equivalent in Excel

Without reference to the original problem (which I suspect is long since solved), I very recently discovered a neat trick that makes the Choose function work exactly like a select case statement without any need to modify data. There's only one catch: only one of your choose conditions can be true at any one time.

The syntax is as follows:

CHOOSE( 
    (1 * (CONDITION_1)) + (2 * (CONDITION_2)) + ... + (N * (CONDITION_N)),
    RESULT_1, RESULT_2, ... , RESULT_N
)

On the assumption that only one of the conditions 1 to N will be true, everything else is 0, meaning the numeric value will correspond to the appropriate result.

If you are not 100% certain that all conditions are mutually exclusive, you might prefer something like:

CHOOSE(
    (1 * TEST1) + (2 * TEST2) + (4 * TEST3) + (8 * TEST4) ... (2^N * TESTN)
    OUT1, OUT2, , OUT3, , , , OUT4 , , <LOTS OF COMMAS> , OUT5
)

That said, if Excel has an upper limit on the number of arguments a function can take, you'd hit it pretty quickly.

Honestly, can't believe it's taken me years to work it out, but I haven't seen it before, so figured I'd leave it here to help others.

EDIT: Per comment below from @aTrusty: Silly numbers of commas can be eliminated (and as a result, the choose statement would work for up to 254 cases) by using a formula of the following form:

CHOOSE(
    1 + LOG(1 + (2*TEST1) + (4*TEST2) + (8*TEST3) + (16*TEST4),2), 
    OTHERWISE, RESULT1, RESULT2, RESULT3, RESULT4
)

Note the second argument to the LOG clause, which puts it in base 2 and makes the whole thing work.

Edit: Per David's answer, there's now an actual switch statement if you're lucky enough to be working on office 2016. Aside from difficulty in reading, this also means you get the efficiency of switch, not just the behaviour!

cut or awk command to print first field of first row

You can kill the process which is running the container.

With this command you can list the processes related with the docker container:

ps -aux | grep $(docker ps -a | grep container-name | awk '{print $1}')

Now you have the process ids to kill with kill or kill -9.

Max value of Xmx and Xms in Eclipse?

Why do you need -Xms768 (small heap must be at least 768...)?

That means any java process (search in eclipse) will start with 768m memory allocated, doesn't that? That is why your eclipse isn't able to start properly.

Try -Xms16 -Xmx2048m, for instance.

No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?

Spring cannot instantiate your TestController because its only constructor requires a parameter. You can add a no-arg constructor or you add @Autowired annotation to the constructor:

@Autowired
public TestController(KeeperClient testClient) {
    TestController.testClient = testClient;
}

In this case, you are explicitly telling Spring to search the application context for a KeeperClient bean and inject it when instantiating the TestControlller.

How to clear jQuery validation error messages?

Try to use this for remove validation on the click on cancel

 function HideValidators() {
            var lblMsg = document.getElementById('<%= lblRFDChild.ClientID %>');
            lblMsg.innerHTML = "";           
            if (window.Page_Validators) {
                for (var vI = 0; vI < Page_Validators.length; vI++) {
                    var vValidator = Page_Validators[vI];
                    vValidator.isvalid = true;
                    ValidatorUpdateDisplay(vValidator);
                }
            } 
        }

Get the index of a certain value in an array in PHP

Try the array_keys PHP function.

$key_string1 = array_keys($list, 'string1');

ASP.NET 4.5 has not been registered on the Web server

I have the same problem.

And got the solution turning on the ASP Net from Turn Windows feature on or off menu.

Test if remote TCP port is open from a shell script

nmap-ncat to test for local port that is not already in use


availabletobindon() {
  port="$1"
  nc -w 2 -i 1 localhost "$port" 2>&1 | grep -v -q 'Idle timeout expired'
  return "$?"
}

How can I select checkboxes using the Selenium Java WebDriver?

Selecting a checkbox is similar to clicking a button.

driver.findElement(By.id("idOfTheElement")).click();

will do.

However, you can also see whether the checkbox is already checked. The following snippet checks whether the checkbox is selected or not. If it is not selected, then it selects.

if ( !driver.findElement(By.id("idOfTheElement")).isSelected() )
{
     driver.findElement(By.id("idOfTheElement")).click();
}

Verilog generate/genvar in an always block

You don't need a generate bock if you want all the bits of temp assigned in the same always block.

parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
always @(posedge sysclk) begin
    for (integer c=0; c<ROWBITS; c=c+1) begin: test
        temp[c] <= 1'b0;
    end
end

Alternatively, if your simulator supports IEEE 1800 (SytemVerilog), then

parameter ROWBITS = 4;
reg [ROWBITS-1:0] temp;
always @(posedge sysclk) begin
        temp <= '0; // fill with 0
    end
end

PowerShell to remove text from a string

I referenced @benjamin-hubbard 's answer above to parse the output of dnscmd for A records, and generate a PHP "dictionary"/key-value pairs of IPs and Hostnames. I strung multiple -replace args together to replace text with nothing or tab to format the data for the PHP file.

$DnsDataClean = $DnsData `
    -match "^[a-zA-Z0-9].+\sA\s.+" `
    -replace "172\.30\.","`$P." `
    -replace "\[.*\] " `
    -replace "\s[0-9]+\sA\s","`t"

$DnsDataTable = ( $DnsDataClean | `
    ForEach-Object { 
        $HostName = ($_ -split "\t")[0] ; 
        $IpAddress = ($_ -split "\t")[1] ; 
        "`t`"$IpAddress`"`t=>`t'$HostName', `n" ;
    } | sort ) + "`t`"`$P.255.255`"`t=>`t'None'"

"<?php
`$P = '10.213';
`$IpHostArr = [`n`n$DnsDataTable`n];

?>" | Out-File -Encoding ASCII -FilePath IpHostLookups.php

Get-Content IpHostLookups.php

filter: progid:DXImageTransform.Microsoft.gradient is not working in ie7

Having seen your fiddle in the comments the issue is quite easy to fix. You just need to add overflow:auto or set a specific height to your div. Live example: http://jsfiddle.net/tw16/xRcXL/3/

.Tab{
    overflow:auto; /* add this */
    border:solid 1px #faa62a;
    border-bottom:none;
    padding:7px 10px;
    background:-moz-linear-gradient(center top , #FAD59F, #FA9907) repeat scroll 0 0 transparent;
    background:-webkit-gradient(linear, left top, left bottom, from(#fad59f), to(#fa9907));
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907);    
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907)";
}

Should I use @EJB or @Inject

Here is a good discussion on the topic. Gavin King recommends @Inject over @EJB for non remote EJBs.

http://www.seamframework.org/107780.lace

or

https://web.archive.org/web/20140812065624/http://www.seamframework.org/107780.lace

Re: Injecting with @EJB or @Inject?

  1. Nov 2009, 20:48 America/New_York | Link Gavin King

That error is very strange, since EJB local references should always be serializable. Bug in glassfish, perhaps?

Basically, @Inject is always better, since:

it is more typesafe,
it supports @Alternatives, and
it is aware of the scope of the injected object.

I recommend against the use of @EJB except for declaring references to remote EJBs.

and

Re: Injecting with @EJB or @Inject?

  1. Nov 2009, 17:42 America/New_York | Link Gavin King

    Does it mean @EJB better with remote EJBs?

For a remote EJB, we can't declare metadata like qualifiers, @Alternative, etc, on the bean class, since the client simply isn't going to have access to that metadata. Furthermore, some additional metadata must be specified that we don't need for the local case (global JNDI name of whatever). So all that stuff needs to go somewhere else: namely the @Produces declaration.

Can I scale a div's height proportionally to its width using CSS?

Another great way to accomplish this is to use a transparent image with a set aspect ratio. Then set the width of the image to 100% and the height to auto. That unfortunately will push down the original content of the container. So you need to wrap the original content in another div and position it absolutely to the top of the parent div.

<div class="parent">
   <img class="aspect-ratio" src="images/aspect-ratio.png" />
   <div class="content">Content</div>
</div>

CSS

.parent {
  position: relative;
}
.aspect-ratio {
  width: 100%;
  height: auto;
}
.content {
  position: absolute;
  width: 100%;
  top: 0; left: 0;
}

Calculate the number of business days between two dates?

So I had a similar task except I had to calculate business days left (from date should not be more than to date), and end date should skip to next business day.

To make it more understandable/readable, I did this in the following steps

  1. Updated toDate to the next business day if it is on weekend.

  2. Find out the number of complete weeks between dates, and for each complete week consider 5 days in running total.

  3. Now days left are only different of from and to weekdays (it won't be more than 6 days), so wrote a small loop to get it (skip Saturday and Sunday)

     public static int GetBusinessDaysLeft(DateTime fromDate, DateTime toDate)
     {
         //Validate that startDate should be less than endDate
         if (fromDate >= toDate) return 0;
    
         //Move end date to Monday if on weekends
         if (toDate.DayOfWeek == DayOfWeek.Saturday || toDate.DayOfWeek == DayOfWeek.Sunday)
             while (toDate.DayOfWeek != DayOfWeek.Monday)
                 toDate = toDate.AddDays(+1);
    
         //Consider 5 days per complete week in between start and end dates
         int remainder, quotient = Math.DivRem((toDate - fromDate).Days, 7, out remainder);
         var daysDiff = quotient * 5;
    
         var curDay = fromDate;
         while (curDay.DayOfWeek != toDate.DayOfWeek)
         {
             curDay = curDay.AddDays(1);
             if (curDay.DayOfWeek == DayOfWeek.Saturday || curDay.DayOfWeek == DayOfWeek.Sunday)
                 continue;
    
             daysDiff += 1;
         }
         return daysDiff;
     }
    

What "wmic bios get serialnumber" actually retrieves?

the wmic bios get serialnumber command call the Win32_BIOS wmi class and get the value of the SerialNumber property, which retrieves the serial number of the BIOS Chip of your system.

How do I programmatically "restart" an Android app?

Use:

navigateUpTo(new Intent(this, MainActivity.class));

It works starting from API level 16 (4.1), I believe.

Angular checkbox and ng-click

You can use ng-change instead of ng-click:

<!doctype html>
<html>
<head>
  <script src="http://code.angularjs.org/1.2.3/angular.min.js"></script>
  <script>
        var app = angular.module('myapp', []);
        app.controller('mainController', function($scope) {
          $scope.vm = {};
          $scope.vm.myClick = function($event) {
                alert($event);
          }
        });     
  </script>  
</head>
<body ng-app="myapp">
  <div ng-controller="mainController">
    <input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">
  </div>
</body>
</html>

Sorting a set of values

From a comment:

I want to sort each set.

That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.


You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.

Using multiple parameters in URL in express

For what you want I would've used

    app.get('/fruit/:fruitName&:fruitColor', function(request, response) {
       const name = request.params.fruitName 
       const color = request.params.fruitColor 
    });

or better yet

    app.get('/fruit/:fruit', function(request, response) {
       const fruit = request.params.fruit
       console.log(fruit)
    });

where fruit is a object. So in the client app you just call

https://mydomain.dm/fruit/{"name":"My fruit name", "color":"The color of the fruit"}

and as a response you should see:

    //  client side response
    // { name: My fruit name, color:The color of the fruit}

How to specify "does not contain" in dplyr filter

Try putting the search condition in a bracket, as shown below. This returns the result of the conditional query inside the bracket. Then test its result to determine if it is negative (i.e. it does not belong to any of the options in the vector), by setting it to FALSE.

SE_CSVLinelist_filtered <- filter(SE_CSVLinelist_clean, 
(where_case_travelled_1 %in% c('Outside Canada','Outside province/territory of residence but within Canada')) == FALSE)

How can I include a YAML file inside another?

Standard YAML 1.2 doesn't include natively this feature. Nevertheless many implementations provides some extension to do so.

I present a way of achieving it with Java and snakeyaml:1.24 (Java library to parse/emit YAML files) that allows creating a custom YAML tag to achieve the following goal (you will see I'm using it to load test suites defined in several YAML files and that I made it work as a list of includes for a target test: node):

# ... yaml prev stuff

tests: !include
  - '1.hello-test-suite.yaml'
  - '3.foo-test-suite.yaml'
  - '2.bar-test-suite.yaml'

# ... more yaml document

Here is the one-class Java that allows processing the !include tag. Files are loaded from classpath (Maven resources directory):

/**
 * Custom YAML loader. It adds support to the custom !include tag which allows splitting a YAML file across several
 * files for a better organization of YAML tests.
 */
@Slf4j   // <-- This is a Lombok annotation to auto-generate logger
public class MyYamlLoader {

    private static final Constructor CUSTOM_CONSTRUCTOR = new MyYamlConstructor();

    private MyYamlLoader() {
    }

    /**
     * Parse the only YAML document in a stream and produce the Java Map. It provides support for the custom !include
     * YAML tag to split YAML contents across several files.
     */
    public static Map<String, Object> load(InputStream inputStream) {
        return new Yaml(CUSTOM_CONSTRUCTOR)
                .load(inputStream);
    }


    /**
     * Custom SnakeYAML constructor that registers custom tags.
     */
    private static class MyYamlConstructor extends Constructor {

        private static final String TAG_INCLUDE = "!include";

        MyYamlConstructor() {
            // Register custom tags
            yamlConstructors.put(new Tag(TAG_INCLUDE), new IncludeConstruct());
        }

        /**
         * The actual include tag construct.
         */
        private static class IncludeConstruct implements Construct {

            @Override
            public Object construct(Node node) {
                List<Node> inclusions = castToSequenceNode(node);
                return parseInclusions(inclusions);
            }

            @Override
            public void construct2ndStep(Node node, Object object) {
                // do nothing
            }

            private List<Node> castToSequenceNode(Node node) {
                try {
                    return ((SequenceNode) node).getValue();

                } catch (ClassCastException e) {
                    throw new IllegalArgumentException(String.format("The !import value must be a sequence node, but " +
                            "'%s' found.", node));
                }
            }

            private Object parseInclusions(List<Node> inclusions) {

                List<InputStream> inputStreams = inputStreams(inclusions);

                try (final SequenceInputStream sequencedInputStream =
                             new SequenceInputStream(Collections.enumeration(inputStreams))) {

                    return new Yaml(CUSTOM_CONSTRUCTOR)
                            .load(sequencedInputStream);

                } catch (IOException e) {
                    log.error("Error closing the stream.", e);
                    return null;
                }
            }

            private List<InputStream> inputStreams(List<Node> scalarNodes) {
                return scalarNodes.stream()
                        .map(this::inputStream)
                        .collect(toList());
            }

            private InputStream inputStream(Node scalarNode) {
                String filePath = castToScalarNode(scalarNode).getValue();
                final InputStream is = getClass().getClassLoader().getResourceAsStream(filePath);
                Assert.notNull(is, String.format("Resource file %s not found.", filePath));
                return is;
            }

            private ScalarNode castToScalarNode(Node scalarNode) {
                try {
                    return ((ScalarNode) scalarNode);

                } catch (ClassCastException e) {
                    throw new IllegalArgumentException(String.format("The value must be a scalar node, but '%s' found" +
                            ".", scalarNode));
                }
            }
        }

    }

}

"application blocked by security settings" prevent applets running using oracle SE 7 update 51 on firefox on Linux mint

Just start your browser with superuser rights, and don't forget to set Java's JRE security to medium.

When running UPDATE ... datetime = NOW(); will all rows updated have the same date/time?

They should have the same time, the update is supposed to be atomic, meaning that whatever how long it takes to perform, the action is supposed to occurs as if all was done at the same time.

If you're experiencing a different behaviour, it's time to change for another DBMS.

Syntax for if/else condition in SCSS mixin

You can assign default parameter values inline when you first create the mixin:

@mixin clearfix($width: 'auto') {

  @if $width == 'auto' {

    // if width is not passed, or empty do this

  } @else {

    display: inline-block;
    width: $width;

  }
}

Using jQuery To Get Size of Viewport

You can try viewport units (CSS3):

div { 
  height: 95vh; 
  width: 95vw; 
}

Browser support

How do I ignore files in Subversion?

As nobody seems to have mentioned it...

svn propedit svn:ignore .

Then edit the contents of the file to specify the patterns to ignore, exit the editor and you're all done.

JavaScript check if variable exists (is defined/initialized)

The highest answer is correct, use typeof.

However, what I wanted to point out was that in JavaScript undefined is mutable (for some ungodly reason). So simply doing a check for varName !== undefined has the potential to not always return as you expect it to, because other libs could have changed undefined. A few answers (@skalee's, for one), seem to prefer not using typeof, and that could get one into trouble.

The "old" way to handle this was declaring undefined as a var to offset any potential muting/over-riding of undefined. However, the best way is still to use typeof because it will ignore any overriding of undefined from other code. Especially if you are writing code for use in the wild where who knows what else could be running on the page...

JavaScript: Upload file

Unless you're trying to upload the file using ajax, just submit the form to /upload/image.

<form enctype="multipart/form-data" action="/upload/image" method="post">
    <input id="image-file" type="file" />
</form>

If you do want to upload the image in the background (e.g. without submitting the whole form), you can use ajax:

Excel VBA Loop on columns

If you want to stick with the same sort of loop then this will work:

Option Explicit

Sub selectColumns()

Dim topSelection As Integer
Dim endSelection As Integer
topSelection = 2
endSelection = 10

Dim columnSelected As Integer
columnSelected = 1
Do
   With Excel.ThisWorkbook.ActiveSheet
        .Range(.Cells(columnSelected, columnSelected), .Cells(endSelection, columnSelected)).Select
   End With
   columnSelected = columnSelected + 1
Loop Until columnSelected > 10

End Sub

EDIT

If in reality you just want to loop through every cell in an area of the spreadsheet then use something like this:

Sub loopThroughCells()

'=============
'this is the starting point
Dim rwMin As Integer
Dim colMin As Integer
rwMin = 2
colMin = 2
'=============

'=============
'this is the ending point
Dim rwMax As Integer
Dim colMax As Integer
rwMax = 10
colMax = 5
'=============

'=============
'iterator
Dim rwIndex As Integer
Dim colIndex As Integer
'=============

For rwIndex = rwMin To rwMax
        For colIndex = colMin To colMax
            Cells(rwIndex, colIndex).Select
        Next colIndex
Next rwIndex

End Sub

How to set the min and max height or width of a Frame?

A workaround - at least for the minimum size: You can use grid to manage the frames contained in root and make them follow the grid size by setting sticky='nsew'. Then you can use root.grid_rowconfigure and root.grid_columnconfigure to set values for minsize like so:

from tkinter import Frame, Tk

class MyApp():
    def __init__(self):
        self.root = Tk()

        self.my_frame_red = Frame(self.root, bg='red')
        self.my_frame_red.grid(row=0, column=0, sticky='nsew')

        self.my_frame_blue = Frame(self.root, bg='blue')
        self.my_frame_blue.grid(row=0, column=1, sticky='nsew')

        self.root.grid_rowconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(1, weight=1)

        self.root.mainloop()

if __name__ == '__main__':
    app = MyApp()

But as Brian wrote (in 2010 :D) you can still resize the window to be smaller than the frame if you don't limit its minsize.

How to create a numpy array of arbitrary length strings?

You could use the object data type:

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

Auto-increment on partial primary key with Entity Framework Core

Specifying the column type as serial for PostgreSQL to generate the id.

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column(Order=1, TypeName="serial")]
public int ID { get; set; }

https://www.postgresql.org/docs/current/static/datatype-numeric.html#DATATYPE-SERIAL

LaTeX: Multiple authors in a two-column article

What about using a tabular inside \author{}, just like in IEEE macros:

\documentclass{article}
\begin{document}
\title{Hello, World}
\author{
\begin{tabular}[t]{c@{\extracolsep{8em}}c} 
I. M. Author  & M. Y. Coauthor \\
My Department & Coauthor Department \\ 
My Institute & Coauthor Institute \\
email, address & email, address
\end{tabular}
}
\maketitle    
\end{document}

This will produce two columns authors with any documentclass.

Results:

enter image description here

Simple calculations for working with lat/lon and km distance?

http://www.jstott.me.uk/jcoord/ - use this library

            LatLng lld1 = new LatLng(40.718119, -73.995667);
            LatLng lld2 = new LatLng(51.499981, -0.125313);
            Double distance = lld1.distance(lld2);
            Log.d(TAG, "Distance in kilometers " + distance);

Render HTML to an image

All the answers here use third party libraries while rendering HTML to an image can be relatively simple in pure Javascript. There is was even an article about it on the canvas section on MDN.

The trick is this:

  • create an SVG with a foreignObject node containing your XHTML
  • set the src of an image to the data url of that SVG
  • drawImage onto the canvas
  • set canvas data to target image.src

_x000D_
_x000D_
const {body} = document_x000D_
_x000D_
const canvas = document.createElement('canvas')_x000D_
const ctx = canvas.getContext('2d')_x000D_
canvas.width = canvas.height = 100_x000D_
_x000D_
const tempImg = document.createElement('img')_x000D_
tempImg.addEventListener('load', onTempImageLoad)_x000D_
tempImg.src = 'data:image/svg+xml,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml"><style>em{color:red;}</style><em>I</em> lick <span>cheese</span></div></foreignObject></svg>')_x000D_
_x000D_
const targetImg = document.createElement('img')_x000D_
body.appendChild(targetImg)_x000D_
_x000D_
function onTempImageLoad(e){_x000D_
  ctx.drawImage(e.target, 0, 0)_x000D_
  targetImg.src = canvas.toDataURL()_x000D_
}
_x000D_
_x000D_
_x000D_

Some things to note

  • The HTML inside the SVG has to be XHTML
  • For security reasons the SVG as data url of an image acts as an isolated CSS scope for the HTML since no external sources can be loaded. So a Google font for instance has to be inlined using a tool like this one.
  • Even when the HTML inside the SVG exceeds the size of the image it wil draw onto the canvas correctly. But the actual height cannot be measured from that image. A fixed height solution will work just fine but dynamic height will require a bit more work. The best is to render the SVG data into an iframe (for isolated CSS scope) and use the resulting size for the canvas.

Python - round up to the nearest ten

You can use math.ceil() to round up, and then multiply by 10

import math

def roundup(x):
    return int(math.ceil(x / 10.0)) * 10

To use just do

>>roundup(45)
50

Xpath: select div that contains class AND whose specific child element contains text

You can use ancestor. I find that this is easier to read because the element you are actually selecting is at the end of the path.

//span[contains(text(),'someText')]/ancestor::div[contains(@class, 'measure-tab')]

Change first commit of project with Git?

git rebase -i allows you to conveniently edit any previous commits, except for the root commit. The following commands show you how to do this manually.

# tag the old root, "git rev-list ..." will return the hash of first commit
git tag root `git rev-list HEAD | tail -1`

# switch to a new branch pointing at the first commit
git checkout -b new-root root

# make any edits and then commit them with:
git commit --amend

# check out the previous branch (i.e. master)
git checkout @{-1}

# replace old root with amended version
git rebase --onto new-root root

# you might encounter merge conflicts, fix any conflicts and continue with:
# git rebase --continue

# delete the branch "new-root"
git branch -d new-root

# delete the tag "root"
git tag -d root

Return outside function error in Python

You can only return from inside a function and not from a loop.

It seems like your return should be outside the while loop, and your complete code should be inside a function.

def func():
    N = int(input("enter a positive integer:"))
    counter = 1
    while (N > 0):
        counter = counter * N
        N -= 1
    return counter  # de-indent this 4 spaces to the left.

print func()

And if those codes are not inside a function, then you don't need a return at all. Just print the value of counter outside the while loop.

How to set standard encoding in Visual Studio

I don't know of a global setting nither but you can try this:

  1. Save all Visual Studio templates in UTF-8
  2. Write a Visual Studio Macro/Addin that will listen to the DocumentSaved event and will save the file in UTF-8 format (if not already).
  3. Put a proxy on your source control that will make sure that new files are always UTF-8.

Provisioning Profiles menu item missing from Xcode 5

Try this:

Xcode >> Preferences >> Accounts

Checking if an input field is required using jQuery

The below code works fine but I am not sure about the radio button and dropdown list

$( '#form_id' ).submit( function( event ) {
    event.preventDefault();

    //validate fields
    var fail = false;
    var fail_log = '';
    var name;
    $( '#form_id' ).find( 'select, textarea, input' ).each(function(){
        if( ! $( this ).prop( 'required' )){

        } else {
            if ( ! $( this ).val() ) {
                fail = true;
                name = $( this ).attr( 'name' );
                fail_log += name + " is required \n";
            }

        }
    });

    //submit if fail never got set to true
    if ( ! fail ) {
        //process form here.
    } else {
        alert( fail_log );
    }

});

Convert absolute path into relative path given a current directory using Bash

Yet another solution, pure bash + GNU readlink for easy use in following context:

ln -s "$(relpath "$A" "$B")" "$B"

Edit: Make sure that "$B" is either not existing or no softlink in that case, else relpath follows this link which is not what you want!

This works in nearly all current Linux. If readlink -m does not work at your side, try readlink -f instead. See also https://gist.github.com/hilbix/1ec361d00a8178ae8ea0 for possible updates:

: relpath A B
# Calculate relative path from A to B, returns true on success
# Example: ln -s "$(relpath "$A" "$B")" "$B"
relpath()
{
local X Y A
# We can create dangling softlinks
X="$(readlink -m -- "$1")" || return
Y="$(readlink -m -- "$2")" || return
X="${X%/}/"
A=""
while   Y="${Y%/*}"
        [ ".${X#"$Y"/}" = ".$X" ]
do
        A="../$A"
done
X="$A${X#"$Y"/}"
X="${X%/}"
echo "${X:-.}"
}

Notes:

  • Care was taken that it is safe against unwanted shell meta character expansion, in case filenames contain * or ?.
  • The output is meant to be usable as the first argument to ln -s:
    • relpath / / gives . and not the empty string
    • relpath a a gives a, even if a happens to be a directory
  • Most common cases were tested to give reasonable results, too.
  • This solution uses string prefix matching, hence readlink is required to canonicalize paths.
  • Thanks to readlink -m it works for not yet existing paths, too.

On old systems, where readlink -m is not available, readlink -f fails if the file does not exist. So you probably need some workaround like this (untested!):

readlink_missing()
{
readlink -m -- "$1" && return
readlink -f -- "$1" && return
[ -e . ] && echo "$(readlink_missing "$(dirname "$1")")/$(basename "$1")"
}

This is not really quite correct in case $1 includes . or .. for nonexisting paths (like in /doesnotexist/./a), but it should cover most cases.

(Replace readlink -m -- above by readlink_missing.)

Edit because of the downvote follows

Here is a test, that this function, indeed, is correct:

check()
{
res="$(relpath "$2" "$1")"
[ ".$res" = ".$3" ] && return
printf ':WRONG: %-10q %-10q gives %q\nCORRECT %-10q %-10q gives %q\n' "$1" "$2" "$res" "$@"
}

#     TARGET   SOURCE         RESULT
check "/A/B/C" "/A"           ".."
check "/A/B/C" "/A.x"         "../../A.x"
check "/A/B/C" "/A/B"         "."
check "/A/B/C" "/A/B/C"       "C"
check "/A/B/C" "/A/B/C/D"     "C/D"
check "/A/B/C" "/A/B/C/D/E"   "C/D/E"
check "/A/B/C" "/A/B/D"       "D"
check "/A/B/C" "/A/B/D/E"     "D/E"
check "/A/B/C" "/A/D"         "../D"
check "/A/B/C" "/A/D/E"       "../D/E"
check "/A/B/C" "/D/E/F"       "../../D/E/F"

check "/foo/baz/moo" "/foo/bar" "../bar"

Puzzled? Well, these are the correct results! Even if you think it does not fit the question, here is the proof this is correct:

check "http://example.com/foo/baz/moo" "http://example.com/foo/bar" "../bar"

Without any doubt, ../bar is the exact and only correct relative path of the page bar seen from the page moo. Everything else would be plain wrong.

It is trivial to adopt the output to the question which apparently assumes, that current is a directory:

absolute="/foo/bar"
current="/foo/baz/foo"
relative="../$(relpath "$absolute" "$current")"

This returns exactly, what was asked for.

And before you raise an eyebrow, here is a bit more complex variant of relpath (spot the small difference), which should work for URL-Syntax, too (so a trailing / survives, thanks to some bash-magic):

# Calculate relative PATH to the given DEST from the given BASE
# In the URL case, both URLs must be absolute and have the same Scheme.
# The `SCHEME:` must not be present in the FS either.
# This way this routine works for file paths an
: relpathurl DEST BASE
relpathurl()
{
local X Y A
# We can create dangling softlinks
X="$(readlink -m -- "$1")" || return
Y="$(readlink -m -- "$2")" || return
X="${X%/}/${1#"${1%/}"}"
Y="${Y%/}${2#"${2%/}"}"
A=""
while   Y="${Y%/*}"
        [ ".${X#"$Y"/}" = ".$X" ]
do
        A="../$A"
done
X="$A${X#"$Y"/}"
X="${X%/}"
echo "${X:-.}"
}

And here are the checks just to make clear: It really works as told.

check()
{
res="$(relpathurl "$2" "$1")"
[ ".$res" = ".$3" ] && return
printf ':WRONG: %-10q %-10q gives %q\nCORRECT %-10q %-10q gives %q\n' "$1" "$2" "$res" "$@"
}

#     TARGET   SOURCE         RESULT
check "/A/B/C" "/A"           ".."
check "/A/B/C" "/A.x"         "../../A.x"
check "/A/B/C" "/A/B"         "."
check "/A/B/C" "/A/B/C"       "C"
check "/A/B/C" "/A/B/C/D"     "C/D"
check "/A/B/C" "/A/B/C/D/E"   "C/D/E"
check "/A/B/C" "/A/B/D"       "D"
check "/A/B/C" "/A/B/D/E"     "D/E"
check "/A/B/C" "/A/D"         "../D"
check "/A/B/C" "/A/D/E"       "../D/E"
check "/A/B/C" "/D/E/F"       "../../D/E/F"

check "/foo/baz/moo" "/foo/bar" "../bar"
check "http://example.com/foo/baz/moo" "http://example.com/foo/bar" "../bar"

check "http://example.com/foo/baz/moo/" "http://example.com/foo/bar" "../../bar"
check "http://example.com/foo/baz/moo"  "http://example.com/foo/bar/" "../bar/"
check "http://example.com/foo/baz/moo/"  "http://example.com/foo/bar/" "../../bar/"

And here is how this can be used to give the wanted result from the question:

absolute="/foo/bar"
current="/foo/baz/foo"
relative="$(relpathurl "$absolute" "$current/")"
echo "$relative"

If you find something which does not work, please let me know in the comments below. Thanks.

PS:

Why are the arguments of relpath "reversed" in contrast to all the other answers here?

If you change

Y="$(readlink -m -- "$2")" || return

to

Y="$(readlink -m -- "${2:-"$PWD"}")" || return

then you can leave the 2nd parameter away, such that the BASE is the current directory/URL/whatever. That's only the Unix principle, as usual.

Java simple code: java.net.SocketException: Unexpected end of file from server

Most likely the headers you are setting is incorrect or not acceptable.

Example: connnection.setRequestProperty("content-type", "application/json");

gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now

cd /Whatever/Directory/Path/The/File/Is/In

chmod +x xampp-linux-x64-7.0.6-0-installer.run

sudo ./xampp-linux-x64-7.0.6-0-installer.run

It works

For more information refer https://forums.linuxmint.com/viewtopic.php?t=223639

Pass a data.frame column name to a function

With dplyr it's now also possible to access a specific column of a dataframe by simply using double curly braces {{...}} around the desired column name within the function body, e.g. for col_name:

library(tidyverse)

fun <- function(df, col_name){
   df %>% 
     filter({{col_name}} == "test_string")
} 

Rename multiple files based on pattern in Unix

It was much easier (on my Mac) to do this in Ruby. Here are 2 examples:

# for your fgh example. renames all files from "fgh..." to "jkl..."
files = Dir['fgh*']

files.each do |f|
  f2 = f.gsub('fgh', 'jkl')
  system("mv #{f} #{f2}")
end

# renames all files in directory from "021roman.rb" to "021_roman.rb"
files = Dir['*rb'].select {|f| f =~ /^[0-9]{3}[a-zA-Z]+/}

files.each do |f|
  f1 = f.clone
  f2 = f.insert(3, '_')
  system("mv #{f1} #{f2}")
end

Determine when a ViewPager changes pages

ViewPager.setOnPageChangeListener is deprecated now. You now need to use ViewPager.addOnPageChangeListener instead.

for example,

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

Function stoi not declared

In comments under another answer, you indicated you are using a dodgy version of g++ under MS Windows.

In this case, -std=c++11 as suggested by the top answer would still not fix the problem.

Please see the following thread which does discuss your situation: std::stoi doesn't exist in g++ 4.6.1 on MinGW

Create a button with rounded border

Use OutlineButton instead of FlatButton.

new OutlineButton(
  child: new Text("Button text"),
  onPressed: null,
  shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0))
)

How to list the tables in a SQLite database file that was opened with ATTACH?

According to the documentation, the equivalent of MySQLs' SHOW TABLES; is:

The ".tables" command is similar to setting list mode then executing the following query:

SELECT name FROM sqlite_master
  WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%'
UNION ALL
SELECT name FROM sqlite_temp_master
  WHERE type IN ('table','view')
ORDER BY 1;

However, if you are checking if a single table exists (or to get its details), see @LuizGeron answer.

How to launch a Google Chrome Tab with specific URL using C#

// open in default browser
Process.Start("http://www.stackoverflow.net");

// open in Internet Explorer
Process.Start("iexplore", @"http://www.stackoverflow.net/");

// open in Firefox
Process.Start("firefox", @"http://www.stackoverflow.net/");

// open in Google Chrome
Process.Start("chrome", @"http://www.stackoverflow.net/");

How do I select and store columns greater than a number in pandas?

Sample DF:

In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))

In [80]: df
Out[80]:
    a   b   c
0   6  11  11
1  14   7   8
2  13   5  11
3  13   7  11
4  13   5   9
5   5  11   9
6   9   8   6
7   5  11  10
8   8  10  14
9   7  14  13

present only those rows where b > 10

In [81]: df[df.b > 10]
Out[81]:
   a   b   c
0  6  11  11
5  5  11   9
7  5  11  10
9  7  14  13

Minimums (for all columns) for the rows satisfying b > 10 condition

In [82]: df[df.b > 10].min()
Out[82]:
a     5
b    11
c     9
dtype: int32

Minimum (for the b column) for the rows satisfying b > 10 condition

In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11

UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25

package sn;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendEmail {
  public static void main(String[] args) {
    final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
 // Get a Properties object
    Properties props = System.getProperties();
    props.setProperty("mail.smtp.host", "smtp.gmail.com");
    props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.setProperty("mail.smtp.socketFactory.fallback", "false");
    props.setProperty("mail.smtp.port", "465");
    props.setProperty("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.auth", "true");
    props.put("mail.debug", "true");
    props.put("mail.store.protocol", "pop3");
    props.put("mail.transport.protocol", "smtp");
    final String username = "[email protected]";//
    final String password = "0000000";
    try{
      Session session = Session.getDefaultInstance(props, 
                          new Authenticator(){
                             protected PasswordAuthentication getPasswordAuthentication() {
                                return new PasswordAuthentication(username, password);
                             }});

   // -- Create a new message --
      Message msg = new MimeMessage(session);

   // -- Set the FROM and TO fields --
      msg.setFrom(new InternetAddress("[email protected]"));
      msg.setRecipients(Message.RecipientType.TO, 
                        InternetAddress.parse("[email protected]",false));
      msg.setSubject("Hello");
      msg.setText("How are you");
      msg.setSentDate(new Date());
      Transport.send(msg);
      System.out.println("Message sent.");
    }catch (MessagingException e){ 
      System.out.println("Erreur d'envoi, cause: " + e);
    }
  }
}

show dbs gives "Not Authorized to execute command" error

for me it worked by adding

1) "You can run the mongodb instance without username and password first.---OK

2) "Then you can add the user to the system database of the mongodb which is default one using the query below".---OK

db.createUser({
  user: "myUserAdmin",
  pwd: "abc123",
  roles: [ { role: "userAdminAnyDatabase", db: "admin" } ],
  mechanisms:[ "SCRAM-SHA-1" ] // I added this line

})

How to adjust gutter in Bootstrap 3 grid system?

You could create a CSS class for this and apply it to your columns. Since the gutter (spacing between columns) is controlled by padding in Bootstrap 3, adjust the padding accordingly:

.col {
  padding-right:7px;
  padding-left:7px;
}

Demo: http://bootply.com/93473

EDIT If you only want the spacing between columns you can select all cols except first and last like this..

.col:not(:first-child,:last-child) {
  padding-right:7px;
  padding-left:7px;
}

Updated Bootply

For Bootstrap 4 see: Remove gutter space for a specific div only

Get the generated SQL statement from a SqlCommand object?

Used part of Flapper's code for my solution, which returns the entire SQL string including parameter values to run in MS SQL SMS.

public string ParameterValueForSQL(SqlParameter sp)
    {
        string retval = "";

        switch (sp.SqlDbType)
        {
            case SqlDbType.Char:
            case SqlDbType.NChar:
            case SqlDbType.NText:
            case SqlDbType.NVarChar:
            case SqlDbType.Text:
            case SqlDbType.Time:
            case SqlDbType.VarChar:
            case SqlDbType.Xml:
            case SqlDbType.Date:
            case SqlDbType.DateTime:
            case SqlDbType.DateTime2:
            case SqlDbType.DateTimeOffset:
                if (sp.Value == DBNull.Value)
                {
                    retval = "NULL";
                }
                else
                {
                    retval = "'" + sp.Value.ToString().Replace("'", "''") + "'";
                }
                break;

            case SqlDbType.Bit:
                if (sp.Value == DBNull.Value)
                {
                    retval = "NULL";
                }
                else
                {
                    retval = ((bool)sp.Value == false) ? "0" : "1";
                }
                break;

            default:
                if (sp.Value == DBNull.Value)
                {
                    retval = "NULL";
                }
                else
                {
                    retval = sp.Value.ToString().Replace("'", "''");
                }
                break;
        }

        return retval;
    }


    public string CommandAsSql(SqlCommand sc)
    {
        string sql = sc.CommandText;

        sql = sql.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");
        sql = System.Text.RegularExpressions.Regex.Replace(sql, @"\s+", " ");

        foreach (SqlParameter sp in sc.Parameters)
        {
            string spName = sp.ParameterName;
            string spValue = ParameterValueForSQL(sp);
            sql = sql.Replace(spName, spValue);
        }

        sql = sql.Replace("= NULL", "IS NULL");
        sql = sql.Replace("!= NULL", "IS NOT NULL");
        return sql;
    }

Sys is undefined

Please please please do check that the Server has the correct time and date set...

After about wasting 6 hours, i read it somewhere...

The date and time for the server must be updated to work correctly...

otherwise you will get 'Sys' is undefined error.

How to compare dates in Java?

You can use Date.getTime() which:

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

This means you can compare them just like numbers:

if (date1.getTime() <= date.getTime() && date.getTime() <= date2.getTime()) {
    /*
     * date is between date1 and date2 (both inclusive)
     */
}

/*
 * when date1 = 2015-01-01 and date2 = 2015-01-10 then
 * returns true for:
 * 2015-01-01
 * 2015-01-01 00:00:01
 * 2015-01-02
 * 2015-01-10
 * returns false for:
 * 2014-12-31 23:59:59
 * 2015-01-10 00:00:01
 * 
 * if one or both dates are exclusive then change <= to <
 */

How to use Elasticsearch with MongoDB?

River is a good solution once you want to have a almost real time synchronization and general solution.

If you have data in MongoDB already and want to ship it very easily to Elasticsearch like "one-shot" you can try my package in Node.js https://github.com/itemsapi/elasticbulk.

It's using Node.js streams so you can import data from everything what is supporting streams (i.e. MongoDB, PostgreSQL, MySQL, JSON files, etc)

Example for MongoDB to Elasticsearch:

Install packages:

npm install elasticbulk
npm install mongoose
npm install bluebird

Create script i.e. script.js:

const elasticbulk = require('elasticbulk');
const mongoose = require('mongoose');
const Promise = require('bluebird');
mongoose.connect('mongodb://localhost/your_database_name', {
  useMongoClient: true
});

mongoose.Promise = Promise;

var Page = mongoose.model('Page', new mongoose.Schema({
  title: String,
  categories: Array
}), 'your_collection_name');

// stream query 
var stream = Page.find({
}, {title: 1, _id: 0, categories: 1}).limit(1500000).skip(0).batchSize(500).stream();

elasticbulk.import(stream, {
  index: 'my_index_name',
  type: 'my_type_name',
  host: 'localhost:9200',
})
.then(function(res) {
  console.log('Importing finished');
})

Ship your data:

node script.js

It's not extremely fast but it's working for millions of records (thanks to streams).

Regular Expression usage with ls

You don't say what shell you are using, but they generally don't support regular expressions that way, although there are common *nix CLI tools (grep, sed, etc) that do.

What shells like bash do support is globbing, which uses some similiar characters (eg, *) but is not the same thing.

Newer versions of bash do have a regular expression operator, =~:

for x in `ls`; do 
    if [[ $x =~ .+\..* ]]; then 
        echo $x; 
    fi; 
done

#1055 - Expression of SELECT list is not in GROUP BY clause and contains nonaggregated column this is incompatible with sql_mode=only_full_group_by

I had a struggle getting this to work i've tested it and it's working on lamp server mysql version 5.12

So, steps to success:

  1. sudo vim /etc/mysql/conf.d/mysql.cnf
  2. Scroll to the bottom of file Copy and paste

    [mysqld] sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

to the bottom of the file

  1. save and exit input mode
  2. sudo service mysql restart to restart MySQL.

Done!

How do files get into the External Dependencies in Visual Studio C++?

To resolve external dependencies within project. below things are important..
1. The compiler should know that where are header '.h' files located in workspace.
2. The linker able to find all specified  all '.lib' files & there names for current project.

So, Developer has to specify external dependencies for Project as below..

1. Select Project in Solution explorer.

2 . Project Properties -> Configuration Properties -> C/C++ -> General
specify all header files in "Additional Include Directories".

3.  Project Properties -> Configuration Properties -> Linker -> General
specify relative path for all lib files in "Additional Library Directories".

enter image description here enter image description here

Convert json to a C# array?

Yes, Json.Net is what you need. You basically want to deserialize a Json string into an array of objects.

See their examples:

string myJsonString = @"{
  "Name": "Apple",
  "Expiry": "\/Date(1230375600000+1300)\/",
  "Price": 3.99,
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ]
}";

// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);

Ansible: copy a directory content to another directory

I found a workaround for recursive copying from remote to remote :

- name: List files in /usr/share/easy-rsa
  find:
    path: /usr/share/easy-rsa
    recurse: yes
    file_type: any
  register: find_result

- name: Create the directories
  file:
    path: "{{ item.path | regex_replace('/usr/share/easy-rsa','/etc/easy-rsa') }}"
    state: directory
    mode: "{{ item.mode }}"
  with_items:
    - "{{ find_result.files }}"
  when:
    - item.isdir

- name: Copy the files
  copy:
    src: "{{ item.path }}"
    dest: "{{ item.path | regex_replace('/usr/share/easy-rsa','/etc/easy-rsa') }}"
    remote_src: yes
    mode: "{{ item.mode }}"
  with_items:
    - "{{ find_result.files }}"
  when:
    - item.isdir == False

How to make rectangular image appear circular with CSS

You can make it like that:

    <html>
<head>
    <style>
        .round {
            display:block;
            width: 55px;
            height: 55px;
            border-radius: 50%;
            overflow: hidden;
            padding:5px 4px;
        }
        .round img {
            width: 45px;
        }
    </style>
</head>
<body>
    <div class="round">
        <img src="image.jpg" />
    </div>
</body>

How to output loop.counter in python jinja template?

in python:

env = Environment(loader=FileSystemLoader("templates"))
env.globals["enumerate"] = enumerate

in template:

{% for k,v in enumerate(list) %}
{% endfor %}

Find files and tar them (with spaces)

If you have multiple files or directories and you want to zip them into independent *.gz file you can do this. Optional -type f -atime

find -name "httpd-log*.txt" -type f -mtime +1 -exec tar -vzcf {}.gz {} \;

This will compress

httpd-log01.txt
httpd-log02.txt

to

httpd-log01.txt.gz
httpd-log02.txt.gz

Best way to strip punctuation from a string

string.punctuation is ASCII only! A more correct (but also much slower) way is to use the unicodedata module:

# -*- coding: utf-8 -*-
from unicodedata import category
s = u'String — with -  «punctation »...'
s = ''.join(ch for ch in s if category(ch)[0] != 'P')
print 'stripped', s

You can generalize and strip other types of characters as well:

''.join(ch for ch in s if category(ch)[0] not in 'SP')

It will also strip characters like ~*+§$ which may or may not be "punctuation" depending on one's point of view.

Permission denied error while writing to a file in Python

Make sure that you have write permissions for that directory you were trying to create file by properties

Typing Greek letters etc. in Python plots

Why not just use the literal characters?

fig.gca().set_xlabel("wavelength, (Å)")
fig.gca().set_ylabel("?")

You might have to add this to the file if you are using python 2:

# -*- coding: utf-8 -*-
from __future__ import unicode literals  # or use u"unicode strings"

It might be easier to define constants for characters that are not easy to type on your keyboard.

ANGSTROM, LAMDBA = "Å?"

Then you can reuse them elsewhere.

fig.gca().set_xlabel("wavelength, (%s)" % ANGSTROM)
fig.gca().set_ylabel(LAMBDA)

QByteArray to QString

you can use QString::fromAscii()

QByteArray data = entity->getData();
QString s_data = QString::fromAscii(data.data());

with data() returning a char*

for QT5, you should use fromCString() instead, as fromAscii() is deprecated, see https://bugreports.qt-project.org/browse/QTBUG-21872 https://bugreports.qt.io/browse/QTBUG-21872

Angular Directive refresh on parameter change

angular.module('app').directive('conversation', function() {
    return {
        restrict: 'E',
        link: function ($scope, $elm, $attr) {
            $scope.$watch("some_prop", function (newValue, oldValue) {
                  var typeId = $attr.type-id;
                  // Your logic.
            });
        }
    };
}

How to add browse file button to Windows Form using C#

var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
    string fileToOpen = FD.FileName;

    System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);

    //OR

    System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
    //etc
}

Should I use Java's String.format() if performance is important?

Another perspective from Logging point of view Only.

I see a lot of discussion related to logging on this thread so thought of adding my experience in answer. May be someone will find it useful.

I guess the motivation of logging using formatter comes from avoiding the string concatenation. Basically, you do not want to have an overhead of string concat if you are not going to log it.

You do not really need to concat/format unless you want to log. Lets say if I define a method like this

public void logDebug(String... args, Throwable t) {
    if(debugOn) {
       // call concat methods for all args
       //log the final debug message
    }
}

In this approach the cancat/formatter is not really called at all if its a debug message and debugOn = false

Though it will still be better to use StringBuilder instead of formatter here. The main motivation is to avoid any of that.

At the same time I do not like adding "if" block for each logging statement since

  • It affects readability
  • Reduces coverage on my unit tests - thats confusing when you want to make sure every line is tested.

Therefore I prefer to create a logging utility class with methods like above and use it everywhere without worrying about performance hit and any other issues related to it.

Example of Mockito's argumentCaptor

The two main differences are:

  • when you capture even a single argument, you are able to make much more elaborate tests on this argument, and with more obvious code;
  • an ArgumentCaptor can capture more than once.

To illustrate the latter, say you have:

final ArgumentCaptor<Foo> captor = ArgumentCaptor.forClass(Foo.class);

verify(x, times(4)).someMethod(captor.capture()); // for instance

Then the captor will be able to give you access to all 4 arguments, which you can then perform assertions on separately.

This or any number of arguments in fact, since a VerificationMode is not limited to a fixed number of invocations; in any event, the captor will give you access to all of them, if you wish.

This also has the benefit that such tests are (imho) much easier to write than having to implement your own ArgumentMatchers -- particularly if you combine mockito with assertj.

Oh, and please consider using TestNG instead of JUnit.

Use jquery to set value of div tag

try this function $('div.total-title').text('test');

Fastest way to download a GitHub project

Another faster way of downloading a GitHub project would be to use the clone functionality with the --depth argument as:

git clone --depth=1 [email protected]:organization/your-repo.git

to perform a shallow clone.

Initial bytes incorrect after Java AES/CBC decryption

Lot of people including myself face lot of issues in making this work due to missing some information like, forgetting to convert to Base64, initialization vectors, character set, etc. So I thought of making a fully functional code.

Hope this will be useful to you all: To compile you need additional Apache Commons Codec jar, which is available here: http://commons.apache.org/proper/commons-codec/download_codec.cgi

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class Encryptor {
    public static String encrypt(String key, String initVector, String value) {
        try {
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            byte[] encrypted = cipher.doFinal(value.getBytes());
            System.out.println("encrypted string: "
                    + Base64.encodeBase64String(encrypted));

            return Base64.encodeBase64String(encrypted);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    public static String decrypt(String key, String initVector, String encrypted) {
        try {
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

            byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));

            return new String(original);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args) {
        String key = "Bar12345Bar12345"; // 128 bit key
        String initVector = "RandomInitVector"; // 16 bytes IV

        System.out.println(decrypt(key, initVector,
                encrypt(key, initVector, "Hello World")));
    }
}

Lombok annotations do not compile under Intellij idea

If you're using Intellij on Mac, this setup finally worked for me.

Installations: Intellij

  1. Go to Preferences, search for Plugins.
  2. Type "Lombok" in the plugin search box. Lombok is a non-bundled plugin, so it won't show at first.
  3. Click "Browse" to search for non-bundled plugins
  4. The "Lombok Plugin" should show up. Select it.
  5. Click the green "Install" button.
  6. Click the "Restart Intellij IDEA" button.

Settings:

  1. Enable Annotation processor

    • Go to Preferences -> Build, Execution,Deployment -->Preferences -> Compiler -> Annotation Processors
    • File -> Other Settings -> Default Settings -> Compiler -> Annotation Processors
  2. Check if Lombok plugin is enabled

    • IntelliJ IDEA-> Preferences -> Other Settings -> Lombok plugin -> Enable Lombok
  3. Add Lombok jar in Global Libraries and project dependencies.

    • File --> Project Structure --> Global libraries (Add lombok.jar)
  4. File --> Project Structure --> Project Settings --> Modules --> Dependencies Tab = check lombok

  5. Restart Intellij

Using Java with Microsoft Visual Studio 2012

IntegraStudio enables syntax coloring, building, debugging and finding definition and references (F12 and ALT-F12) for Java projects in Visual Studio.

How to view file history in Git?

TortoiseGit also provides a command line tool to do see the history of a file. Using PowerShell:

C:\Program` Files\TortoiseGit\bin\TortoiseGitProc.exe /command:log /path:"c:\path\to\your\file.txt"

How to unnest a nested list

Use itertools.chain:

itertools.chain(*iterables):

Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.

Example:

from itertools import chain

A = [[1,2], [3,4]]

print list(chain(*A))
# or better: (available since Python 2.6)
print list(chain.from_iterable(A))

The output is:

[1, 2, 3, 4]
[1, 2, 3, 4]

SELECT using 'CASE' in SQL

Try this.

SELECT 
  CASE 
     WHEN FRUIT = 'A' THEN 'APPLE'
     WHEN FRUIT = 'B' THEN 'BANANA'
     ELSE 'UNKNOWN FRUIT'
  END AS FRUIT
FROM FRUIT_TABLE;

How do I get a PHP class constructor to call its parent's parent's constructor?

You must use Grandpa::__construct(), there's no other shortcut for it. Also, this ruins the encapsulation of the Papa class - when reading or working on Papa, it should be safe to assume that the __construct() method will be called during construction, but the Kiddo class does not do this.

Why does an SSH remote command get fewer environment variables then when run manually?

Just export the environment variables you want above the check for a non-interactive shell in ~/.bashrc.

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

this works. thanks. I am injecting custom html and compile it using angular in the controller.

        var tableContent= '<div>Search: <input ng-model="searchText"></div>' 
                            +'<div class="table-heading">'
                            +    '<div class="table-col">Customer ID</div>'
                           + ' <div class="table-col" ng-click="vm.openDialog(c.CustomerId)">{{c.CustomerId}}</div>';

            $timeout(function () {
            var linkingFunction = $compile(tableContent);
            var elem = linkingFunction($scope);

            // You can then use the DOM element like normal.
            jQuery(tablePanel).append(elem);

            console.log("timeout");
        },100);

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

The GUI can be fickle at times. The error you got when using T-SQL is because you're trying to overwrite an existing database, but did not specify to overwrite/replace the existing database. The following might work:

Use Master
Go
RESTORE DATABASE Publications
  FROM DISK = 'C:\Publications_backup_2012_10_15_010004_5648316.bak'
  WITH 
    MOVE 'Publications' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS2008R2\MSSQL\DATA\Publications.mdf',--adjust path
    MOVE 'Publications_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS2008R2\MSSQL\DATA\Publications.ldf'
, REPLACE -- Add REPLACE to specify the existing database which should be overwritten.

Passing headers with axios POST request

You can also use interceptors to pass the headers

It can save you a lot of code

axios.interceptors.request.use(config => {
  if (config.method === 'POST' || config.method === 'PATCH' || config.method === 'PUT')
    config.headers['Content-Type'] = 'application/json;charset=utf-8';

  const accessToken = AuthService.getAccessToken();
  if (accessToken) config.headers.Authorization = 'Bearer ' + accessToken;

  return config;
});

Inserting Data into Hive Table

to insert ad-hoc value like (12,"xyz), do this:

insert into table foo select * from (select 12,"xyz")a;

Datatables - Setting column width

You can define sScrollX : "100%" to force dataTables to keep the column widths :

..
 sScrollX: "100%", //<-- here
 aoColumns : [
      { "sWidth": "100px"},
      { "sWidth": "100px"},
      { "sWidth": "100px"},
      { "sWidth": "100px"},
      { "sWidth": "100px"},
      { "sWidth": "100px"},
      { "sWidth": "100px"},
      { "sWidth": "100px"},
    ],
...

you can play with this fiddle -> http://jsfiddle.net/vuAEx/

WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter value

This is how it can be done using CASE:

DECLARE @myParam INT;
SET @myParam = 1;

SELECT * 
  FROM MyTable
 WHERE 'T' = CASE @myParam
             WHEN 1 THEN 
                CASE WHEN MyColumn IS NULL THEN 'T' END
             WHEN 2 THEN
                CASE WHEN MyColumn IS NOT NULL THEN 'T' END
             WHEN 3 THEN 'T' END;

Big O, how do you calculate/approximate it?

In addition to using the master method (or one of its specializations), I test my algorithms experimentally. This can't prove that any particular complexity class is achieved, but it can provide reassurance that the mathematical analysis is appropriate. To help with this reassurance, I use code coverage tools in conjunction with my experiments, to ensure that I'm exercising all the cases.

As a very simple example say you wanted to do a sanity check on the speed of the .NET framework's list sort. You could write something like the following, then analyze the results in Excel to make sure they did not exceed an n*log(n) curve.

In this example I measure the number of comparisons, but it's also prudent to examine the actual time required for each sample size. However then you must be even more careful that you are just measuring the algorithm and not including artifacts from your test infrastructure.

int nCmp = 0;
System.Random rnd = new System.Random();

// measure the time required to sort a list of n integers
void DoTest(int n)
{
   List<int> lst = new List<int>(n);
   for( int i=0; i<n; i++ )
      lst[i] = rnd.Next(0,1000);

   // as we sort, keep track of the number of comparisons performed!
   nCmp = 0;
   lst.Sort( delegate( int a, int b ) { nCmp++; return (a<b)?-1:((a>b)?1:0)); }

   System.Console.Writeline( "{0},{1}", n, nCmp );
}


// Perform measurement for a variety of sample sizes.
// It would be prudent to check multiple random samples of each size, but this is OK for a quick sanity check
for( int n = 0; n<1000; n++ )
   DoTest(n);

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

word-wrap break-word does not work in this example

to get the smart break (break-word) work well on different browsers, what worked for me was the following set of rules:

#elm {
    word-break:break-word; /* webkit/blink browsers */
    word-wrap:break-word; /* ie */
}
-moz-document url-prefix() {/* catch ff */
    #elm {
        word-break: break-all; /* in ff-  with no break-word we'll settle for break-all */
    }
}

Concatenating string and integer in python

No string formatting:

>> print 'Foo',0
Foo 0

Convert the values in a column into row names in an existing data frame

You can execute this in 2 simple statements:

row.names(samp) <- samp$names
samp[1] <- NULL

How to trigger click on page load?

You can do the following :-

$(document).ready(function(){
    $("#id").trigger("click");
});

How can I get a collection of keys in a JavaScript dictionary?

For new browsers: Object.keys( MY_DICTIONARY ) will return an array of keys. Else you may want to go the old school way:

var keys = []
for(var key in dic) keys.push( key );

login to remote using "mstsc /admin" with password

Save your username, password and sever name in an RDP file and run the RDP file from your script

jQuery change input text value

Just adding to Jason's answer, the . selector is only for classes. If you want to select something other than the element, id, or class, you need to wrap it in square brackets.

e.g.

$('element[attr=val]')

./xx.py: line 1: import: command not found

I've experienced the same problem and now I just found my solution to this issue.

#!/usr/bin/python

import sys
import os

os.system('meld "%s" "%s"' % (sys.argv[2], sys.argv[5]))

This is the code[1] for my case. When I tried this script I received error message like :

import: command not found

I found people talks about the shebang. As you see there is the shebang in my python code above. I tried these and those trials but didn't find a good solution.

I finally tried to type the shebang my self.

#!/usr/bin/python

and removed the copied one.

And my problem solved!!!

I copied the code from the internet[1].

And I guess there had been some unseeable(?) unseen special characters in the original copied shebang statement.

I use vim, sometimes I experience similar problems.. Especially when I copied some code snippet from the internet this kind of problems happen.. Web pages have some virus special characters!! I doubt. :-)

Journeyer

PS) I copied the code in Windows 7 - host OS - into the Windows clipboard and pasted it into my vim in Ubuntu - guest OS. VM is Oracle Virtual Machine.

[1] http://nathanhoad.net/how-to-meld-for-git-diffs-in-ubuntu-hardy

Registering for Push Notifications in Xcode 8/Swift 3.0?

Heads up, you should be using the main thread for this action.

let center = UNUserNotificationCenter.current()
center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
        if granted {
            DispatchQueue.main.async(execute: {
                UIApplication.shared.registerForRemoteNotifications()
            })
        }
    }

Programmatically saving image to Django ImageField

If you want to just "set" the actual filename, without incurring the overhead of loading and re-saving the file (!!), or resorting to using a charfield (!!!), you might want to try something like this --

model_instance.myfile = model_instance.myfile.field.attr_class(model_instance, model_instance.myfile.field, 'my-filename.jpg')

This will light up your model_instance.myfile.url and all the rest of them just as if you'd actually uploaded the file.

Like @t-stone says, what we really want, is to be able to set instance.myfile.path = 'my-filename.jpg', but Django doesn't currently support that.

In LINQ, select all values of property X where X != null

You can use the OfType operator. It ignores null values in the source sequence. Just use the same type as MyProperty and it won't filter out anything else.

// given:
// public T MyProperty { get; }
var nonNullItems = list.Select(x => x.MyProperty).OfType<T>();

I would advise against this though. If you want to pick non-null values, what can be more explicit than saying you want "the MyProperties from the list that are not null"?

PreparedStatement IN clause alternatives?

An unpleasant work-around, but certainly feasible is to use a nested query. Create a temporary table MYVALUES with a column in it. Insert your list of values into the MYVALUES table. Then execute

select my_column from my_table where search_column in ( SELECT value FROM MYVALUES )

Ugly, but a viable alternative if your list of values is very large.

This technique has the added advantage of potentially better query plans from the optimizer (check a page for multiple values, tablescan only once instead once per value, etc) may save on overhead if your database doesn't cache prepared statements. Your "INSERTS" would need to be done in batch and the MYVALUES table may need to be tweaked to have minimal locking or other high-overhead protections.

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

ArrayIndexOutOfBoundsException when using the ArrayList's iterator

You could also do a for loop as you would for an array but instead of array[i] you would use list.get(i)

for (int i = 0; i < list.size(); i++) {
    System.out.println(list.get(i));
}

Rails: Missing host to link to! Please provide :host parameter or set default_url_options[:host]

The host should be specified in each environment's config file. Eg:

config/environments/development.rb

See this question and this question.

concatenate char array in C

in rare cases when you can't use strncat, strcat or strcpy. And you don't have access to <string.h> so you can't use strlen. Also you maybe don't even know the size of the char arrays and you still want to concatenate because you got only pointers. Well, you can do old school malloc and count characters yourself like..

char *combineStrings(char* inputA, char* inputB) {
    size_t len = 0, lenB = 0;
    while(inputA[len] != '\0') len++;
    while(inputB[lenB] != '\0') lenB++;
    char* output = malloc(len+lenB);
    sprintf((char*)output,"%s%s",inputA,inputB);
    return output;
}

It just needs #include <stdio.h> which you will have most likely included already

Finding duplicate rows in SQL Server

Try

SELECT orgName, id, count(*) as dupes
FROM organizations
GROUP BY orgName, id
HAVING count(*) > 1;

What Language is Used To Develop Using Unity

i remember this from reading some articles about performance in unity from internet which awaring javascript users from using it in unity about really massive issues of using javascript in unity instead of C#, it says that C# is almost 4x faster than javascript!
i really appreciate that article b/c it saved my ass when i was about to start gaming, i dont mean that javascript it bad for unity developers , it is good but my advice could be that if you like using javascript, you should use it for simple small gamesNOT FOR BIG PROJECTS because it really can be a damn problem!

Adding a column to a dataframe in R

Even if that's a 7 years old question, people new to R should consider using the data.table, package.

A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.

vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]

Does JavaScript pass by reference?

Objects are always pass by reference and primitives by value. Just keep that parameter at the same address for objects.

Here's some code to illustrate what I mean (try it in a JavaScript sandbox such as https://js.do/).

Unfortunately you can't only retain the address of the parameter; you retain all the original member values as well.

a = { key: 'bevmo' };
testRetain(a);
document.write(' after function ');
document.write(a.key);


function testRetain (b)
{
    document.write(' arg0 is ');
    document.write(arguments[0].key);
    b.key = 'passed by reference';
    var retain = b; // Retaining the original address of the parameter

    // Address of left set to address of right, changes address of parameter
    b = {key: 'vons'}; // Right is a new object with a new address
    document.write(' arg0 is ');
    document.write(arguments[0].key);

    // Now retrieve the original address of the parameter for pass by reference
    b = retain;
    document.write(' arg0 is ');
    document.write(arguments[0].key);
}

Result:

arg0 is bevmo arg0 is vons arg0 is passed by reference after function passed by reference

What is define([ , function ]) in JavaScript?

define() is part of the AMD spec of js

See:

Edit: Also see Claudio's answer below. Likely the more relevant explanation.

How to extract text from a PDF file?

For extracting Text from PDF use below code

import PyPDF2
pdfFileObj = open('mypdf.pdf', 'rb')

pdfReader = PyPDF2.PdfFileReader(pdfFileObj)

print(pdfReader.numPages)

pageObj = pdfReader.getPage(0)

a = pageObj.extractText()

print(a)

Styling a input type=number

I modified @LcSalazar's answer a bit... it's still not perfect because the background of the default buttons can still be seen in both Firefox, Chrome & Opera (not tested in Safari); but clicking on the arrows still works

Notes:

  • Adding pointer-events: none; allows you to click through the overlapping button, but then you can not style the button while hovered.
  • The arrows are visible in Edge, but don't work because Edge doesn't use arrows. It only adds an "x" to clear the input.

_x000D_
_x000D_
.number-wrapper {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.number-wrapper:after,_x000D_
.number-wrapper:before {_x000D_
  position: absolute;_x000D_
  right: 5px;_x000D_
  width: 1.6em;_x000D_
  height: .9em;_x000D_
  font-size: 10px;_x000D_
  pointer-events: none;_x000D_
  background: #fff;_x000D_
}_x000D_
_x000D_
.number-wrapper:after {_x000D_
  color: blue;_x000D_
  content: "\25B2";_x000D_
  margin-top: 1px;_x000D_
}_x000D_
_x000D_
.number-wrapper:before {_x000D_
  color: red;_x000D_
  content: "\25BC";_x000D_
  margin-bottom: 5px;_x000D_
  bottom: -.5em;_x000D_
}
_x000D_
<span class='number-wrapper'>_x000D_
    <input type="number" />_x000D_
</span>
_x000D_
_x000D_
_x000D_

How do I check if a directory exists? "is_dir", "file_exists" or both?

This is an old, but still topical question. Just test with the is_dir() or file_exists() function for the presence of the . or .. file in the directory under test. Each directory must contain these files:

is_dir("path_to_directory/.");    

What are the differences between Deferred, Promise and Future in JavaScript?

A Promise represents a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers to an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise of having a value at some point in the future.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

The deferred.promise() method allows an asynchronous function to prevent other code from interfering with the progress or status of its internal request. The Promise exposes only the Deferred methods needed to attach additional handlers or determine the state (then, done, fail, always, pipe, progress, state and promise), but not ones that change the state (resolve, reject, notify, resolveWith, rejectWith, and notifyWith).

If target is provided, deferred.promise() will attach the methods onto it and then return this object rather than create a new one. This can be useful to attach the Promise behavior to an object that already exists.

If you are creating a Deferred, keep a reference to the Deferred so that it can be resolved or rejected at some point. Return only the Promise object via deferred.promise() so other code can register callbacks or inspect the current state.

Simply we can say that a Promise represents a value that is not yet known where as a Deferred represents work that is not yet finished.


enter image description here

List all tables in postgresql information_schema

If you want a quick and dirty one-liner query:

select * from information_schema.tables

You can run it directly in the Query tool without having to open psql.

(Other posts suggest nice more specific information_schema queries but as a newby, I am finding this one-liner query helps me get to grips with the table)

Launch custom android application from android browser

Hey I got the solution. I did not set the category as "Default". Also I was using the Main activity for the intent Data. Now i am using a different activity for the intent data. Thanks for the help. :)

AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?

Overriding the input directive does seem to do the job. I made some minor alterations to Dan Hunsaker's code:

  • Added a check for ngModel before trying to use $parse().assign() on fields without a ngModel attributes.
  • Corrected the assign() function param order.
app.directive('input', function ($parse) {
  return {
    restrict: 'E',
    require: '?ngModel',
    link: function (scope, element, attrs) {
      if (attrs.ngModel && attrs.value) {
        $parse(attrs.ngModel).assign(scope, attrs.value);
      }
    }
  };
});

Add legend to ggplot2 line plot

Since @Etienne asked how to do this without melting the data (which in general is the preferred method, but I recognize there may be some cases where that is not possible), I present the following alternative.

Start with a subset of the original data:

datos <-
structure(list(fecha = structure(c(1317452400, 1317538800, 1317625200, 
1317711600, 1317798000, 1317884400, 1317970800, 1318057200, 1318143600, 
1318230000, 1318316400, 1318402800, 1318489200, 1318575600, 1318662000, 
1318748400, 1318834800, 1318921200, 1319007600, 1319094000), class = c("POSIXct", 
"POSIXt"), tzone = ""), TempMax = c(26.58, 27.78, 27.9, 27.44, 
30.9, 30.44, 27.57, 25.71, 25.98, 26.84, 33.58, 30.7, 31.3, 27.18, 
26.58, 26.18, 25.19, 24.19, 27.65, 23.92), TempMedia = c(22.88, 
22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52, 19.71, 20.73, 
23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 20.45, 19.42, 19.97, 
19.61), TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75, 
16.88, 16.82, 14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01, 
16.95, 17.55, 15.21, 14.22, 16.42)), .Names = c("fecha", "TempMax", 
"TempMedia", "TempMin"), row.names = c(NA, 20L), class = "data.frame")

You can get the desired effect by (and this also cleans up the original plotting code):

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      breaks = c("TempMax", "TempMedia", "TempMin"),
                      values = c("red", "green", "blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

The idea is that each line is given a color by mapping the colour aesthetic to a constant string. Choosing the string which is what you want to appear in the legend is the easiest. The fact that in this case it is the same as the name of the y variable being plotted is not significant; it could be any set of strings. It is very important that this is inside the aes call; you are creating a mapping to this "variable".

scale_colour_manual can now map these strings to the appropriate colors. The result is enter image description here

In some cases, the mapping between the levels and colors needs to be made explicit by naming the values in the manual scale (thanks to @DaveRGP for pointing this out):

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      values = c("TempMedia"="green", "TempMax"="red", 
                                 "TempMin"="blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

(giving the same figure as before). With named values, the breaks can be used to set the order in the legend and any order can be used in the values.

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      breaks = c("TempMedia", "TempMax", "TempMin"),
                      values = c("TempMedia"="green", "TempMax"="red", 
                                 "TempMin"="blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

How do I view the Explain Plan in Oracle Sql developer?

Explain only shows how the optimizer thinks the query will execute.

To show the real plan, you will need to run the sql once. Then use the same session run the following:

@yoursql 
select * from table(dbms_xplan.display_cursor()) 

This way can show the real plan used during execution. There are several other ways in showing plan using dbms_xplan. You can Google with term "dbms_xplan".

How to use S_ISREG() and S_ISDIR() POSIX Macros?

[Posted on behalf of fossuser] Thanks to "mu is too short" I was able to fix the bug. Here is my working code has been edited in for those looking for a nice example (since I couldn't find any others online).

#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

void helper(DIR *, struct dirent *, struct stat, char *, int, char **);
void dircheck(DIR *, struct dirent *, struct stat, char *, int, char **);

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

  DIR *dip;
  struct dirent *dit;
  struct stat statbuf;
  char currentPath[FILENAME_MAX];
  int depth = 0; /*Used to correctly space output*/

  /*Open Current Directory*/
  if((dip = opendir(".")) == NULL)
    return errno;

  /*Store Current Working Directory in currentPath*/
  if((getcwd(currentPath, FILENAME_MAX)) == NULL)
    return errno;

  /*Read all items in directory*/
  while((dit = readdir(dip)) != NULL){

    /*Skips . and ..*/
    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
      continue;

    /*Correctly forms the path for stat and then resets it for rest of algorithm*/
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    if(stat(currentPath, &statbuf) == -1){
      perror("stat");
      return errno;
    }
    getcwd(currentPath, FILENAME_MAX);


    /*Checks if current item is of the type file (type 8) and no command line arguments*/
    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL)
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*If a command line argument is given, checks for filename match*/
    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL)
      if(strcmp(dit->d_name, argv[1]) == 0)
         printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*Checks if current item is of the type directory (type 4)*/
    if(S_ISDIR(statbuf.st_mode))
      dircheck(dip, dit, statbuf, currentPath, depth, argv);

  }
  closedir(dip);
  return 0;
}

/*Recursively called helper function*/
void helper(DIR *dip, struct dirent *dit, struct stat statbuf, 
        char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  if((dip = opendir(currentPath)) == NULL)
    printf("Error: Failed to open Directory ==> %s\n", currentPath);

  while((dit = readdir(dip)) != NULL){

    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
      continue;

    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    stat(currentPath, &statbuf);
    getcwd(currentPath, FILENAME_MAX);

    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL){
      for(i = 0; i < depth; i++)
    printf("    ");
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
    }

    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL){
      if(strcmp(dit->d_name, argv[1]) == 0){
    for(i = 0; i < depth; i++)
      printf("    ");
    printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
      }
    }

    if(S_ISDIR(statbuf.st_mode))
      dircheck(dip, dit, statbuf, currentPath, depth, argv);
  }
  /*Changing back here is necessary because of how stat is done*/
    chdir("..");
    closedir(dip);
}

void dircheck(DIR *dip, struct dirent *dit, struct stat statbuf, 
          char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  strcat(currentPath, "/");
  strcat(currentPath, dit->d_name);

  /*If two directories exist at the same level the path
    is built wrong and needs to be corrected*/
  if((chdir(currentPath)) == -1){
    chdir("..");
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);

    for(i = 0; i < depth; i++)
      printf ("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    depth++;
    helper(dip, dit, statbuf, currentPath, depth, argv);
  }

  else{
    for(i =0; i < depth; i++)
      printf("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    chdir(currentPath);
    depth++;
    helper(dip, dit, statbuf, currentPath, depth, argv);
  }
}

How to install Selenium WebDriver on Mac OS

First up you need to download Selenium jar files from http://www.seleniumhq.org/download/. Then you'd need an IDE, something like IntelliJ or Eclipse. Then you'll have to map your jar files to those IDEs. Then depending on which language/framework you choose, you'll have to download the relevant library files, for example, if you're using JUnit you'll have to download Junit 4.11 jar file. Finally don't forget to download the drivers for Chrome and Safari (firefox driver comes standard with selenium). Once done, you can start coding and testing your code with the browser of your choice.

How to have multiple conditions for one if statement in python

Might be a bit odd or bad practice but this is one way of going about it.

(arg1, arg2, arg3) = (1, 2, 3)

if (arg1 == 1)*(arg2 == 2)*(arg3 == 3):
    print('Example.')

Anything multiplied by 0 == 0. If any of these conditions fail then it evaluates to false.

Iterating through a golang map

For example,

package main

import "fmt"

func main() {
    type Map1 map[string]interface{}
    type Map2 map[string]int
    m := Map1{"foo": Map2{"first": 1}, "boo": Map2{"second": 2}}
    //m = map[foo:map[first: 1] boo: map[second: 2]]
    fmt.Println("m:", m)
    for k, v := range m {
        fmt.Println("k:", k, "v:", v)
    }
}

Output:

m: map[boo:map[second:2] foo:map[first:1]]
k: boo v: map[second:2]
k: foo v: map[first:1]

How to get WooCommerce order details

ONLY FOR WOOCOMMERCE VERSIONS 2.5.x AND 2.6.x

For WOOCOMMERCE VERSION 3.0+ see THIS UPDATE

Here is a custom function I have made, to make the things clear for you, related to get the data of an order ID. You will see all the different RAW outputs you can get and how to get the data you need…

Using print_r() function (or var_dump() function too) allow to output the raw data of an object or an array.

So first I output this data to show the object or the array hierarchy. Then I use different syntax depending on the type of that variable (string, array or object) to output the specific data needed.

IMPORTANT: With $order object you can use most of WC_order or WC_Abstract_Order methods (using the object syntax)…


Here is the code:

function get_order_details($order_id){

    // 1) Get the Order object
    $order = wc_get_order( $order_id );

    // OUTPUT
    echo '<h3>RAW OUTPUT OF THE ORDER OBJECT: </h3>';
    print_r($order);
    echo '<br><br>';
    echo '<h3>THE ORDER OBJECT (Using the object syntax notation):</h3>';
    echo '$order->order_type: ' . $order->order_type . '<br>';
    echo '$order->id: ' . $order->id . '<br>';
    echo '<h4>THE POST OBJECT:</h4>';
    echo '$order->post->ID: ' . $order->post->ID . '<br>';
    echo '$order->post->post_author: ' . $order->post->post_author . '<br>';
    echo '$order->post->post_date: ' . $order->post->post_date . '<br>';
    echo '$order->post->post_date_gmt: ' . $order->post->post_date_gmt . '<br>';
    echo '$order->post->post_content: ' . $order->post->post_content . '<br>';
    echo '$order->post->post_title: ' . $order->post->post_title . '<br>';
    echo '$order->post->post_excerpt: ' . $order->post->post_excerpt . '<br>';
    echo '$order->post->post_status: ' . $order->post->post_status . '<br>';
    echo '$order->post->comment_status: ' . $order->post->comment_status . '<br>';
    echo '$order->post->ping_status: ' . $order->post->ping_status . '<br>';
    echo '$order->post->post_password: ' . $order->post->post_password . '<br>';
    echo '$order->post->post_name: ' . $order->post->post_name . '<br>';
    echo '$order->post->to_ping: ' . $order->post->to_ping . '<br>';
    echo '$order->post->pinged: ' . $order->post->pinged . '<br>';
    echo '$order->post->post_modified: ' . $order->post->post_modified . '<br>';
    echo '$order->post->post_modified_gtm: ' . $order->post->post_modified_gtm . '<br>';
    echo '$order->post->post_content_filtered: ' . $order->post->post_content_filtered . '<br>';
    echo '$order->post->post_parent: ' . $order->post->post_parent . '<br>';
    echo '$order->post->guid: ' . $order->post->guid . '<br>';
    echo '$order->post->menu_order: ' . $order->post->menu_order . '<br>';
    echo '$order->post->post_type: ' . $order->post->post_type . '<br>';
    echo '$order->post->post_mime_type: ' . $order->post->post_mime_type . '<br>';
    echo '$order->post->comment_count: ' . $order->post->comment_count . '<br>';
    echo '$order->post->filter: ' . $order->post->filter . '<br>';
    echo '<h4>THE ORDER OBJECT (again):</h4>';
    echo '$order->order_date: ' . $order->order_date . '<br>';
    echo '$order->modified_date: ' . $order->modified_date . '<br>';
    echo '$order->customer_message: ' . $order->customer_message . '<br>';
    echo '$order->customer_note: ' . $order->customer_note . '<br>';
    echo '$order->post_status: ' . $order->post_status . '<br>';
    echo '$order->prices_include_tax: ' . $order->prices_include_tax . '<br>';
    echo '$order->tax_display_cart: ' . $order->tax_display_cart . '<br>';
    echo '$order->display_totals_ex_tax: ' . $order->display_totals_ex_tax . '<br>';
    echo '$order->display_cart_ex_tax: ' . $order->display_cart_ex_tax . '<br>';
    echo '$order->formatted_billing_address->protected: ' . $order->formatted_billing_address->protected . '<br>';
    echo '$order->formatted_shipping_address->protected: ' . $order->formatted_shipping_address->protected . '<br><br>';
    echo '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <br><br>';

    // 2) Get the Order meta data
    $order_meta = get_post_meta($order_id);

    echo '<h3>RAW OUTPUT OF THE ORDER META DATA (ARRAY): </h3>';
    print_r($order_meta);
    echo '<br><br>';
    echo '<h3>THE ORDER META DATA (Using the array syntax notation):</h3>';
    echo '$order_meta[_order_key][0]: ' . $order_meta[_order_key][0] . '<br>';
    echo '$order_meta[_order_currency][0]: ' . $order_meta[_order_currency][0] . '<br>';
    echo '$order_meta[_prices_include_tax][0]: ' . $order_meta[_prices_include_tax][0] . '<br>';
    echo '$order_meta[_customer_user][0]: ' . $order_meta[_customer_user][0] . '<br>';
    echo '$order_meta[_billing_first_name][0]: ' . $order_meta[_billing_first_name][0] . '<br><br>';
    echo 'And so on ……… <br><br>';
    echo '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <br><br>';

    // 3) Get the order items
    $items = $order->get_items();

    echo '<h3>RAW OUTPUT OF THE ORDER ITEMS DATA (ARRAY): </h3>';

    foreach ( $items as $item_id => $item_data ) {

        echo '<h4>RAW OUTPUT OF THE ORDER ITEM NUMBER: '. $item_id .'): </h4>';
        print_r($item_data);
        echo '<br><br>';
        echo 'Item ID: ' . $item_id. '<br>';
        echo '$item_data["product_id"] <i>(product ID)</i>: ' . $item_data['product_id'] . '<br>';
        echo '$item_data["name"] <i>(product Name)</i>: ' . $item_data['name'] . '<br>';

        // Using get_item_meta() method
        echo 'Item quantity <i>(product quantity)</i>: ' . $order->get_item_meta($item_id, '_qty', true) . '<br><br>';
        echo 'Item line total <i>(product quantity)</i>: ' . $order->get_item_meta($item_id, '_line_total', true) . '<br><br>';
        echo 'And so on ……… <br><br>';
        echo '- - - - - - - - - - - - - <br><br>';
    }
    echo '- - - - - - E N D - - - - - <br><br>';
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Usage (if your order ID is 159 for example):

get_order_details(159);

This code is tested and works.

Updated code on November 21, 2016

Concrete Javascript Regex for Accented Characters (Diacritics)

Which of these three approaches is most suited for the task?

Depends on the task :-) To match exactly all Latin characters and their accented versions, the Unicode ranges probably provide the best solution. They might be extended to all non-whitespace characters, which could be done using the \S character class.

I'm forcing a field in a UI to match the format: last_name, first_name (last [comma space] first)

The most basic problem I'm seeing here are not diacritics, but whitespaces. There are a few names that consist of multiple words, e.g. for titles. So you should go with the most generic, that is allowing everything but the comma that distinguishes first from last name:

/[^,]+,\s[^,]+/

But your second solution with the . character class is just as fine, you only might need to care about multiple commata then.

What are the time complexities of various data structures?

Arrays

  • Set, Check element at a particular index: O(1)
  • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
  • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
  • Similarly, Insert for arrays is basically Set as mentioned in the beginning

ArrayList:

  • Add: Amortized O(1)
  • Remove: O(n)
  • Contains: O(n)
  • Size: O(1)

Linked List:

  • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Doubly-Linked List:

  • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Stack:

  • Push: O(1)
  • Pop: O(1)
  • Top: O(1)
  • Search (Something like lookup, as a special operation): O(n) (I guess so)

Queue/Deque/Circular Queue:

  • Insert: O(1)
  • Remove: O(1)
  • Size: O(1)

Binary Search Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

Red-Black Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

Heap/PriorityQueue (min/max):

  • Find Min/Find Max: O(1)
  • Insert: O(log n)
  • Delete Min/Delete Max: O(log n)
  • Extract Min/Extract Max: O(log n)
  • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST

HashMap/Hashtable/HashSet:

  • Insert/Delete: O(1) amortized
  • Re-size/hash: O(n)
  • Contains: O(1)

Convert a String to int?

You can use the FromStr trait's from_str method, which is implemented for i32:

let my_num = i32::from_str("9").unwrap_or(0);

Check whether a string matches a regex in JS

You can try this, it works for me.

 <input type="text"  onchange="CheckValidAmount(this.value)" name="amount" required>

 <script type="text/javascript">
    function CheckValidAmount(amount) {          
       var a = /^(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+)?$/;
       if(amount.match(a)){
           alert("matches");
       }else{
        alert("does not match"); 
       }
    }
</script>

Authentication failed to bitbucket

I was trying the git push --all bitbucket call and it was throwing back the "fatal: Authentication failed for 'https://..." response. The solution that worked for me was to change the command to:

git push --all https://{username}@{url}

On Windows, this popped up a dialog that allowed me to enter my password and the push worked.

How to find if element with specific id exists or not

 var myEle = document.getElementById("myElement");
    if(myEle){
        var myEleValue= myEle.value;
    }

the return of getElementById is null if an element is not actually present inside the dom, so your if statement will fail, because null is considered a false value

jQuery move to anchor location on page load

Put this right before the closing Body tag at the bottom of the page.

<script>
    if (location.hash) {
        location.href = location.hash;
    }
</script>

jQuery is actually not required.

Why is MySQL InnoDB insert so slow?

things that speed up the inserts:

  • i had removed all keys from a table before large insert into empty table
  • then found i had a problem that the index did not fit in memory.
  • also found i had sync_binlog=0 (should be 1) even if binlog is not used.
  • also found i did not set innodb_buffer_pool_instances

How to define dimens.xml for every different screen size in android?

we want to see the changes of required view size in different screens.

We need to create a different values folders for different screens and put dimens.xml file based on screen densities.

I have taken one TextView and observed the changes when i changed dimens.xml in different values folders.

Please follow the process

normal - xhdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - xhdpi \ dimens.xml

nexus 5X ( 5.2" * 1080 * 1920 : 420dpi )

nexus 6P ( 5.7" * 1440 * 2560 : 560dpi)

nexus 6 ( 6.0" * 1440 * 2560 : 560dpi)

nexus 5 (5.0", 1080 1920 : xxhdpi)

nexus 4 (4.7", 768 * 1280 : xhdpi)

Galaxy nexus (4.7", 720 * 1280 : xhdpi)

4.65" 720p ( 720 * 1280 : xhdpi )

4.7" WXGA ( 1280 * 720 : Xhdpi )

Xlarge - xhdpi \ dimens.xml

The below devices can change the sizes of screens when we change the Xlarge - xhdpi \ dimens.xml

nexus 9 ( 8.9", 2048 * 1556 : xhdpi)

nexus 10 (10.1", 2560 * 1600 : xhdpi)

large - xhdpi \ dimens.xml

The below devices can change the sizes of screens when we change the large - xhdpi \ dimens.xml

nexus 7 ( 7.0", 1200 * 1920: xhdpi)

nexus 7 (2012) (7.0", 800 * 1280 : tvdpi)

The below screens are visible in " Search Generic Phones and Tablets "

large - mdpi \ dimens.xml

The below devices can change the sizes of screens when we change the large - mdpi \ dimens.xml

5.1" WVGA ( 480 * 800 : mdpi )

5.4" FWVGA ( 480 * 854 : mdpi )

7.0" WSVGA (Tablet) ( 1024 * 600 : mdpi )

normal - hdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - hdpi \ dimens.xml

nexus s ( 4.0", 480 * 800 : hdpi )

nexus one ( 3.7", 480 * 800: hdpi)

small - ldpi \ dimens.xml

The below devices can change the sizes of screens when we change the small - ldpi \ dimens.xml

2.7" QVGA Slider ( 240 * 320 : ldpi )

2.7" QVGA ( 240 * 320 : ldpi )

xlarge - mdpi \ dimens.xml

The below devices can change the sizes of screens when we change the xlarge - mdpi \ dimens.xml

10.1" WXGA ( tABLET) ( 1280 * 800 : MDPI )

normal - ldpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - ldpi \ dimens.xml

3.3" WQVGA ( 240 * 400 : LDPI )

3.4" WQVGA ( 240 * 432 : LDPI )

normal - hdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - hdpi \ dimens.xml

4.0" WVGA ( 480 * 800 : hdpi )

3.7" WVGA ( 480 * 800 : hdpi )

3.7" FWVGA Slider ( 480 * 854 : hdpi )

normal - mdpi \ dimens.xml

The below devices can change the sizes of screens when we change the normal - mdpi \ dimens.xml

3.2" HVGA Slider ( ADP1 ) ( 320 * 480 : MDPI )

3.2" QVGA ( ADP2 ) ( 320 * 480 : MDPI )

How to convert a Java String to an ASCII byte array?

I found the solution. Actually Base64 class is not available in Android. Link is given below for more information.

byte[] byteArray;                                                  
     byteArray= json.getBytes(StandardCharsets.US_ASCII);
    String encoded=Base64.encodeBytes(byteArray);
    userLogin(encoded);

Here is the link for Base64 class: http://androidcodemonkey.blogspot.com/2010/03/how-to-base64-encode-decode-android.html

How to return values in javascript

Javascript is duck typed, so you can create a small structure.

function myFunction(value1,value2,value3)
{         
     var myObject = new Object();
     myObject.value2 = somevalue2;
     myObject.value3 = somevalue3;
     return myObject;
}


var value = myFunction("1",value2,value3);

if(value.value2  && value.value3)
{
//Do some stuff
}

How can I calculate the number of lines changed between two commits in Git?

I just solved this problem for myself, so I'll share what I came up with. Here's the end result:

> git summary --since=yesterday
total: 114 file changes, 13800 insertions(+) 638 deletions(-)

The underlying command looks like this:

git log --numstat --format="" "$@" | awk '{files += 1}{ins += $1}{del += $2} END{print "total: "files" files, "ins" insertions(+) "del" deletions(-)"}'

Note the $@ in the log command to pass on your arguments such as --author="Brian" or --since=yesterday.

Escaping the awk to put it into a git alias was messy, so instead, I put it into an executable script on my path (~/bin/git-stat-sum), then used the script in the alias in my .gitconfig:

[alias]
    summary = !git-stat-sum \"$@\"

And it works really well. One last thing to note is that file changes is the number of changes to files, not the number of unique files changed. That's what I was looking for, but it may not be what you expect.

Here's another example or two

git summary --author=brian
git summary master..dev
# combine them as you like
git summary --author=brian master..dev
git summary --all

Really, you should be able to replace any git log command with git summary.

Running a command as Administrator using PowerShell?

Here is an addition to Shay Levi's suggestion (just add these lines at the beginning of a script):

if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))  
{  
  $arguments = "& '" +$myinvocation.mycommand.definition + "'"
  Start-Process powershell -Verb runAs -ArgumentList $arguments
  Break
}

This results in the current script being passed to a new powershell process in Administrator mode (if current User has access to Administrator mode and the script is not launched as Administrator).

selenium - chromedriver executable needs to be in PATH

Another way is download and unzip chromedriver and put 'chromedriver.exe' in C:\Python27\Scripts and then you need not to provide the path of driver, just

driver= webdriver.Chrome()

will work

Can testify that this also works for Python3.7.

A failure occurred while executing com.android.build.gradle.internal.tasks

If any one having this issue in flutter after adding firebase storage. Do flutter clean and re run it, it will work

keyCode values for numeric keypad?

Docs says the order of events related to the onkeyxxx event:

  1. onkeydown
  2. onkeypress
  3. onkeyup

If you use like below code, it fits with also backspace and enter user interactions. After you can do what you want in onKeyPress or onKeyUp events. Code block trigger event.preventDefault function if the value is not number,backspace or enter.

onInputKeyDown = event => {
    const { keyCode } = event;
    if (
      (keyCode >= 48 && keyCode <= 57) ||
      (keyCode >= 96 && keyCode <= 105) ||
      keyCode === 8 || //Backspace key
      keyCode === 13   //Enter key
    ) {
    } else {
      event.preventDefault();
    }
  };

How to add property to object in PHP >= 5.3 strict mode without generating error

Yes, is possible to dynamically add properties to a PHP object.

This is useful when a partial object is received from javascript.

JAVASCRIPT side:

var myObject = { name = "myName" };
$.ajax({ type: "POST", url: "index.php",
    data: myObject, dataType: "json",
    contentType: "application/json;charset=utf-8"
}).success(function(datareceived){
    if(datareceived.id >= 0 ) { /* the id property has dynamically added on server side via PHP */ }
});

PHP side:

$requestString = file_get_contents('php://input');
$myObject = json_decode($requestString); // same object as was sent in the ajax call
$myObject->id = 30; // This will dynamicaly add the id property to the myObject object

OR JUST SEND A DUMMY PROPERTY from javascript that you will fill in PHP.

Prevent jQuery UI dialog from setting focus to first textbox

I have a similar problem. I open an error dialog when validation fails and it grabs the focus, just like Flugan shows it in his answer. The problem is that even if no element inside the dialog is tabbable, the dialog itself is still focused. Here is the original unminified code from jquery-ui-1.8.23\js\jquery.ui.dialog.js:

// set focus to the first tabbable element in the content area or the first button
// if there are no tabbable elements, set focus on the dialog itself
$(self.element.find(':tabbable').get().concat(
  uiDialog.find('.ui-dialog-buttonpane :tabbable').get().concat(
    uiDialog.get()))).eq(0).focus();

The comment is theirs!

This is really bad for me for several reasons. The most annoying thing is that the first reaction of the user is to hit the backspace to delete the last character, but instead (s)he is prompted to leave the page, because the backspace is hit outside an input control.

I found that the following workaround works pretty good for me:

jqueryFocus = $.fn.focus;
$.fn.focus = function (delay, fn) {
  jqueryFocus.apply(this.filter(':not(.ui-dialog)'), arguments);
};

Interface naming in Java

Following good OO principles, your code should (as far as practical/possible) depend on abstractions rather than concrete classes. For example, it is generally better to write a method like this:

public void doSomething(Collection someStuff) {
    ...
}

than this:

public void doSomething(Vector someStuff) {
    ...
}

If you follow this idea, then I maintain that your code will be more readable if you give interfaces names like "User" and "BankAccount" (for example), rather than "IUser", "UserInterface", or other variations.

The only bits of code that should care about the actual concrete classes are the places where the concrete classes are constructed. Everything else should be written using the interfaces.

If you do this, then the "ugly" concrete class names like "UserImpl" should be safely hidden from the rest of the code, which can merrily go on using the "nice" interface names.

Extending the User model with custom fields in Django

Try this:

Create a model called Profile and reference the user with a OneToOneField and provide an option of related_name.

models.py

from django.db import models
from django.contrib.auth.models import *
from django.dispatch import receiver
from django.db.models.signals import post_save

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile')

    def __str__(self):
        return self.user.username

@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
    try:
        if created:
            Profile.objects.create(user=instance).save()
    except Exception as err:
        print('Error creating user profile!')

Now to directly access the profile using a User object you can use the related_name.

views.py

from django.http import HttpResponse

def home(request):
    profile = f'profile of {request.user.user_profile}'
    return HttpResponse(profile)

Making heatmap from pandas DataFrame

You want matplotlib.pcolor:

import numpy as np 
from pandas import DataFrame
import matplotlib.pyplot as plt

index = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
columns = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=index, columns=columns)

plt.pcolor(df)
plt.yticks(np.arange(0.5, len(df.index), 1), df.index)
plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)
plt.show()

This gives:

Output sample

How do I return the SQL data types from my query?

select COLUMN_NAME, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH 
from INFORMATION_SCHEMA.COLUMNS 
where TABLE_NAME='yourTable';

jquery find class and get the value

You can get value of id,name or value in this way. class name my_class

 var id_value = $('.my_class').$(this).attr('id'); //get id value
 var name_value = $('.my_class').$(this).attr('name'); //get name value
 var value = $('.my_class').$(this).attr('value'); //get value any input or tag

Duplicate keys in .NET dictionaries?

Since the new C# (I belive it's from 7.0), you can also do something like this:

var duplicatedDictionaryExample = new List<(string Key, string Value)> { ("", "") ... }

and you are using it as a standard List, but with two values named whatever you want

foreach(var entry in duplicatedDictionaryExample)
{ 
    // do something with the values
    entry.Key;
    entry.Value;
}

How to import an existing project from GitHub into Android Studio

You can directly import github projects into Android Studio. File -> New -> Project from Version Control -> GitHub. Then enter your github username and password.Select the repository and hit clone.

The github repo will be created as a new project in android studio.

How to view transaction logs in SQL Server 2008

I accidentally deleted a whole bunch of data in the wrong environment and this post was one of the first ones I found.

Because I was simultaneously panicking and searching for a solution, I went for the first thing I saw - ApexSQL Logs, which was $2000 which was an acceptable cost.

However, I've since found out that Toad for Sql Server can generate undo scripts from transaction logs and it is only $655.

Lastly, found an even cheaper option SysToolsGroup Log Analyzer and it is only $300.

How to right-align form input boxes?

input { float: right; clear: both; }

Warning - Build path specifies execution environment J2SE-1.4

In Eclipse from your project:

  1. Right-click on your project
  2. Click Properties
  3. Java build path: Libraries; Remove the "JRE System Library[J2SE 1.4]"
  4. Click Add Library -> JRE System Library
  5. Select the new "Execution Environment" or Workspace default JRE

How can I enable CORS on Django REST Framework

pip install django-cors-headers

and then add it to your installed apps:

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

You will also need to add a middleware class to listen in on responses:

MIDDLEWARE_CLASSES = (
    ...
    'corsheaders.middleware.CorsMiddleware',  
    'django.middleware.common.CommonMiddleware',  
    ...
)

CORS_ORIGIN_ALLOW_ALL = True # If this is used then `CORS_ORIGIN_WHITELIST` will not have any effect
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = [
    'http://localhost:3030',
] # If this is used, then not need to use `CORS_ORIGIN_ALLOW_ALL = True`
CORS_ORIGIN_REGEX_WHITELIST = [
    'http://localhost:3030',
]

more details: https://github.com/ottoyiu/django-cors-headers/#configuration

read the official documentation can resolve almost all problem

How to delete from a table where ID is in a list of IDs?

Your question almost spells the SQL for this:

DELETE FROM table WHERE id IN (1, 4, 6, 7)

"Automatic" vs "Automatic (Delayed start)"

In short, services set to Automatic will start during the boot process, while services set to start as Delayed will start shortly after boot.

Starting your service Delayed improves the boot performance of your server and has security benefits which are outlined in the article Adriano linked to in the comments.

Update: "shortly after boot" is actually 2 minutes after the last "automatic" service has started, by default. This can be configured by a registry key, according to Windows Internals and other sources (3,4).

The registry keys of interest (At least in some versions of windows) are:

  • HKLM\SYSTEM\CurrentControlSet\services\<service name>\DelayedAutostart will have the value 1 if delayed, 0 if not.
  • HKLM\SYSTEM\CurrentControlSet\services\AutoStartDelay or HKLM\SYSTEM\CurrentControlSet\Control\AutoStartDelay (on Windows 10): decimal number of seconds to wait, may need to create this one. Applies globally to all Delayed services.

In Javascript/jQuery what does (e) mean?

In jQuery e short for event, the current event object. It's usually passed as a parameter for the event function to be fired.

Demo: jQuery Events

In the demo I used e

$("img").on("click dblclick mouseover mouseout",function(e){
        $("h1").html("Event: " + e.type);
}); 

I may as well have used event

 $("img").on("click dblclick mouseover mouseout",function(event){
            $("h1").html("Event: " + event.type);
    }); 

Same thing!

Programmers are lazy we use a lot of shorthand, partly it decreases our work, partly is helps with readability. Understanding that will help you understand the mentality of writing code.

Get source JARs from Maven repository

Maven repositories do provide simple way to download sources jar.

I will explain it using a demonstration for "spring-boot-actuator-autoconfigure".

  1. Go to maven repository - https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-actuator-autoconfigure
  2. The page lists various versions. Click-on to desired one, let's say, 2.1.6.RELEASE - https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-actuator-autoconfigure/2.1.6.RELEASE
  3. The page have link "View All" next to "Files". Click it - https://repo1.maven.org/maven2/org/springframework/boot/spring-boot-actuator-autoconfigure/2.1.6.RELEASE/
  4. The page lists various files including the one for sources - https://repo1.maven.org/maven2/org/springframework/boot/spring-boot-actuator-autoconfigure/2.1.6.RELEASE/spring-boot-actuator-autoconfigure-2.1.6.RELEASE-sources.jar

Otherwise, you can always "git clone" the repo from github, if its there and get the specific code.

As explained by others, you can use "mvn dependency:sources" command the get and generate sources jar for the dependency you are using.

Note: Some dependencies will not have sources.jar, as those contains no source code but a pom file. e.g. spring-boot-starter-actuator. As in this case:

Starter POMs are a set of convenient dependency descriptors that you can include in your application. You get a one-stop-shop for all the Spring and related technology that you need, without having to hunt through sample code and copy paste loads of dependency descriptors.

Reference: Intro to Spring Boot Starters

How to deal with floating point number precision in JavaScript?

This works for me:

function round_up( value, precision ) { 
    var pow = Math.pow ( 10, precision ); 
    return ( Math.ceil ( pow * value ) + Math.ceil ( pow * value - Math.ceil ( pow * value ) ) ) / pow; 
}

round_up(341.536, 2); // 341.54

Rails: Default sort order for a rails model?

A quick update to Michael's excellent answer above.

For Rails 4.0+ you need to put your sort in a block like this:

class Book < ActiveRecord::Base
  default_scope { order('created_at DESC') }
end

Notice that the order statement is placed in a block denoted by the curly braces.

They changed it because it was too easy to pass in something dynamic (like the current time). This removes the problem because the block is evaluated at runtime. If you don't use a block you'll get this error:

Support for calling #default_scope without a block is removed. For example instead of default_scope where(color: 'red'), please use default_scope { where(color: 'red') }. (Alternatively you can just redefine self.default_scope.)

As @Dan mentions in his comment below, you can do a more rubyish syntax like this:

class Book < ActiveRecord::Base
  default_scope { order(created_at: :desc) }
end

or with multiple columns:

class Book < ActiveRecord::Base
  default_scope { order({begin_date: :desc}, :name) }
end

Thanks @Dan!

Is there a function in python to split a word into a list?

def count(): list = 'oixfjhibokxnjfklmhjpxesriktglanwekgfvnk'

word_list = []
# dict = {}
for i in range(len(list)):
    word_list.append(list[i])
# word_list1 = sorted(word_list)
for i in range(len(word_list) - 1, 0, -1):
    for j in range(i):
        if word_list[j] > word_list[j + 1]:
            temp = word_list[j]
            word_list[j] = word_list[j + 1]
            word_list[j + 1] = temp
print("final count of arrival of each letter is : \n", dict(map(lambda x: (x, word_list.count(x)), word_list)))

Simple and clean way to convert JSON string to Object in Swift

For iOS 10 & Swift 3, using Alamofire & Gloss:

Alamofire.request("http://localhost:8080/category/en").responseJSON { response in

if let data = response.data {

    if let categories = [Category].from(data: response.data) {

        self.categories = categories

        self.categoryCollectionView.reloadData()
    } else {

        print("Casting error")
    }
  } else {

    print("Data is null")
  }
}

and here is the Category class

import Gloss

struct Category: Decodable {

    let categoryId: Int?
    let name: String?
    let image: String?

    init?(json: JSON) {
        self.categoryId = "categoryId" <~~ json
        self.name = "name" <~~ json
        self.image = "image" <~~ json
    }
}

IMO, this is by far the most elegant solution.

I want to add a JSONObject to a JSONArray and that JSONArray included in other JSONObject

org.json.simple.JSONArray resultantJson = new org.json.simple.JSONArray();

        org.json.JSONArray o1 = new org.json.JSONArray("[{\"one\":[],\"two\":\"abc\"}]");
        org.json.JSONArray o2 = new org.json.JSONArray("[{\"three\":[1,2],\"four\":\"def\"}]");


        resultantJson.addAll(o1.toList());
        resultantJson.addAll(o2.toList());

Sqlite in chrome

Chrome supports WebDatabase API (which is powered by sqlite), but looks like W3C stopped its development.

Find a class somewhere inside dozens of JAR files?

Just use FindClassInJars util, it's a simple swing program, but useful. You can check source code or download jar file at http://code.google.com/p/find-class-in-jars/

How can I get query string values in JavaScript?

Here's an extended version of Andy E's linked "Handle array-style query strings"-version. Fixed a bug (?key=1&key[]=2&key[]=3; 1 is lost and replaced with [2,3]), made a few minor performance improvements (re-decoding of values, recalculating "[" position, etc.) and added a number of improvements (functionalized, support for ?key=1&key=2, support for ; delimiters). I left the variables annoyingly short, but added comments galore to make them readable (oh, and I reused v within the local functions, sorry if that is confusing ;).

It will handle the following querystring...

?test=Hello&person=neek&person[]=jeff&person[]=jim&person[extra]=john&test3&nocache=1398914891264

...making it into an object that looks like...

{
    "test": "Hello",
    "person": {
        "0": "neek",
        "1": "jeff",
        "2": "jim",
        "length": 3,
        "extra": "john"
    },
    "test3": "",
    "nocache": "1398914891264"
}

As you can see above, this version handles some measure of "malformed" arrays, i.e. - person=neek&person[]=jeff&person[]=jim or person=neek&person=jeff&person=jim as the key is identifiable and valid (at least in dotNet's NameValueCollection.Add):

If the specified key already exists in the target NameValueCollection instance, the specified value is added to the existing comma-separated list of values in the form "value1,value2,value3".

It seems the jury is somewhat out on repeated keys as there is no spec. In this case, multiple keys are stored as an (fake)array. But do note that I do not process values based on commas into arrays.

The code:

getQueryStringKey = function(key) {
    return getQueryStringAsObject()[key];
};


getQueryStringAsObject = function() {
    var b, cv, e, k, ma, sk, v, r = {},
        d = function (v) { return decodeURIComponent(v).replace(/\+/g, " "); }, //# d(ecode) the v(alue)
        q = window.location.search.substring(1), //# suggested: q = decodeURIComponent(window.location.search.substring(1)),
        s = /([^&;=]+)=?([^&;]*)/g //# original regex that does not allow for ; as a delimiter:   /([^&=]+)=?([^&]*)/g
    ;

    //# ma(make array) out of the v(alue)
    ma = function(v) {
        //# If the passed v(alue) hasn't been setup as an object
        if (typeof v != "object") {
            //# Grab the cv(current value) then setup the v(alue) as an object
            cv = v;
            v = {};
            v.length = 0;

            //# If there was a cv(current value), .push it into the new v(alue)'s array
            //#     NOTE: This may or may not be 100% logical to do... but it's better than loosing the original value
            if (cv) { Array.prototype.push.call(v, cv); }
        }
        return v;
    };

    //# While we still have key-value e(ntries) from the q(uerystring) via the s(earch regex)...
    while (e = s.exec(q)) { //# while((e = s.exec(q)) !== null) {
        //# Collect the open b(racket) location (if any) then set the d(ecoded) v(alue) from the above split key-value e(ntry) 
        b = e[1].indexOf("[");
        v = d(e[2]);

        //# As long as this is NOT a hash[]-style key-value e(ntry)
        if (b < 0) { //# b == "-1"
            //# d(ecode) the simple k(ey)
            k = d(e[1]);

            //# If the k(ey) already exists
            if (r[k]) {
                //# ma(make array) out of the k(ey) then .push the v(alue) into the k(ey)'s array in the r(eturn value)
                r[k] = ma(r[k]);
                Array.prototype.push.call(r[k], v);
            }
            //# Else this is a new k(ey), so just add the k(ey)/v(alue) into the r(eturn value)
            else {
                r[k] = v;
            }
        }
        //# Else we've got ourselves a hash[]-style key-value e(ntry) 
        else {
            //# Collect the d(ecoded) k(ey) and the d(ecoded) sk(sub-key) based on the b(racket) locations
            k = d(e[1].slice(0, b));
            sk = d(e[1].slice(b + 1, e[1].indexOf("]", b)));

            //# ma(make array) out of the k(ey) 
            r[k] = ma(r[k]);

            //# If we have a sk(sub-key), plug the v(alue) into it
            if (sk) { r[k][sk] = v; }
            //# Else .push the v(alue) into the k(ey)'s array
            else { Array.prototype.push.call(r[k], v); }
        }
    }

    //# Return the r(eturn value)
    return r;
};

How to link html pages in same or different folders?

You can go up a folder in the hierarchy by using

../

So to get to folder /webroot/site/pages/folder2/mypage.htm from /webroot/site/pages/folder1/myotherpage.htm your link would look like this:

<a href="../folder2/mypage.htm">Link to My Page</a>

Default values in a C Struct

How about something like:

struct foo bar;
update(init_id(42, init_dont_care(&bar)));

with:

struct foo* init_dont_care(struct foo* bar) {
  bar->id = dont_care;
  bar->route = dont_care;
  bar->backup_route = dont_care;
  bar->current_route = dont_care;
  return bar;
}

and:

struct foo* init_id(int id, struct foo* bar) {
  bar->id = id;
  return bar;
}

and correspondingly:

struct foo* init_route(int route, struct foo* bar);
struct foo* init_backup_route(int backup_route, struct foo* bar);
struct foo* init_current_route(int current_route, struct foo* bar);

In C++, a similar pattern has a name which I don't remember just now.

EDIT: It's called the Named Parameter Idiom.

Python Anaconda - How to Safely Uninstall

In my case Anaconda3 was not installed in home directory. Instead, it was installed in root. Therefore, I had to do the following to get it uninstalled:

sudo rm -rf /anaconda3/bin/python

Is it possible to set async:false to $.getJSON call

In my case, Jay D is right. I have to add this before the call.

$.ajaxSetup({
    async: false
});

In my previous code, I have this:

var jsonData= (function() {
    var result;
    $.ajax({
        type:'GET',
        url:'data.txt',
        dataType:'json',
        async:false,
        success:function(data){
            result = data;
        }
    });
    return result;
})();
alert(JSON.stringify(jsonData));

It works find. Then I change to

var jsonData= (function() {
    var result;
    $.getJSON('data.txt', {}, function(data){
      result = data;
    });
    return result;
})();
alert(JSON.stringify(jsonData));

The alert is undefined.

If I add those three lines, the alert shows the data again.

$.ajaxSetup({
    async: false
});
var jsonData= (function() {
    var result;
    $.getJSON('data.txt', {}, function(data){
      result = data;
    });
    return result;
})();
alert(JSON.stringify(jsonData));

react-router scroll to top on every transition

My solution: a component that I'm using in my screens components (where I want a scroll to top).

import { useLayoutEffect } from 'react';

const ScrollToTop = () => {
    useLayoutEffect(() => {
        window.scrollTo(0, 0);
    }, []);

    return null;
};

export default ScrollToTop;

This preserves scroll position when going back. Using useEffect() was buggy for me, when going back the document would scroll to top and also had a blink effect when route was changed in an already scrolled document.

HTTP Ajax Request via HTTPS Page

Still, this can be done with the following steps:

  1. send an https ajax request to your web-site (the same domain)

    jQuery.ajax({
        'url'      : '//same_domain.com/ajax_receiver.php',
        'type'     : 'get',
        'data'     : {'foo' : 'bar'},
        'success'  : function(response) {
            console.log('Successful request');
        }
    }).fail(function(xhr, err) {
        console.error('Request error');
    });
    
  2. get ajax request, for example, by php, and make a CURL get request to any desired website via http.

    use linslin\yii2\curl;
    $curl = new curl\Curl();
    $curl->get('http://example.com');
    

Getting net::ERR_UNKNOWN_URL_SCHEME while calling telephone number from HTML page in Android

The following should work and not require any permissions in the manifest (basically override shouldOverrideUrlLoading and handle links separately from tel, mailto, etc.):

    mWebView = (WebView) findViewById(R.id.web_view);

    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    mWebView.setWebViewClient(new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if( url.startsWith("http:") || url.startsWith("https:") ) {
                return false;
            }

            // Otherwise allow the OS to handle things like tel, mailto, etc.
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity( intent );
            return true;
        }
    });
    mWebView.loadUrl(url);

Also, note that in the above snippet I am enabling JavaScript, which you will also most likely want, but if for some reason you don't, just remove those 2 lines.

VS 2017 Metadata file '.dll could not be found

Double check the name of your project folder. In my case my project folder was named with spaces in it. When I cloned the project from Team Foundation Server using git bash the spaces in the folder name were converted to: "%20". Changing those back to spaces fixed the problem for me.

How to get C# Enum description from value?

You can't easily do this in a generic way: you can only convert an integer to a specific type of enum. As Nicholas has shown, this is a trivial cast if you only care about one kind of enum, but if you want to write a generic method that can handle different kinds of enums, things get a bit more complicated. You want a method along the lines of:

public static string GetEnumDescription<TEnum>(int value)
{
  return GetEnumDescription((Enum)((TEnum)value));  // error!
}

but this results in a compiler error that "int can't be converted to TEnum" (and if you work around this, that "TEnum can't be converted to Enum"). So you need to fool the compiler by inserting casts to object:

public static string GetEnumDescription<TEnum>(int value)
{
  return GetEnumDescription((Enum)(object)((TEnum)(object)value));  // ugly, but works
}

You can now call this to get a description for whatever type of enum is at hand:

GetEnumDescription<MyEnum>(1);
GetEnumDescription<YourEnum>(2);

Declare and assign multiple string variables at the same time

You can do it like:

string Camnr, Klantnr, Ordernr, Bonnr, Volgnr;// and so on.
Camnr = Klantnr = Ordernr = Bonnr = Volgnr = string.Empty;

First you have to define the variables and then you can use them.

Error: Selection does not contain a main type

Right click on the folder where you put your main class then click on Build Path --> Use as Source Folder.

Finally run your main file as java application. Hope this problem will be solved.

React - How to pass HTML tags in props?

Here is a solution that doesn't use the dangerouslySetInnerHTML which is dangerous as the name says.

import { IntlProvider, FormattedMessage } from "react-intl";

<FormattedMessage
          id="app.greeting"
          description="Bold text example"
          defaultMessage="Look here, I can include HTML tags in plain string and render them as HTML: <b>Bold</b>, <i>Italics</i> and <a>links too</a>."
          values={{
            b: (chunks) => <b>{chunks}</b>,
            i: (chunks) => <i>{chunks}</i>,
            a: (chunks) => (
              <a class="external_link" target="_blank" href="https://jiga.dev/">
                {chunks}
              </a>
            )
          }}
        />

This should be rendered as:

react jiga.dev

Full example in https://jiga.dev/react-render-string-with-html-tags-from-props/

Gradle Build Android Project "Could not resolve all dependencies" error

If you are running on headless CI and are installing the Android SDK through command line, make sure to include the m2repository packages in the --filter argument:

android update sdk --no-ui --filter platform-tools,build-tools-19.0.1,android-19,extra-android-support,extra-android-m2repository,extra-google-m2repository

Update

As of Android SDK Manager rev. 22.6.4 this does not work anymore. Try this instead:

android list sdk --all

You will get a list of all available SDK packages. Look up the numerical values of the components from the first command above ("Google Repository" and others you might be missing).

Install the packages using their numerical values:

android update sdk --no-ui --all --filter <num>

Update #2 (Sept 2017)

With the "new" Android SDK tools that were released earlier this year, the android command is now deprecated, and similar functionality has been moved to a new tool called sdkmanager:

List installed components:

sdkmanager --list

Update installed components:

sdkmanager --update

Install a new component (e.g. build tools version 26.0.0):

sdkmanager 'build-tools;26.0.0'

Event binding on dynamically created elements?

Here is why dynamically created elements do not respond to clicks :

_x000D_
_x000D_
var body = $("body");_x000D_
var btns = $("button");_x000D_
var btnB = $("<button>B</button>");_x000D_
// `<button>B</button>` is not yet in the document._x000D_
// Thus, `$("button")` gives `[<button>A</button>]`._x000D_
// Only `<button>A</button>` gets a click listener._x000D_
btns.on("click", function () {_x000D_
  console.log(this);_x000D_
});_x000D_
// Too late for `<button>B</button>`..._x000D_
body.append(btnB);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button>A</button>
_x000D_
_x000D_
_x000D_

As a workaround, you have to listen to all clicks and check the source element :

_x000D_
_x000D_
var body = $("body");_x000D_
var btnB = $("<button>B</button>");_x000D_
var btnC = $("<button>C</button>");_x000D_
// Listen to all clicks and_x000D_
// check if the source element_x000D_
// is a `<button></button>`._x000D_
body.on("click", function (ev) {_x000D_
  if ($(ev.target).is("button")) {_x000D_
    console.log(ev.target);_x000D_
  }_x000D_
});_x000D_
// Now you can add any number_x000D_
// of `<button></button>`._x000D_
body.append(btnB);_x000D_
body.append(btnC);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button>A</button>
_x000D_
_x000D_
_x000D_

This is called "Event Delegation". Good news, it's a builtin feature in jQuery :-)

_x000D_
_x000D_
var i = 11;_x000D_
var body = $("body");_x000D_
body.on("click", "button", function () {_x000D_
  var letter = (i++).toString(36).toUpperCase();_x000D_
  body.append($("<button>" + letter + "</button>"));_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button>A</button>
_x000D_
_x000D_
_x000D_

What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?

Table relationships vs. entity relationships

In a relational database system, there can be only three types of table relationships:

  • one-to-many (via a Foreign Key column)
  • one-to-one (via a shared Primary Key)
  • many-to-many (via a link table with two Foreign Keys referencing two separate parent tables)

So, a one-to-many table relationship looks as follows:

one-to-many table relationship

Note that the relationship is based on the Foreign Key column (e.g., post_id) in the child table.

So, there is a single source of truth when it comes to managing a one-to-many table relationship.

Now, if you take a bidirectional entity relationship that maps on the one-to-many table relationship we saw previously:

Bidirectional One-To-Many entity association

If you take a look at the diagram above, you can see that there are two ways to manage this relationship.

In the Post entity, you have the comments collection:

@OneToMany(
    mappedBy = "post",
    cascade = CascadeType.ALL,
    orphanRemoval = true
)
private List<PostComment> comments = new ArrayList<>();

And, in the PostComment, the post association is mapped as follows:

@ManyToOne(
    fetch = FetchType.LAZY
)
@JoinColumn(name = "post_id")
private Post post;

So, you have two sides that can change the entity association:

  • By adding an entry in the comments child collection, a new post_comment row should be associated with the parent post entity via its post_id column.
  • By setting the post property of the PostComment entity, the post_id column should be updated as well.

Because there are two ways to represent the Foreign Key column, you must define which is the source of truth when it comes to translating the association state change into its equivalent Foreign Key column value modification.

MappedBy (a.k.a the inverse side)

The mappedBy attribute tells that the @ManyToOne side is in charge of managing the Foreign Key column, and the collection is used only to fetch the child entities and to cascade parent entity state changes to children (e.g., removing the parent should also remove the child entities).

It's called the inverse side because it references the child entity property that manages this table relationship.

Synchronize both sides of a bidirectional association

Now, even if you defined the mappedBy attribute and the child-side @ManyToOne association manages the Foreign Key column, you still need to synchronize both sides of the bidirectional association.

The best way to do that is to add these two utility methods:

public void addComment(PostComment comment) {
    comments.add(comment);
    comment.setPost(this);
}

public void removeComment(PostComment comment) {
    comments.remove(comment);
    comment.setPost(null);
}

The addComment and removeComment methods ensure that both sides are synchronized. So, if we add a child entity, the child entity needs to point to the parent and the parent entity should have the child contained in the child collection.

Write values in app.config file

As others mentioned, you can do this with ConfigurationManager.AppSettings.Settings. But: Using Settings[key] = value will not work if the key doesn't exist.
Using Settings.Add(key, value), if the key already exists, it will join the new value to its value(s) separated by a comma, something like <add key="myKey" value="value1, value2, value3" />

To avoid these unexpected results, you have to handle two scenario's

  • If entry with the given key exists? then update its value
  • if entry with the given key doesn't exist? then create new entry(key,value)

Code

public static void Set(string key, string value)
{
    var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

    var entry = config.AppSettings.Settings[key];
    if (entry == null)
        config.AppSettings.Settings.Add(key, value);
    else
        config.AppSettings.Settings[key].Value = value;

    config.Save(ConfigurationSaveMode.Modified);
}

For more info about the check entry == null, check this post.
Hope this will help someone.

Updating a date in Oracle SQL table

If this SQL is being used in any peoplesoft specific code (Application Engine, SQLEXEC, SQLfetch, etc..) you could use %Datein metaSQL. Peopletools automatically converts the date to a format which would be accepted by the database platform the application is running on.

In case this SQL is being used to perform a backend update from a query analyzer (like SQLDeveloper, SQLTools), the date format that is being used is wrong. Oracle expects the date format to be DD-MMM-YYYY, where MMM could be JAN, FEB, MAR, etc..

How to get first two characters of a string in oracle query?

Just use SUBSTR function. It takes 3 parameters: String column name, starting index and length of substring:

select SUBSTR(OrderNo, 1, 2) FROM shipment;