Programs & Examples On #Dataobjects.net

DataObjects.Net is an ORM and business logic layer development framework.

In OS X Lion, LANG is not set to UTF-8, how to fix it?

I had this issue with MacOS High Sierria.

Screenshot 1

You can set up locale as well as language to UTF-8 format using below command :

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

Screenshot 2

Now in order to check whether locale environment is updated use below command :

Locale

Screenshot 3

Search in lists of lists by given index

You're always going to have a loop - someone might come along with a clever one-liner that hides the loop within a call to map() or similar, but it's always going to be there.

My preference would always be to have clean and simple code, unless performance is a major factor.

Here's perhaps a more Pythonic version of your code:

data = [['a','b'], ['a','c'], ['b','d']]
search = 'c'
for sublist in data:
    if sublist[1] == search:
        print "Found it!", sublist
        break
# Prints: Found it! ['a', 'c']

It breaks out of the loop as soon as it finds a match.

(You have a typo, by the way, in ['b''d'].)

How do you create optional arguments in php?

If you don't know how many attributes need to be processed, you can use the variadic argument list token(...) introduced in PHP 5.6 (see full documentation here).

Syntax:

function <functionName> ([<type> ]...<$paramName>) {}

For example:

function someVariadricFunc(...$arguments) {
  foreach ($arguments as $arg) {
    // do some stuff with $arg...
  }
}

someVariadricFunc();           // an empty array going to be passed
someVariadricFunc('apple');    // provides a one-element array
someVariadricFunc('apple', 'pear', 'orange', 'banana');

As you can see, this token basically turns all parameters to an array, which you can process in any way you like.

How to split a string into a list?

Splits the string in text on any consecutive runs of whitespace.

words = text.split()      

Split the string in text on delimiter: ",".

words = text.split(",")   

The words variable will be a list and contain the words from text split on the delimiter.

Handling very large numbers in Python

python supports arbitrarily large integers naturally:

example:

>>> 10**1000
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

You could even get, for example of a huge integer value, fib(4000000).

But still it does not (for now) supports an arbitrarily large float !!

If you need one big, large, float then check up on the decimal Module. There are examples of use on these foruns: OverflowError: (34, 'Result too large')

Another reference: http://docs.python.org/2/library/decimal.html

You can even using the gmpy module if you need a speed-up (which is likely to be of your interest): Handling big numbers in code

Another reference: https://code.google.com/p/gmpy/

Get Current Session Value in JavaScript?

Accessing & Assigning the Session Variable using Javascript:

Assigning the ASP.NET Session Variable using Javascript:

 <script type="text/javascript">
function SetUserName()
{
    var userName = "Shekhar Shete";
    '<%Session["UserName"] = "' + userName + '"; %>';
     alert('<%=Session["UserName"] %>');
}
</script>

Accessing ASP.NET Session variable using Javascript:

<script type="text/javascript">
    function GetUserName()
    {

        var username = '<%= Session["UserName"] %>';
        alert(username );
    }
</script>

Already Answered here

How to quickly edit values in table in SQL Server Management Studio?

Go to Tools > Options. In the tree on the left, select SQL Server Object Explorer. Set the option "Value for Edit Top Rows command" to 0. It'll now allow you to view and edit the entire table from the context menu.

INSERT INTO a temp table, and have an IDENTITY field created, without first declaring the temp table?

To make things efficient, you need to do declare that one of the columns to be a primary key:

ALTER TABLE #mytable
ADD PRIMARY KEY(KeyColumn)

That won't take a variable for the column name.

Trust me, you are MUCH better off doing a: CREATE #myTable TABLE (or possibly a DECLARE TABLE @myTable) , which allows you to set IDENTITY and PRIMARY KEY directly.

Java String split removed empty values

split(delimiter) by default removes trailing empty strings from result array. To turn this mechanism off we need to use overloaded version of split(delimiter, limit) with limit set to negative value like

String[] split = data.split("\\|", -1);

Little more details:
split(regex) internally returns result of split(regex, 0) and in documentation of this method you can find (emphasis mine)

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.

If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.

If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.

If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

Exception:

It is worth mentioning that removing trailing empty string makes sense only if such empty strings ware created by split mechanism. So for "".split(anything) since we can't split "" farther we will get as result [""] array.
It happens because split didn't happen here, so "" despite being empty and trailing represents original string, not empty string which was created by splitting process.

How to write "Html.BeginForm" in Razor

The following code works fine:

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
{
    @Html.ValidationSummary(true)
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
}

and generates as expected:

<form action="/Upload/Upload" enctype="multipart/form-data" method="post">    
    <fieldset>
        Select a file <input type="file" name="file" />
        <input type="submit" value="Upload" />
    </fieldset>
</form>

On the other hand if you are writing this code inside the context of other server side construct such as an if or foreach you should remove the @ before the using. For example:

@if (SomeCondition)
{
    using (Html.BeginForm("Upload", "Upload", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)
        <fieldset>
            Select a file <input type="file" name="file" />
            <input type="submit" value="Upload" />
        </fieldset>
    }
}

As far as your server side code is concerned, here's how to proceed:

[HttpPost]
public ActionResult Upload(HttpPostedFileBase file) 
{
    if (file != null && file.ContentLength > 0) 
    {
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
        file.SaveAs(path);
    }
    return RedirectToAction("Upload");
}

ArrayList: how does the size increase?

From JDK source code, I found below code

int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);

Angular 2: How to call a function after get a response from subscribe http.post

You can code as a lambda expression as the third parameter(on complete) to the subscribe method. Here I re-set the departmentModel variable to the default values.

saveData(data:DepartmentModel){
  return this.ds.sendDepartmentOnSubmit(data).
  subscribe(response=>this.status=response,
   ()=>{},
   ()=>this.departmentModel={DepartmentId:0});
}

Regular expression [Any number]

UPDATE: for your updated question

variable.match(/\[[0-9]+\]/);

Try this:

variable.match(/[0-9]+/);    // for unsigned integers
variable.match(/[-0-9]+/);   // for signed integers
variable.match(/[-.0-9]+/);  // for signed float numbers

Hope this helps!

How to read a string one letter at a time in python

I can't leave this question in this state with that final code in the question hanging over me...

dan: here's a much neater and shorter version of your code. It would be a good idea to look at how this is done and code more this way in future. I realise you probably have no further need of this code, but learning how you should do it is a good idea. Some things to note:

  • There are only two comments - and even the second is not really necessary for someone familiar with Python, they'll realise NL is being stripped. Only write comments where it adds value.

  • The with statement (recommended in another answer) removes the bother of closing the file through the context handler.

  • Use a dictionary instead of two lists.

  • A generator comprehension ((x for y in z)) is used to do the translation in one line.

  • Wrap as little code as you can in a try/except block to reduce the probability of catching an exception you didn't mean to.

  • Use the input() argument rather than print()ing first - Use '\n' to get the new line you want.

  • Don't write code across multiple lines or with intermediate variables like this just for the sake of it:

    a = a.b()
    a = a.c()
    b = a.x()
    c = b.y()
    

    Instead, write these constructs like this, chaining the calls as is perfectly valid:

    a = a.b().c()
    c = a.x().y()
    

code = {}
with open('morseCode.txt', 'r') as morse_code_file:
    # line format is <letter>:<morse code translation>
    for line in morse_code_file:
        line = line.rstrip()  # Remove NL
        code[line[0]] = line[2:]

user_input = input("Enter a string to convert to morse code or press <enter> to quit\n")
while user_input:
    try:
        print(''.join(code[x] for x in user_input.replace(' ', '').upper()))
    except KeyError:
        print("Error in input. Only alphanumeric characters, a comma, and period allowed")

    user_input = input("Try again or press <enter> to quit\n")

How do I find a default constraint using INFORMATION_SCHEMA?

Object Catalog View : sys.default_constraints

The information schema views INFORMATION_SCHEMA are ANSI-compliant, but the default constraints aren't a part of ISO standard. Microsoft SQL Server provides system catalog views for getting information about SQL Server object metadata.

sys.default_constraints system catalog view used to getting the information about default constraints.

SELECT so.object_id TableName,
       ss.name AS TableSchema,
       cc.name AS Name,
       cc.object_id AS ObjectID,              
       sc.name AS ColumnName,
       cc.parent_column_id AS ColumnID,
       cc.definition AS Defination,
       CONVERT(BIT,
               CASE cc.is_system_named
                   WHEN 1
                   THEN 1
                   ELSE 0
               END) AS IsSystemNamed,
       cc.create_date AS CreationDate,
       cc.modify_date AS LastModifiednDate
FROM sys.default_constraints cc WITH (NOLOCK)
     INNER JOIN sys.objects so WITH (NOLOCK) ON so.object_id = cc.parent_object_id
     LEFT JOIN sys.schemas ss WITH (NOLOCK) ON ss.schema_id = so.schema_id
     LEFT JOIN sys.columns sc WITH (NOLOCK) ON sc.column_id = cc.parent_column_id
                                               AND sc.object_id = cc.parent_object_id
ORDER BY so.name,
         cc.name;

Fastest way to convert a dict's keys & values from `unicode` to `str`?

I know I'm late on this one:

def convert_keys_to_string(dictionary):
    """Recursively converts dictionary keys to strings."""
    if not isinstance(dictionary, dict):
        return dictionary
    return dict((str(k), convert_keys_to_string(v)) 
        for k, v in dictionary.items())

Repeating a function every few seconds

Use a timer. Keep in mind that .NET comes with a number of different timers. This article covers the differences.

Angular File Upload

Try this

Install

npm install primeng --save

Import

import {FileUploadModule} from 'primeng/primeng';

Html

<p-fileUpload name="myfile[]" url="./upload.php" multiple="multiple"
    accept="image/*" auto="auto"></p-fileUpload>

Determine direct shared object dependencies of a Linux binary?

You can use readelf to explore the ELF headers. readelf -d will list the direct dependencies as NEEDED sections.

 $ readelf -d elfbin

Dynamic section at offset 0xe30 contains 22 entries:
  Tag        Type                         Name/Value
 0x0000000000000001 (NEEDED)             Shared library: [libssl.so.1.0.0]
 0x0000000000000001 (NEEDED)             Shared library: [libc.so.6]
 0x000000000000000c (INIT)               0x400520
 0x000000000000000d (FINI)               0x400758
 ...

Prevent linebreak after </div>

A DIV is by default a BLOCK display element, meaning it sits on its own line. If you add the CSS property display:inline it will behave the way you want. But perhaps you should be considering a SPAN instead?

Datatables on-the-fly resizing

The code below is the combination of Chintan Panchal's answer along with Antoine Leclair's comment (placing the code in the windows resize event). (I didn't need the debounce mentioned by Antoine Leclair, however that could be a best practice.)

  $(window).resize( function() {
      $("#example").DataTable().columns.adjust().draw();
  });

This was the approach that worked in my case.

tqdm in Jupyter Notebook prints new progress bars repeatedly

Try using tqdm.notebook.tqdm instead of tqdm, as outlined here.

This could be as simple as changing your import to:

from tqdm.notebook import tqdm

Good luck!

EDIT: After testing, it seems that tqdm actually works fine in 'text mode' in Jupyter notebook. It's hard to tell because you haven't provided a minimal example, but it looks like your problem is caused by a print statement in each iteration. The print statement is outputting a number (~0.89) in between each status bar update, which is messing up the output. Try removing the print statement.

How can building a heap be O(n) time complexity?

Your analysis is correct. However, it is not tight.

It is not really easy to explain why building a heap is a linear operation, you should better read it.

A great analysis of the algorithm can be seen here.


The main idea is that in the build_heap algorithm the actual heapify cost is not O(log n)for all elements.

When heapify is called, the running time depends on how far an element might move down in tree before the process terminates. In other words, it depends on the height of the element in the heap. In the worst case, the element might go down all the way to the leaf level.

Let us count the work done level by level.

At the bottommost level, there are 2^(h)nodes, but we do not call heapify on any of these, so the work is 0. At the next to level there are 2^(h - 1) nodes, and each might move down by 1 level. At the 3rd level from the bottom, there are 2^(h - 2) nodes, and each might move down by 2 levels.

As you can see not all heapify operations are O(log n), this is why you are getting O(n).

Changing Node.js listening port

I usually manually set the port that I am listening on in the app.js file (assuming you are using express.js

var server = app.listen(8080, function() {
    console.log('Ready on port %d', server.address().port);
});

This will log Ready on port 8080 to your console.

Spin or rotate an image on hover

You can use CSS3 transitions with rotate() to spin the image on hover.

Rotating image :

_x000D_
_x000D_
img {_x000D_
  border-radius: 50%;_x000D_
  -webkit-transition: -webkit-transform .8s ease-in-out;_x000D_
          transition:         transform .8s ease-in-out;_x000D_
}_x000D_
img:hover {_x000D_
  -webkit-transform: rotate(360deg);_x000D_
          transform: rotate(360deg);_x000D_
}
_x000D_
<img src="https://i.stack.imgur.com/BLkKe.jpg" width="100" height="100"/>
_x000D_
_x000D_
_x000D_

Here is a fiddle DEMO


More info and references :

  • a guide about CSS transitions on MDN
  • a guide about CSS transforms on MDN
  • browser support table for 2d transforms on caniuse.com
  • browser support table for transitions on caniuse.com

Single TextView with multiple colored text

25 June 2020 by @canerkaseler

I would like to share Kotlin Answer :

fun setTextColor(tv:TextView, startPosition:Int, endPosition:Int, color:Int){
    val spannableStr = SpannableString(tv.text)

    val underlineSpan = UnderlineSpan()
    spannableStr.setSpan(
        underlineSpan,
        startPosition,
        endPosition,
        Spanned.SPAN_INCLUSIVE_EXCLUSIVE
    )

    val backgroundColorSpan = ForegroundColorSpan(this.resources.getColor(R.color.agreement_color))
    spannableStr.setSpan(
        backgroundColorSpan,
        startPosition,
        endPosition,
        Spanned.SPAN_INCLUSIVE_EXCLUSIVE
    )

    val styleSpanItalic = StyleSpan(Typeface.BOLD)
    spannableStr.setSpan(
        styleSpanItalic,
        startPosition,
        endPosition,
        Spanned.SPAN_INCLUSIVE_EXCLUSIVE
    )

    tv.text = spannableStr
}

After, call above function. You can call more than one:

setTextColor(textView, 0, 61, R.color.agreement_color)
setTextColor(textView, 65, 75, R.color.colorPrimary)

Output: You can see underline and different colors with each other.

@canerkaseler

Kubernetes how to make Deployment to update image

UPDATE 2019-06-24

Based on the @Jodiug comment if you have a 1.15 version you can use the command:

kubectl rollout restart deployment/demo

Read more on the issue:

https://github.com/kubernetes/kubernetes/issues/13488


Well there is an interesting discussion about this subject on the kubernetes GitHub project. See the issue: https://github.com/kubernetes/kubernetes/issues/33664

From the solutions described there, I would suggest one of two.

First

1.Prepare deployment

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: demo
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: demo
    spec:
      containers:
      - name: demo
        image: registry.example.com/apps/demo:master
        imagePullPolicy: Always
        env:
        - name: FOR_GODS_SAKE_PLEASE_REDEPLOY
          value: 'THIS_STRING_IS_REPLACED_DURING_BUILD'

2.Deploy

sed -ie "s/THIS_STRING_IS_REPLACED_DURING_BUILD/$(date)/g" deployment.yml
kubectl apply -f deployment.yml

Second (one liner):

kubectl patch deployment web -p \
  "{\"spec\":{\"template\":{\"metadata\":{\"labels\":{\"date\":\"`date +'%s'`\"}}}}}"

Of course the imagePullPolicy: Always is required on both cases.

How to exit git log or git diff

In this case, as snarly suggested, typing q is the intended way to quit git log (as with most other pagers or applications that use pagers).

However normally, if you just want to abort a command that is currently executing, you can try ctrl+c (doesn't seem to work for git log, however) or ctrl+z (although in bash, ctrl-z will freeze the currently running foreground process, which can then be thawed as a background process with the bg command).

How could I convert data from string to long in c#

You can also use long.TryParse and long.Parse.

long l1;
l1 = long.Parse("1100.25");
//or
long.TryParse("1100.25", out l1);

How to handle configuration in Go

The JSON format worked for me quite well. The standard library offers methods to write the data structure indented, so it is quite readable.

See also this golang-nuts thread.

The benefits of JSON are that it is fairly simple to parse and human readable/editable while offering semantics for lists and mappings (which can become quite handy), which is not the case with many ini-type config parsers.

Example usage:

conf.json:

{
    "Users": ["UserA","UserB"],
    "Groups": ["GroupA"]
}

Program to read the configuration

import (
    "encoding/json"
    "os"
    "fmt"
)

type Configuration struct {
    Users    []string
    Groups   []string
}

file, _ := os.Open("conf.json")
defer file.Close()
decoder := json.NewDecoder(file)
configuration := Configuration{}
err := decoder.Decode(&configuration)
if err != nil {
  fmt.Println("error:", err)
}
fmt.Println(configuration.Users) // output: [UserA, UserB]

Copy and paste content from one file to another file in vi

  1. Make sure you have the Vim version compiled with clipboard support
    • :echo has('clipboard') should return 1
    • if it returns 0 (for example Mac OS X, at least v10.11 (El Capitan), v10.9 (Mavericks) and v10.8 (Mountain Lion) - comes with a Vim version lacking clipboard support), you have to install a Vim version with clipboard support, say via brew install vim (don't forget to relaunch your terminal(s) after the installation)
  2. Enter a visual mode (V - multiline, v - plain, or Ctrlv - block-visual)
  3. Select line(s) you wish to copy
  4. "*y - to copy selected
  5. "*p - to paste copied

P.S:

  • you can replace steps 2-5 with the instructions from the answer by JayG, if you need to copy and paste a single line
  • to ease selecting lines, you can add set mouse+=a to your .vimrc - it will allow you to select lines in Vim using the mouse, while not selecting extraneous elements (like line numbers, etc.) NOTICE: it will block the ability to copy mouse-selected text to the system clipboard from Vim.

When should I use "this" in a class?

"this" is also useful when calling one constructor from another:

public class MyClass {
    public MyClass(String foo) {
        this(foo, null);
    }
    public MyClass(String foo, String bar) {
        ...
    }
}

memcpy() vs memmove()

Both memcpy and memove do similar things.

But to sight out one difference:

#include <memory.h>
#include <string.h>
#include <stdio.h>

char str1[7] = "abcdef";

int main()
{

   printf( "The string: %s\n", str1 );
   memcpy( (str1+6), str1, 10 );
   printf( "New string: %s\n", str1 );

   strcpy_s( str1, sizeof(str1), "aabbcc" );   // reset string


   printf("\nstr1: %s\n", str1);
   printf( "The string: %s\n", str1 );
   memmove( (str1+6), str1, 10 );
   printf( "New string: %s\n", str1 );

}

gives:

The string: abcdef
New string: abcdefabcdefabcd
The string: abcdef
New string: abcdefabcdef

Terminating a Java Program

Because System.exit() is just another method to the compiler. It doesn't read ahead and figure out that the whole program will quit at that point (the JVM quits). Your OS or shell can read the integer that is passed back in the System.exit() method. It is standard for 0 to mean "program quit and everything went OK" and any other value to notify an error occurred. It is up to the developer to document these return values for any users.

return on the other hand is a reserved key word that the compiler knows well. return returns a value and ends the current function's run moving back up the stack to the function that invoked it (if any). In your code above it returns void as you have not supplied anything to return.

Assign JavaScript variable to Java Variable in JSP

I think there's no way to do that, unless you pass the value of the JavaScript var on the URL, but it's a ugly workaround.

Fade Effect on Link Hover?

I know in the question you state "I assume JavaScript is used to create this effect" but CSS can be used too, an example is below.

CSS

.fancy-link {
   color: #333333;
   text-decoration: none;
   transition: color 0.3s linear;
   -webkit-transition: color 0.3s linear;
   -moz-transition: color 0.3s linear;
}

.fancy-link:hover {
   color: #F44336;
}

HTML

<a class="fancy-link" href="#">My Link</a>

And here is a JSFIDDLE for the above code!


Marcel in one of the answers points out you can "transition multiple CSS properties" you can also use "all" to effect the element with all your :hover styles like below.

CSS

.fancy-link {
   color: #333333;
   text-decoration: none;
   transition: all 0.3s linear;
   -webkit-transition: all 0.3s linear;
   -moz-transition: all 0.3s linear;
}

.fancy-link:hover {
   color: #F44336;
   padding-left: 10px;
}

HTML

<a class="fancy-link" href="#">My Link</a>

And here is a JSFIDDLE for the "all" example!

Java2D: Increase the line width

What is Stroke:

The BasicStroke class defines a basic set of rendering attributes for the outlines of graphics primitives, which are rendered with a Graphics2D object that has its Stroke attribute set to this BasicStroke.

https://docs.oracle.com/javase/7/docs/api/java/awt/BasicStroke.html

Note that the Stroke setting:

Graphics2D g2 = (Graphics2D) g;
g2.setStroke(new BasicStroke(10));

is setting the line width,since BasicStroke(float width):

Constructs a solid BasicStroke with the specified line width and with default values for the cap and join styles.

And, it also effects other methods like Graphics2D.drawLine(int x1, int y1, int x2, int y2) and Graphics2D.drawRect(int x, int y, int width, int height):

The methods of the Graphics2D interface that use the outline Shape returned by a Stroke object include draw and any other methods that are implemented in terms of that method, such as drawLine, drawRect, drawRoundRect, drawOval, drawArc, drawPolyline, and drawPolygon.

C++ undefined reference to defined function

You need to compile and link all your source files together:

g++ main.c function_file.c

Why is a "GRANT USAGE" created the first time I grant a user privileges?

In addition mysql passwords when not using the IDENTIFIED BY clause, may be blank values, if non-blank, they may be encrypted. But yes USAGE is used to modify an account by granting simple resource limiters such as MAX_QUERIES_PER_HOUR, again this can be specified by also using the WITH clause, in conjuction with GRANT USAGE(no privileges added) or GRANT ALL, you can also specify GRANT USAGE at the global level, database level, table level,etc....

Extracting numbers from vectors of strings

A stringr pipelined solution:

library(stringr)
years %>% str_match_all("[0-9]+") %>% unlist %>% as.numeric

Git merge with force overwrite

I had a similar issue, where I needed to effectively replace any file that had changes / conflicts with a different branch.

The solution I found was to use git merge -s ours branch.

Note that the option is -s and not -X. -s denotes the use of ours as a top level merge strategy, -X would be applying the ours option to the recursive merge strategy, which is not what I (or we) want in this case.

Steps, where oldbranch is the branch you want to overwrite with newbranch.

  • git checkout newbranch checks out the branch you want to keep
  • git merge -s ours oldbranch merges in the old branch, but keeps all of our files.
  • git checkout oldbranch checks out the branch that you want to overwrite
  • get merge newbranch merges in the new branch, overwriting the old branch

What Content-Type value should I send for my XML sitemap?

both are fine.

text/xxx means that in case the program does not understand xxx it makes sense to show the file to the user as plain text. application/xxx means that it is pointless to show it.

Please note that those content-types were originally defined for E-Mail attachment before they got later used in Web world.

Query to check index on a table

On Oracle:

  • Determine all indexes on table:

    SELECT index_name 
     FROM user_indexes
     WHERE table_name = :table
    
  • Determine columns indexes and columns on index:

    SELECT index_name
         , column_position
         , column_name
      FROM user_ind_columns
     WHERE table_name = :table
     ORDER BY index_name, column_order
    

References:

Why use Optional.of over Optional.ofNullable?

This depends upon scenarios.

Let's say you have some business functionality and you need to process something with that value further but having null value at time of processing would impact it.

Then, in that case, you can use Optional<?>.

String nullName = null;

String name = Optional.ofNullable(nullName)
                      .map(<doSomething>)
                      .orElse("Default value in case of null");

How to check date of last change in stored procedure or function in SQL server

For SQL 2000 I would use:

SELECT name, crdate, refdate 
FROM sysobjects
WHERE type = 'P' 
ORDER BY refdate desc

Count the number of occurrences of a character in a string in Javascript

And there is:

function character_count(string, char, ptr = 0, count = 0) {
    while (ptr = string.indexOf(char, ptr) + 1) {count ++}
    return count
}

Works with integers too!

Eclipse reported "Failed to load JNI shared library"

First, ensure that your version of Eclipse and JDK match, either both 64-bit or both 32-bit (you can't mix-and-match 32-bit with 64-bit).

Second, the -vm argument in eclipse.ini should point to the java executable. See http://wiki.eclipse.org/Eclipse.ini for examples.

If you're unsure of what version (64-bit or 32-bit) of Eclipse you have installed, you can determine that a few different ways. See How to find out if an installed Eclipse is 32 or 64 bit version?

Regex - Does not contain certain Characters

^[^<>]+$

The caret in the character class ([^) means match anything but, so this means, beginning of string, then one or more of anything except < and >, then the end of the string.

How to find the operating system version using JavaScript?

@Ludwig 's solution was brilliant. A couple of fixes (which didn't have to do with operating system, and I couldn't place as a comment on his original posting because this is too long):

  1. IE 11 no longer identifies itself as MS IE.
  2. Chrome on IOS spoofs itself as Safari

Here they are:

(function (window) {
    {
    /* test cases
        alert(
            'browserInfo result: OS: ' + browserInfo.os +' '+ browserInfo.osVersion + '\n'+
                'Browser: ' + browserInfo.browser +' '+ browserInfo.browserVersion + '\n' +
                'Mobile: ' + browserInfo.mobile + '\n' +
                'Cookies: ' + browserInfo.cookies + '\n' +
                'Screen Size: ' + browserInfo.screen
        );
    */
        var unknown = 'Unknown';

        // screen
        var screenSize = '';
        if (screen.width) {
            width = (screen.width) ? screen.width : '';
            height = (screen.height) ? screen.height : '';
            screenSize += '' + width + " x " + height;
        }

        //browser
        var nVer = navigator.appVersion;
        var nAgt = navigator.userAgent;
        var browser = navigator.appName;
        var version = '' + parseFloat(navigator.appVersion);
        var majorVersion = parseInt(navigator.appVersion, 10);
        var nameOffset, verOffset, ix;

        // Opera
        if ((verOffset = nAgt.indexOf('Opera')) != -1) {
            browser = 'Opera';
            version = nAgt.substring(verOffset + 6);
            if ((verOffset = nAgt.indexOf('Version')) != -1) {
                version = nAgt.substring(verOffset + 8);
            }
        }
        // MSIE
        else if ((verOffset = nAgt.indexOf('MSIE')) != -1) {
            browser = 'Microsoft Internet Explorer';
            version = nAgt.substring(verOffset + 5);
        }

        //IE 11 no longer identifies itself as MS IE, so trap it
        //http://stackoverflow.com/questions/17907445/how-to-detect-ie11
        else if ((browser == 'Netscape') && (nAgt.indexOf('Trident/') != -1)) {

            browser = 'Microsoft Internet Explorer';
            version = nAgt.substring(verOffset + 5);
            if ((verOffset = nAgt.indexOf('rv:')) != -1) {
                version = nAgt.substring(verOffset + 3);
            }

        }

        // Chrome
        else if ((verOffset = nAgt.indexOf('Chrome')) != -1) {
            browser = 'Chrome';
            version = nAgt.substring(verOffset + 7);
        }
        // Safari
        else if ((verOffset = nAgt.indexOf('Safari')) != -1) {
            browser = 'Safari';
            version = nAgt.substring(verOffset + 7);
            if ((verOffset = nAgt.indexOf('Version')) != -1) {
                version = nAgt.substring(verOffset + 8);
            }

            // Chrome on iPad identifies itself as Safari. Actual results do not match what Google claims
            //  at: https://developers.google.com/chrome/mobile/docs/user-agent?hl=ja
            //  No mention of chrome in the user agent string. However it does mention CriOS, which presumably
            //  can be keyed on to detect it.
            if (nAgt.indexOf('CriOS') != -1) {
                //Chrome on iPad spoofing Safari...correct it.
                browser = 'Chrome';
                //Don't believe there is a way to grab the accurate version number, so leaving that for now.
            }
        }
        // Firefox
        else if ((verOffset = nAgt.indexOf('Firefox')) != -1) {
            browser = 'Firefox';
            version = nAgt.substring(verOffset + 8);
        }
        // Other browsers
        else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
            browser = nAgt.substring(nameOffset, verOffset);
            version = nAgt.substring(verOffset + 1);
            if (browser.toLowerCase() == browser.toUpperCase()) {
                browser = navigator.appName;
            }
        }
        // trim the version string
        if ((ix = version.indexOf(';')) != -1) version = version.substring(0, ix);
        if ((ix = version.indexOf(' ')) != -1) version = version.substring(0, ix);
        if ((ix = version.indexOf(')')) != -1) version = version.substring(0, ix);

        majorVersion = parseInt('' + version, 10);
        if (isNaN(majorVersion)) {
            version = '' + parseFloat(navigator.appVersion);
            majorVersion = parseInt(navigator.appVersion, 10);
        }

        // mobile version
        var mobile = /Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(nVer);

        // cookie
        var cookieEnabled = (navigator.cookieEnabled) ? true : false;

        if (typeof navigator.cookieEnabled == 'undefined' && !cookieEnabled) {
            document.cookie = 'testcookie';
            cookieEnabled = (document.cookie.indexOf('testcookie') != -1) ? true : false;
        }

        // system
        var os = unknown;
        var clientStrings = [
            {s:'Windows 3.11', r:/Win16/},
            {s:'Windows 95', r:/(Windows 95|Win95|Windows_95)/},
            {s:'Windows ME', r:/(Win 9x 4.90|Windows ME)/},
            {s:'Windows 98', r:/(Windows 98|Win98)/},
            {s:'Windows CE', r:/Windows CE/},
            {s:'Windows 2000', r:/(Windows NT 5.0|Windows 2000)/},
            {s:'Windows XP', r:/(Windows NT 5.1|Windows XP)/},
            {s:'Windows Server 2003', r:/Windows NT 5.2/},
            {s:'Windows Vista', r:/Windows NT 6.0/},
            {s:'Windows 7', r:/(Windows 7|Windows NT 6.1)/},
            {s:'Windows 8.1', r:/(Windows 8.1|Windows NT 6.3)/},
            {s:'Windows 8', r:/(Windows 8|Windows NT 6.2)/},
            {s:'Windows NT 4.0', r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},
            {s:'Windows ME', r:/Windows ME/},
            {s:'Android', r:/Android/},
            {s:'Open BSD', r:/OpenBSD/},
            {s:'Sun OS', r:/SunOS/},
            {s:'Linux', r:/(Linux|X11)/},
            {s:'iOS', r:/(iPhone|iPad|iPod)/},
            {s:'Mac OS X', r:/Mac OS X/},
            {s:'Mac OS', r:/(MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},
            {s:'QNX', r:/QNX/},
            {s:'UNIX', r:/UNIX/},
            {s:'BeOS', r:/BeOS/},
            {s:'OS/2', r:/OS\/2/},
            {s:'Search Bot', r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}
        ];
        for (var id in clientStrings) {
            var cs = clientStrings[id];
            if (cs.r.test(nAgt)) {
                os = cs.s;
                break;
            }
        }

        var osVersion = unknown;

        if (/Windows/.test(os)) {
            osVersion = /Windows (.*)/.exec(os)[1];
            os = 'Windows';
        }

        switch (os) {
            case 'Mac OS X':
                osVersion = /Mac OS X (10[\.\_\d]+)/.exec(nAgt)[1];
                break;

            case 'Android':
                osVersion = /Android ([\.\_\d]+)/.exec(nAgt)[1];
                break;

            case 'iOS':
                osVersion = /OS (\d+)_(\d+)_?(\d+)?/.exec(nVer);
                osVersion = osVersion[1] + '.' + osVersion[2] + '.' + (osVersion[3] | 0);
                break;

        }
    }

    window.browserInfo = {
        screen: screenSize,
        browser: browser,
        browserVersion: version,
        mobile: mobile,
        os: os,
        osVersion: osVersion,
        cookies: cookieEnabled
    };
}(this));

Display Records From MySQL Database using JTable in Java

If you need to work a lot with database in your code and you know the structure of your table, I suggest you do it as follow:

First of all you can define a class which will help you to make objects capable of keeping your table rows data. For example in my project I created a class named Document.java to keep data of a single document from my database and I made an array list of these objects to keep data of my table which is gain by a query.

package financialdocuments;

import java.lang.*;
import java.util.HashMap;

/**
 *
 * @author Administrator
 */
public class Document {

 private int document_number; 
 private boolean document_type;
 private boolean document_status; 
 private StringBuilder document_date;
 private StringBuilder document_statement;
 private int document_code_number;
 private int document_employee_number;
 private int document_client_number;
 private String document_employee_name;
 private String document_client_name;
 private long document_amount;
 private long document_payment_amount;

 HashMap<Integer,Activity> document_activity_hashmap;


public Document(int dn,boolean dt,boolean ds,String dd,String dst,int dcon,int den,int dcln,long da,String dena,String dcna){

    document_date = new StringBuilder(dd);
    document_date.setLength(10);
    document_date.setCharAt(4, '.');
    document_date.setCharAt(7, '.');
    document_statement = new StringBuilder(dst);
    document_statement.setLength(50);
    document_number = dn; 
    document_type = dt;
    document_status = ds;
    document_code_number = dcon;
    document_employee_number = den;
    document_client_number = dcln;
    document_amount = da;
    document_employee_name = dena;
    document_client_name = dcna;

    document_payment_amount = 0;

    document_activity_hashmap = new HashMap<>();

}

public Document(int dn,boolean dt,boolean ds, long dpa){

    document_number = dn; 
    document_type = dt;
    document_status = ds;

    document_payment_amount = dpa;

    document_activity_hashmap = new HashMap<>();

}

// Print document information 
public void printDocumentInformation (){
    System.out.println("Document Number:" + document_number); 
    System.out.println("Document Date:" + document_date); 
    System.out.println("Document Type:" + document_type); 
    System.out.println("Document Status:" + document_status); 
    System.out.println("Document Statement:" + document_statement); 
    System.out.println("Document Code Number:" + document_code_number); 
    System.out.println("Document Client Number:" + document_client_number); 
    System.out.println("Document Employee Number:" + document_employee_number); 
    System.out.println("Document Amount:" + document_amount); 
    System.out.println("Document Payment Amount:" + document_payment_amount); 
    System.out.println("Document Employee Name:" + document_employee_name); 
    System.out.println("Document Client Name:" + document_client_name); 

} 
} 

Second of all, you can define a class to handle your database needs. For example I defined a class named DataBase.java which handles my connections to the database and my needed queries. And I instantiated an objected of it in my main class.

package financialdocuments;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class DataBase {

/** 
 * 
 * Defining parameters and strings that are going to be used
 * 
 */
//Connection connect;

// Tables which their datas are extracted at the beginning 
HashMap<Integer,String> code_table;
HashMap<Integer,String> activity_table;
HashMap<Integer,String> client_table;
HashMap<Integer,String> employee_table;

// Resultset Returned by queries 
private ResultSet result;

// Strings needed to set connection
String url = "jdbc:mysql://localhost:3306/financial_documents?useUnicode=yes&characterEncoding=UTF-8";
String dbName = "financial_documents";
String driver = "com.mysql.jdbc.Driver";
String userName = "root"; 
String password = "";

public DataBase(){

    code_table = new HashMap<>();
    activity_table = new HashMap<>();
    client_table = new HashMap<>();
    employee_table = new HashMap<>();
    Initialize();

}

/**
 * Set variables and objects for this class.
 */
private void Initialize(){

    System.out.println("Loading driver..."); 
    try {
        Class.forName(driver);
        System.out.println("Driver loaded!"); 
    } catch (ClassNotFoundException e) { 
        throw new IllegalStateException("Cannot find the driver in the classpath!", e); 
    }

    System.out.println("Connecting database...");

try (Connection connect = DriverManager.getConnection(url,userName,password)) {
            System.out.println("Database connected!");
            //Get tables' information 
            selectCodeTableQueryArray(connect);
           // System.out.println("HshMap Print:");
           // printCodeTableQueryArray();

            selectActivityTableQueryArray(connect);
           // System.out.println("HshMap Print:");
           // printActivityTableQueryArray(); 

            selectClientTableQueryArray(connect);
           // System.out.println("HshMap Print:");
           // printClientTableQueryArray();

            selectEmployeeTableQueryArray(connect);
           // System.out.println("HshMap Print:");
           // printEmployeeTableQueryArray();

            connect.close();
    }catch (SQLException e) { 
        throw new IllegalStateException("Cannot connect the database!", e);
    }

} 

/**
 * Write Queries 
 * @param s
 * @return 
 */
public boolean insertQuery(String s){

    boolean ret = false;
    System.out.println("Loading driver..."); 
    try {
        Class.forName(driver);
        System.out.println("Driver loaded!"); 
    } catch (ClassNotFoundException e) { 
        throw new IllegalStateException("Cannot find the driver in the classpath!", e); 
    }

    System.out.println("Connecting database...");

try (Connection connect = DriverManager.getConnection(url,userName,password)) {
            System.out.println("Database connected!");
            //Set tables' information 
            try {
                Statement st = connect.createStatement();
                int val = st.executeUpdate(s);
                if(val==1){ 
                    System.out.print("Successfully inserted value");
                    ret = true;
                }
                else{ 
                    System.out.print("Unsuccessful insertion");
                    ret = false;
                }
                st.close();
            } catch (SQLException ex) {
                Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
            }
            connect.close();
    }catch (SQLException e) { 
        throw new IllegalStateException("Cannot connect the database!", e);
    } 
    return ret;
}

/**
 * Query needed to get code table's data
 * @param c
 * @return 
 */
private void selectCodeTableQueryArray(Connection c) {
    try {
        Statement st = c.createStatement();
        ResultSet res = st.executeQuery("SELECT * FROM  code;");
        while (res.next()) {
                int id = res.getInt("code_number");
                String msg = res.getString("code_statement");
                code_table.put(id, msg);
            }
        st.close();
    } catch (SQLException ex) {
        Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private void printCodeTableQueryArray() {
    for (HashMap.Entry<Integer ,String> entry : code_table.entrySet()){
        System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
    }
}

/**
 * Query needed to get activity table's data
 * @param c
 * @return 
 */
private void selectActivityTableQueryArray(Connection c) {
    try {
        Statement st = c.createStatement();
        ResultSet res = st.executeQuery("SELECT * FROM  activity;");
        while (res.next()) {
                int id = res.getInt("activity_number");
                String msg = res.getString("activity_statement");
                activity_table.put(id, msg);
            }
        st.close();
    } catch (SQLException ex) {
        Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private void printActivityTableQueryArray() {
    for (HashMap.Entry<Integer ,String> entry : activity_table.entrySet()){
        System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
    }
}

/**
 * Query needed to get client table's data
 * @param c
 * @return 
 */
private void selectClientTableQueryArray(Connection c) {
    try {
        Statement st = c.createStatement();
        ResultSet res = st.executeQuery("SELECT * FROM  client;");
        while (res.next()) {
                int id = res.getInt("client_number");
                String msg = res.getString("client_full_name");
                client_table.put(id, msg);
            }
        st.close();
    } catch (SQLException ex) {
        Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private void printClientTableQueryArray() {
    for (HashMap.Entry<Integer ,String> entry : client_table.entrySet()){
        System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
    }
}

/**
 * Query needed to get activity table's data
 * @param c
 * @return 
 */
private void selectEmployeeTableQueryArray(Connection c) {
    try {
        Statement st = c.createStatement();
        ResultSet res = st.executeQuery("SELECT * FROM  employee;");
        while (res.next()) {
                int id = res.getInt("employee_number");
                String msg = res.getString("employee_full_name");
                employee_table.put(id, msg);
            }
        st.close();
    } catch (SQLException ex) {
        Logger.getLogger(DataBase.class.getName()).log(Level.SEVERE, null, ex);
    }
}

private void printEmployeeTableQueryArray() {
    for (HashMap.Entry<Integer ,String> entry : employee_table.entrySet()){
        System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
    }
} 
}

I hope this could be a little help.

How to sort by column in descending order in Spark SQL?

In the case of Java:

If we use DataFrames, while applying joins (here Inner join), we can sort (in ASC) after selecting distinct elements in each DF as:

Dataset<Row> d1 = e_data.distinct().join(s_data.distinct(), "e_id").orderBy("salary");

where e_id is the column on which join is applied while sorted by salary in ASC.

Also, we can use Spark SQL as:

SQLContext sqlCtx = spark.sqlContext();
sqlCtx.sql("select * from global_temp.salary order by salary desc").show();

where

  • spark  -> SparkSession
  • salary -> GlobalTemp View.

Why can I not create a wheel in python?

I also ran into the error message invalid command 'bdist_wheel'

It turns out the package setup.py used distutils rather than setuptools. Changing it as follows enabled me to build the wheel.

#from distutils.core import setup
from setuptools import setup

.prop('checked',false) or .removeAttr('checked')?

Another alternative to do the same thing is to filter on type=checkbox attribute:

$('input[type="checkbox"]').removeAttr('checked');

or

$('input[type="checkbox"]').prop('checked' , false);

Remeber that The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

Know more...

How to repeat last command in python interpreter shell?

ALT + p works for me on Enthought Python in Windows.

What does the [Flags] Enum Attribute mean in C#?

I asked recently about something similar.

If you use flags you can add an extension method to enums to make checking the contained flags easier (see post for detail)

This allows you to do:

[Flags]
public enum PossibleOptions : byte
{
    None = 0,
    OptionOne = 1,
    OptionTwo = 2,
    OptionThree = 4,
    OptionFour = 8,

    //combinations can be in the enum too
    OptionOneAndTwo = OptionOne | OptionTwo,
    OptionOneTwoAndThree = OptionOne | OptionTwo | OptionThree,
    ...
}

Then you can do:

PossibleOptions opt = PossibleOptions.OptionOneTwoAndThree 

if( opt.IsSet( PossibleOptions.OptionOne ) ) {
    //optionOne is one of those set
}

I find this easier to read than the most ways of checking the included flags.

Ng-model does not update controller value

I was facing same problem... The resolution that worked for me is to use this keyword..........

alert(this.ModelName);

Apache Proxy: No protocol handler was valid

To clarify for future reference, a2enmod, as is suggested in several answers above, is for Debian/Ubuntu. Red Hat does not use this to enable Apache modules - instead it uses LoadModule statements in httpd.conf.

More here: https://serverfault.com/questions/56394/how-do-i-enable-apache-modules-from-the-command-line-in-redhat

The resolution/correct answer is in the comments on the OP:

I think you need mod_ssl and SSLProxyEngine with ProxyPass – Deadooshka May 29 '14 at 11:35

@Deadooshka Yes, this is working. If you post this as an answer, I can accept it – das_j May 29 '14 at 12:04

How to create a popup windows in javafx

Take a look at jfxmessagebox (http://en.sourceforge.jp/projects/jfxmessagebox/) if you are looking for very simple dialog popups.

Can I animate absolute positioned element with CSS transition?

try this:

.test {
    position:absolute;
    background:blue;
    width:200px;
    height:200px;
    top:40px;
    transition:left 1s linear;
    left: 0;
}

How to copy a string of std::string type in C++?

You shouldn't use strcpy() to copy a std::string, only use it for C-Style strings.

If you want to copy a to b then just use the = operator.

string a = "text";
string b = "image";
b = a;

How can I add the new "Floating Action Button" between two widgets/layouts

With AppCompat 22, the FAB is supported for older devices.

Add the new support library in your build.gradle(app):

compile 'com.android.support:design:22.2.0'

Then you can use it in your xml:

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:src="@android:drawable/ic_menu_more"
    app:elevation="6dp"
    app:pressedTranslationZ="12dp" />

To use elevation and pressedTranslationZ properties, namespace app is needed, so add this namespace to your layout: xmlns:app="http://schemas.android.com/apk/res-auto"

Add colorbar to existing axis

Couldn't add this as a comment, but in case anyone is interested in using the accepted answer with subplots, the divider should be formed on specific axes object (rather than on the numpy.ndarray returned from plt.subplots)

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots(ncols=2, nrows=2)
for row in ax:
    for col in row:
        im = col.imshow(data, cmap='bone')
        divider = make_axes_locatable(col)
        cax = divider.append_axes('right', size='5%', pad=0.05)
        fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()

Disable cache for some images

If you need to do it dynamically in the browser using javascript, here is an example...

<img id=graph alt="" 
  src="http://www.kitco.com/images/live/gold.gif" 
  />

<script language="javascript" type="text/javascript">
    var d = new Date(); 
    document.getElementById("graph").src = 
      "http://www.kitco.com/images/live/gold.gif?ver=" + 
       d.getTime();
</script>

SQL Add foreign key to existing column

In the future.

ALTER TABLE Employees
ADD UserID int;

ALTER TABLE Employees
ADD CONSTRAINT FK_ActiveDirectories_UserID FOREIGN KEY (UserID)
    REFERENCES ActiveDirectories(id);

What is a .NET developer?

Generally what's meant by that is a fairly intimate familiarity with one (or probably more) of the .NET languages (C#, VB.NET, etc.) and one (or less probably more) of the .NET stacks (WinForms, ASP.NET, WPF, etc.).

As for a specific "formal definition", I don't think you'll find one beyond that. The job description should be specific about what they're looking for. I wouldn't consider a job listing that asks for a ".NET developer" and provides no more detail than that to be sufficiently descriptive.

How do I calculate a trendline for a graph?

Given that the trendline is straight, find the slope by choosing any two points and calculating:

(A) slope = (y1-y2)/(x1-x2)

Then you need to find the offset for the line. The line is specified by the equation:

(B) y = offset + slope*x

So you need to solve for offset. Pick any point on the line, and solve for offset:

(C) offset = y - (slope*x)

Now you can plug slope and offset into the line equation (B) and have the equation that defines your line. If your line has noise you'll have to decide on an averaging algorithm, or use curve fitting of some sort.

If your line isn't straight then you'll need to look into Curve fitting, or Least Squares Fitting - non trivial, but do-able. You'll see the various types of curve fitting at the bottom of the least squares fitting webpage (exponential, polynomial, etc) if you know what kind of fit you'd like.

Also, if this is a one-off, use Excel.

Google Play Services Missing in Emulator (Android 4.4.2)

You will not able to test the app using the Google-Play-Service library in emulator. In order to test that app in emulator you need to install some system framework in your emulator to make it work.

https://stackoverflow.com/a/11213598/1405008

Refer the above answer to install Google play service on your emulator.

bash: mkvirtualenv: command not found

On Windows 7 and Git Bash this helps me:

  1. Create a ~/.bashrc file (under your user home folder)
  2. Add line export WORKON_HOME=$HOME/.virtualenvs (you must create this folder if it doesn't exist)
  3. Add line source "C:\Program Files (x86)\Python36-32\Scripts\virtualenvwrapper.sh" (change path for your virtualenvwrapper.sh)

Restart your git bash and mkvirtualenv command now will work nicely.

creating a new list with subset of list using index in python

Try new_list = a[0:2] + [a[4]] + a[6:].

Or more generally, something like this:

from itertools import chain
new_list = list(chain(a[0:2], [a[4]], a[6:]))

This works with other sequences as well, and is likely to be faster.

Or you could do this:

def chain_elements_or_slices(*elements_or_slices):
    new_list = []
    for i in elements_or_slices:
        if isinstance(i, list):
            new_list.extend(i)
        else:
            new_list.append(i)
    return new_list

new_list = chain_elements_or_slices(a[0:2], a[4], a[6:])

But beware, this would lead to problems if some of the elements in your list were themselves lists. To solve this, either use one of the previous solutions, or replace a[4] with a[4:5] (or more generally a[n] with a[n:n+1]).

How to embed a video into GitHub README.md?

I strongly recommend placing the video in a project website created with GitHub Pages instead of the readme, like described in VonC's answer; it will be a lot better than any of these ideas. But if you need a quick fix just like I needed, here are some suggestions.

Use a gif

See aloisdg's answer, result is awesome, gifs are rendered on github's readme ;)

Use a video player picture

You could trick the user into thinking the video is on the readme page with a picture. It sounds like an ad trick, it's not perfect, but it works and it's funny ;).

Example:

[![Watch the video](https://i.imgur.com/vKb2F1B.png)](https://youtu.be/vt5fpE0bzSY)

Result:

Watch the video

Use youtube's preview picture

You can also use the picture generated by youtube for your video.

For youtube urls in the form of:

https://www.youtube.com/watch?v=<VIDEO ID>
https://youtu.be/<VIDEO URL>

The preview urls are in the form of:

https://img.youtube.com/vi/<VIDEO ID>/maxresdefault.jpg
https://img.youtube.com/vi/<VIDEO ID>/hqdefault.jpg

Example:

[![Watch the video](https://img.youtube.com/vi/T-D1KVIuvjA/maxresdefault.jpg)](https://youtu.be/T-D1KVIuvjA)

Result:

Watch the video

Use asciinema

If your use case is something that runs in a terminal, asciinema lets you record a terminal session and has nice markdown embedding.

Hit share button and copy the markdown snippet.

Example:

[![asciicast](https://asciinema.org/a/113463.png)](https://asciinema.org/a/113463)

Result:

asciicast

Get name of property as a string

Okay, here's what I ended up creating (based upon the answer I selected and the question he referenced):

// <summary>
// Get the name of a static or instance property from a property access lambda.
// </summary>
// <typeparam name="T">Type of the property</typeparam>
// <param name="propertyLambda">lambda expression of the form: '() => Class.Property' or '() => object.Property'</param>
// <returns>The name of the property</returns>

public string GetPropertyName<T>(Expression<Func<T>> propertyLambda)
{
    var me = propertyLambda.Body as MemberExpression;

    if (me == null)
    {
        throw new ArgumentException("You must pass a lambda of the form: '() => Class.Property' or '() => object.Property'");
    }

    return me.Member.Name;
 }

Usage:

// Static Property
string name = GetPropertyName(() => SomeClass.SomeProperty);

// Instance Property
string name = GetPropertyName(() => someObject.SomeProperty);

What is the difference between "mvn deploy" to a local repo and "mvn install"?

Ken, good question. I should be more explicit in the The Definitive Guide about the difference. "install" and "deploy" serve two different purposes in a build. "install" refers to the process of installing an artifact in your local repository. "deploy" refers to the process of deploying an artifact to a remote repository.

Example:

  1. When I run a large multi-module project on a my machine, I'm going to usually run "mvn install". This is going to install all of the generated binary software artifacts (usually JARs) in my local repository. Then when I build individual modules in the build, Maven is going to retrieve the dependencies from the local repository.

  2. When it comes time to deploy snapshots or releases, I'm going to run "mvn deploy". Running this is going to attempt to deploy the files to a remote repository or server. Usually I'm going to be deploying to a repository manager such as Nexus

It is true that running "deploy" is going to require some extra configuration, you are going to have to supply a distributionManagement section in your POM.

Find a line in a file and remove it

This solution uses a RandomAccessFile to only cache the portion of the file subsequent to the string to remove. It scans until it finds the String you want to remove. Then it copies all of the data after the found string, then writes it over the found string, and everything after. Last, it truncates the file size to remove the excess data.

public static long scanForString(String text, File file) throws IOException {
    if (text.isEmpty())
        return file.exists() ? 0 : -1;
    // First of all, get a byte array off of this string:
    byte[] bytes = text.getBytes(/* StandardCharsets.your_charset */);

    // Next, search the file for the byte array.
    try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) {

        List<Integer> matches = new LinkedList<>();

        for (long pos = 0; pos < file.length(); pos++) {
            byte bite = dis.readByte();

            for (int i = 0; i < matches.size(); i++) {
                Integer m = matches.get(i);
                if (bytes[m] != bite)
                    matches.remove(i--);
                else if (++m == bytes.length)
                    return pos - m + 1;
                else
                    matches.set(i, m);
            }

            if (bytes[0] == bite)
                matches.add(1);
        }
    }
    return -1;
}

public static void remove(String text, File file) throws IOException {
    try (RandomAccessFile rafile = new RandomAccessFile(file, "rw");) {
        long scanForString = scanForString(text, file);
        if (scanForString == -1) {
            System.out.println("String not found.");
            return;
        }
        long remainderStartPos = scanForString + text.getBytes().length;
        rafile.seek(remainderStartPos);
        int remainderSize = (int) (rafile.length() - rafile.getFilePointer());
        byte[] bytes = new byte[remainderSize];
        rafile.read(bytes);
        rafile.seek(scanForString);

        rafile.write(bytes);
        rafile.setLength(rafile.length() - (text.length()));
    }
}

Usage:

File Contents: ABCDEFGHIJKLMNOPQRSTUVWXYZ

Method Call: remove("ABC", new File("Drive:/Path/File.extension"));

Resulting Contents: DEFGHIJKLMNOPQRSTUVWXYZ

This solution could easily be modified to remove with a certain, specifiable cacheSize, if memory is a concern. This would just involve iterating over the rest of the file to continually replace portions of size, cacheSize. Regardless, this solution is generally much better than caching an entire file in memory, or copying it to a temporary directory, etc.

Select and trigger click event of a radio button in jquery

In my case i had to load images on radio button click, I just uses the regular onclick event and it worked for me.

 <input type="radio" name="colors" value="{{color.id}}" id="{{color.id}}-option" class="color_radion"  onclick="return get_images(this, {{color.id}})">

<script>
  function get_images(obj, color){
    console.log($("input[type='radio'][name='colors']:checked").val());

  }
  </script>

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

You can leverage Conditional Formatting as follows.

  1. In cell H8 select Format > Conditional Formatting...
  2. In Condition1, select Formula Is in first drop down menu
  3. In the next textbox type =I8="Elementary"
  4. Select Format... and select the color you want etc.
  5. Select Add>> and repeat steps 1 to 4

Note that you can only have (in excel 2003) three separate conditions so you will only be able to have different formatting for three items in the drop down menu. If the idea is to make them visually distinct then (maybe) having no color for one of the selections is not a problem?

If the cell is never blank, you can use format (not conditional) to get 4 distinct visuals.

php multidimensional array get values

For people who searched for php multidimensional array get values and actually want to solve problem comes from getting one column value from a 2 dimensinal array (like me!), here's a much elegant way than using foreach, which is array_column

For example, if I only want to get hotel_name from the below array, and form to another array:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
    ]
];

I can do this using array_column:

$hotel_name = array_column($hotels, 'hotel_name');

print_r($hotel_name); // Which will give me ['Hotel A', 'Hotel B']

For the actual answer for this question, it can also be beautified by array_column and call_user_func_array('array_merge', $twoDimensionalArray);

Let's make the data in PHP:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 1,
                    'price' => 200
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 2,
                    'price' => 150
                ]
            ],
        ]
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 3,
                    'price' => 900
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 4,
                    'price' => 300
                ]
            ],
        ]
    ]
];

And here's the calculation:

$rooms = array_column($hotels, 'rooms');
$rooms = call_user_func_array('array_merge', $rooms);
$boards = array_column($rooms, 'boards');

foreach($boards as $board){
    $board_id = $board['board_id'];
    $price = $board['price'];
    echo "Board ID is: ".$board_id." and price is: ".$price . "<br/>";
}

Which will give you the following result:

Board ID is: 1 and price is: 200
Board ID is: 2 and price is: 150
Board ID is: 3 and price is: 900
Board ID is: 4 and price is: 300

Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?

As of Angular 2.2.3 there is now a forwardRef() utility function that allows you to inject providers that have not yet been defined.

By not defined, I mean that the dependency injection map doesn't know the identifier. This is what happens during circular dependencies. You can have circular dependencies in Angular that are very difficult to untangle and see.

export class HeaderComponent {
  mobileNav: boolean = false;

  constructor(@Inject(forwardRef(() => MobileService)) public ms: MobileService) {
    console.log(ms);
  }

}

Adding @Inject(forwardRef(() => MobileService)) to the parameter of the constructor in the original question's source code will fix the problem.

References

Angular 2 Manual: ForwardRef

Forward references in Angular 2

How to catch segmentation fault in Linux?

For portability, one should probably use std::signal from the standard C++ library, but there is a lot of restriction on what a signal handler can do. Unfortunately, it is not possible to catch a SIGSEGV from within a C++ program without introducing undefined behavior because the specification says:

  1. it is undefined behavior to call any library function from within the handler other than a very narrow subset of the standard library functions (abort, exit, some atomic functions, reinstall current signal handler, memcpy, memmove, type traits, `std::move, std::forward, and some more).
  2. it is undefined behavior if handler use a throw expression.
  3. it is undefined behavior if the handler returns when handling SIGFPE, SIGILL, SIGSEGV

This proves that it is impossible to catch SIGSEGV from within a program using strictly standard and portable C++. SIGSEGV is still caught by the operating system and is normally reported to the parent process when a wait family function is called.

You will probably run into the same kind of trouble using POSIX signal because there is a clause that says in 2.4.3 Signal Actions:

The behavior of a process is undefined after it returns normally from a signal-catching function for a SIGBUS, SIGFPE, SIGILL, or SIGSEGV signal that was not generated by kill(), sigqueue(), or raise().

A word about the longjumps. Assuming we are using POSIX signals, using longjump to simulate stack unwinding won't help:

Although longjmp() is an async-signal-safe function, if it is invoked from a signal handler which interrupted a non-async-signal-safe function or equivalent (such as the processing equivalent to exit() performed after a return from the initial call to main()), the behavior of any subsequent call to a non-async-signal-safe function or equivalent is undefined.

This means that the continuation invoked by the call to longjump cannot reliably call usually useful library function such as printf, malloc or exit or return from main without inducing undefined behavior. As such, the continuation can only do a restricted operations and may only exit through some abnormal termination mechanism.

To put things short, catching a SIGSEGV and resuming execution of the program in a portable is probably infeasible without introducing UB. Even if you are working on a Windows platform for which you have access to Structured exception handling, it is worth mentioning that MSDN suggest to never attempt to handle hardware exceptions: Hardware Exceptions.

At last but not least, whether any SIGSEGV would be raised when dereferencing a null valued pointer (or invalid valued pointer) is not a requirement from the standard. Because indirection through a null valued pointer or any invalid valued pointer is an undefined behaviour, which means the compiler assumes your code will never attempt such a thing at runtime, the compiler is free to make code transformation that would elide such undefined behavior. For example, from cppreference,

int foo(int* p) {
    int x = *p;
    if(!p)
        return x; // Either UB above or this branch is never taken
    else
        return 0;
}
 
int main() {
    int* p = nullptr;
    std::cout << foo(p);
}

Here the true path of the if could be completely elided by the compiler as an optimization; only the else part could be kept. Said otherwise, the compiler infers foo() will never receive a null valued pointer at runtime since it would lead to an undefined behaviour. Invoking it with a null valued pointer, you may observe the value 0 printed to standard output and no crash, you may observe a crash with SIGSEG, in fact you could observe anything since no sensible requirements are imposed on programs that are not free of undefined behaviors.

Why is 1/1/1970 the "epoch time"?

Short answer: Why not?

Longer answer: The time itself doesn't really matter, as long as everyone who uses it agrees on its value. As 1/1/70 has been in use for so long, using it will make you code as understandable as possible for as many people as possible.

There's no great merit in choosing an arbitrary epoch just to be different.

What is the difference between origin and upstream on GitHub?

after cloning a fork you have to explicitly add a remote upstream, with git add remote "the original repo you forked from". This becomes your upstream, you mostly fetch and merge from your upstream. Any other business such as pushing from your local to upstream should be done using pull request.

How do I remove an object from an array with JavaScript?

we have an array of objects, we want to remove one object using only the id property

var apps = [
       {id:34,name:'My App',another:'thing'},
       {id:37,name:'My New App',another:'things'
}];

get the index of the object with id:37

var removeIndex = apps.map(function(item) { return item.id; }).indexOf(37);

// remove object

apps.splice(removeIndex, 1);

Update Tkinter Label from variable

This is the easiest one , Just define a Function and then a Tkinter Label & Button . Pressing the Button changes the text in the label. The difference that you would when defining the Label is that use the text variable instead of text. Code is tested and working.

    from tkinter import *
    master = Tk()
    
    def change_text():
        my_var.set("Second click")
    
    my_var = StringVar()
    my_var.set("First click")
    label = Label(mas,textvariable=my_var,fg="red")
    button = Button(mas,text="Submit",command = change_text)
    button.pack()
    label.pack()
    
    master.mainloop()

How to assign pointer address manually in C programming language?

Like this:

void * p = (void *)0x28ff44;

Or if you want it as a char *:

char * p = (char *)0x28ff44;

...etc.

If you're pointing to something you really, really aren't meant to change, add a const:

const void * p = (const void *)0x28ff44;
const char * p = (const char *)0x28ff44;

...since I figure this must be some kind of "well-known address" and those are typically (though by no means always) read-only.

How to select <td> of the <table> with javascript?

There begin to appear some answers that assume you want to get all <td> elements from #table. If so, the simplest cross-browser way how to do this is document.getElementById('table').getElementsByTagName('td'). This works because getElementsByTagName doesn't return only immediate children. No loops are needed.

Searching for Text within Oracle Stored Procedures

If you use UPPER(text), the like '%lah%' will always return zero results. Use '%LAH%'.

Recursively add the entire folder to a repository

I just needed to do this, and I found that you can easily add files in subdirectories. You only need to be on the "top directory" of the repo, and then run something like:

$ git add ./subdir/file_in_subdir.txt

What is the difference between null and System.DBNull.Value?

Null is similar to zero pointer in C++. So it is a reference which not pointing to any value.

DBNull.Value is completely different and is a constant which is returned when a field value contains NULL.

ASP.NET - How to write some html in the page? With Response.Write?

If you want something lighter than a Label or other ASP.NET-specific server control you can just use a standard HTML DIV or SPAN and with runat="server", e.g.:

Markup:

<span runat="server" id="FooSpan"></span>

Code:

FooSpan.Text = "Foo";

How do I add comments to package.json for npm install?

Inspired by this thread, here's what we are using:

{
  "//dependencies": {
    "crypto-exchange": "Unified exchange API"
  },
  "dependencies": {
    "crypto-exchange": "^2.3.3"
  },
  "//devDependencies": {
    "chai": "Assertions",
    "mocha": "Unit testing framwork",
    "sinon": "Spies, Stubs, Mocks",
    "supertest": "Test requests"
  },
  "devDependencies": {
    "chai": "^4.1.2",
    "mocha": "^4.0.1",
    "sinon": "^4.1.3",
    "supertest": "^3.0.0"
  }
}

Best way to serialize/unserialize objects in JavaScript?

I am the author of https://github.com/joonhocho/seri.

Seri is JSON + custom (nested) class support.

You simply need to provide toJSON and fromJSON to serialize and deserialize any class instances.

Here's an example with nested class objects:

import seri from 'seri';

class Item {
  static fromJSON = (name) => new Item(name)

  constructor(name) {
    this.name = name;
  }

  toJSON() {
    return this.name;
  }
}

class Bag {
  static fromJSON = (itemsJson) => new Bag(seri.parse(itemsJson))

  constructor(items) {
    this.items = items;
  }

  toJSON() {
    return seri.stringify(this.items);
  }
}

// register classes
seri.addClass(Item);
seri.addClass(Bag);


const bag = new Bag([
  new Item('apple'),
  new Item('orange'),
]);


const bagClone = seri.parse(seri.stringify(bag));


// validate
bagClone instanceof Bag;

bagClone.items[0] instanceof Item;
bagClone.items[0].name === 'apple';

bagClone.items[1] instanceof Item;
bagClone.items[1].name === 'orange';

Hope it helps address your problem.

RegEx to match stuff between parentheses

Use this expression:

/\(([^()]+)\)/g

e.g:

function()
{
    var mts = "something/([0-9])/([a-z])".match(/\(([^()]+)\)/g );
    alert(mts[0]);
    alert(mts[1]);
}

Exclude all transitive dependencies of a single dependency

If you develop under Eclipse, you can in the POM Editor (advanced tabs enabled) dependency graph look for the dependency you want to exclude of your project and then:

right click on it -> "Exclude Maven Artifact ..." and Eclipse will make the exclusion for you without the need to find out on which dependency the lib is linked.

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

Command-line tool for finding out who is locking a file

I have used Unlocker for years and really like it. It not only will identify programs and offer to unlock the folder\file, it will allow you to kill the processing that has the lock as well.

Additionally, it offers actions to do to the locked file in question such as deleting it.

Unlocker helps delete locked files with error messages including "cannot delete file," and "access is denied." Video tutorial available.

Some errors you might get that Unlocker can help with include:

  • Cannot delete file: Access is denied.
  • There has been a sharing violation.
  • The source or destination file may be in use.
  • The file is in use by another program or user.
  • Make sure the disk is not full or write-protected and that the file is not currently in use.

How do I call a JavaScript function on page load?

here's the trick (works everywhere):

r(function(){
alert('DOM Ready!');
});
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}

How do I check whether a checkbox is checked in jQuery?

This was my workaround:

$('#vcGoButton').click(function () {
    var buttonStatus = $('#vcChangeLocation').prop('checked');
    console.log("Status is " + buttonStatus);
    if (buttonStatus) {
        var address = $('#vcNewLocation').val();
        var cabNumber = $('#vcVehicleNumber').val();
        $.get('postCabLocation.php',
              {address: address, cabNumber: cabNumber},
              function(data) {
                  console.log("Changed vehicle " + cabNumber + " location to " + address );
              });
    }
    else {
        console.log("VC go button clicked, but no location action");
    }
});

T-SQL: Deleting all duplicate rows but keeping one

You didn't say what version you were using, but in SQL 2005 and above, you can use a common table expression with the OVER Clause. It goes a little something like this:

WITH cte AS (
  SELECT[foo], [bar], 
     row_number() OVER(PARTITION BY foo, bar ORDER BY baz) AS [rn]
  FROM TABLE
)
DELETE cte WHERE [rn] > 1

Play around with it and see what you get.

(Edit: In an attempt to be helpful, someone edited the ORDER BY clause within the CTE. To be clear, you can order by anything you want here, it needn't be one of the columns returned by the cte. In fact, a common use-case here is that "foo, bar" are the group identifier and "baz" is some sort of time stamp. In order to keep the latest, you'd do ORDER BY baz desc)

AngularJS ng-repeat handle empty list case

With the newer versions of angularjs the correct answer to this question is to use ng-if:

<ul>
  <li ng-if="list.length === 0">( No items in this list yet! )</li>
  <li ng-repeat="item in list">{{ item }}</li>
</ul>

This solution will not flicker when the list is about to download either because the list has to be defined and with a length of 0 for the message to display.

Here is a plunker to show it in use: http://plnkr.co/edit/in7ha1wTlpuVgamiOblS?p=preview

Tip: You can also show a loading text or spinner:

  <li ng-if="!list">( Loading... )</li>

how to list all sub directories in a directory

Use Directory.GetDirectories to get the subdirectories of the directory specified by "your_directory_path". The result is an array of strings.

var directories = Directory.GetDirectories("your_directory_path");

By default, that only returns subdirectories one level deep. There are options to return all recursively and to filter the results, documented here, and shown in Clive's answer.


Avoiding an UnauthorizedAccessException

It's easily possible that you'll get an UnauthorizedAccessException if you hit a directory to which you don't have access.

You may have to create your own method that handles the exception, like this:

public class CustomSearcher
{ 
    public static List<string> GetDirectories(string path, string searchPattern = "*",
        SearchOption searchOption = SearchOption.AllDirectories)
    {
        if (searchOption == SearchOption.TopDirectoryOnly)
            return Directory.GetDirectories(path, searchPattern).ToList();

        var directories = new List<string>(GetDirectories(path, searchPattern));

        for (var i = 0; i < directories.Count; i++)
            directories.AddRange(GetDirectories(directories[i], searchPattern));

        return directories;
    }

    private static List<string> GetDirectories(string path, string searchPattern)
    {
        try
        {
            return Directory.GetDirectories(path, searchPattern).ToList();
        }
        catch (UnauthorizedAccessException)
        {
            return new List<string>();
        }
    }
}

And then call it like this:

var directories = CustomSearcher.GetDirectories("your_directory_path");

This traverses a directory and all its subdirectories recursively. If it hits a subdirectory that it cannot access, something that would've thrown an UnauthorizedAccessException, it catches the exception and just returns an empty list for that inaccessible directory. Then it continues on to the next subdirectory.

Undefined reference to pthread_create in Linux

Sometimes, if you use multiple library, check the library dependency. (e.g. -lpthread -lSDL... <==> ... -lSDL -lpthread)

how to use font awesome in own css?

Try this way. In your css file change font-family: FontAwesome into font-family: "FontAwesome"; or font-family: 'FontAwesome';. I've solved the same problem using this method.

Difference between try-catch and throw in java

If you execute the following example, you will know the difference between a Throw and a Catch block.

In general terms:

The catch block will handle the Exception

throws will pass the error to his caller.

In the following example, the error occurs in the throwsMethod() but it is handled in the catchMethod().

public class CatchThrow {

private static void throwsMethod() throws NumberFormatException {
    String  intNumber = "5A";

    Integer.parseInt(intNumber);
}

private static void catchMethod() {
    try {

        throwsMethod();

    } catch (NumberFormatException e) {
        System.out.println("Convertion Error");
    }

}

public static void main(String[] args) {
    // TODO Auto-generated method stub

    catchMethod();
}

}

File upload along with other object in Jersey restful web service

The request type is multipart/form-data and what you are sending is essentially form fields that go out as bytes with content boundaries separating different form fields.To send an object representation as form field (string), you can send a serialized form from the client that you can then deserialize on the server.

After all no programming environment object is actually ever traveling on the wire. The programming environment on both side are just doing automatic serialization and deserialization that you can also do. That is the cleanest and programming environment quirks free way to do it.

As an example, here is a javascript client posting to a Jersey example service,

submitFile(){

    let data = new FormData();
    let account = {
        "name": "test account",
        "location": "Bangalore"
    }

    data.append('file', this.file);
    data.append("accountKey", "44c85e59-afed-4fb2-884d-b3d85b051c44");
    data.append("device", "test001");
    data.append("account", JSON.stringify(account));
    
    let url = "http://localhost:9090/sensordb/test/file/multipart/upload";

    let config = {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }

    axios.post(url, data, config).then(function(data){
        console.log('SUCCESS!!');
        console.log(data.data);
    }).catch(function(){
        console.log('FAILURE!!');
    });
},

Here the client is sending a file, 2 form fields (strings) and an account object that has been stringified for transport. here is how the form fields look on the wire,

enter image description here

On the server, you can just deserialize the form fields the way you see fit. To finish this trivial example,

    @POST
@Path("/file/multipart/upload")
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Response uploadMultiPart(@Context ContainerRequestContext requestContext,
        @FormDataParam("file") InputStream fileInputStream,
        @FormDataParam("file") FormDataContentDisposition cdh,
        @FormDataParam("accountKey") String accountKey,
        @FormDataParam("account") String json)  {
    

    
    System.out.println(cdh.getFileName());
    System.out.println(cdh.getName());
    System.out.println(accountKey);
    
    try {
        Account account = Account.deserialize(json);
        System.out.println(account.getLocation());
        System.out.println(account.getName());
        
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    return Response.ok().build();
    
}

C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order

The problem is that you're calling List<T>.Reverse() which returns void.

You could either do:

List<string> names = "Tom,Scott,Bob".Split(',').ToList<string>();
names.Reverse();

or:

IList<string> names = "Tom,Scott,Bob".Split(',').Reverse().ToList<string>();

The latter is more expensive, as reversing an arbitrary IEnumerable<T> involves buffering all of the data and then yielding it all - whereas List<T> can do all the reversing "in-place". (The difference here is that it's calling the Enumerable.Reverse<T>() extension method, instead of the List<T>.Reverse() instance method.)

More efficient yet, you could use:

string[] namesArray = "Tom,Scott,Bob".Split(',');
List<string> namesList = new List<string>(namesArray.Length);
namesList.AddRange(namesArray);
namesList.Reverse();

This avoids creating any buffers of an inappropriate size - at the cost of taking four statements where one will do... As ever, weigh up readability against performance in the real use case.

How can I get a list of all classes within current module in Python?

I frequently find myself writing command line utilities wherein the first argument is meant to refer to one of many different classes. For example ./something.py feature command —-arguments, where Feature is a class and command is a method on that class. Here's a base class that makes this easy.

The assumption is that this base class resides in a directory alongside all of its subclasses. You can then call ArgBaseClass(foo = bar).load_subclasses() which will return a dictionary. For example, if the directory looks like this:

  • arg_base_class.py
  • feature.py

Assuming feature.py implements class Feature(ArgBaseClass), then the above invocation of load_subclasses will return { 'feature' : <Feature object> }. The same kwargs (foo = bar) will be passed into the Feature class.

#!/usr/bin/env python3
import os, pkgutil, importlib, inspect

class ArgBaseClass():
    # Assign all keyword arguments as properties on self, and keep the kwargs for later.
    def __init__(self, **kwargs):
        self._kwargs = kwargs
        for (k, v) in kwargs.items():
            setattr(self, k, v)
        ms = inspect.getmembers(self, predicate=inspect.ismethod)
        self.methods = dict([(n, m) for (n, m) in ms if not n.startswith('_')])

    # Add the names of the methods to a parser object.
    def _parse_arguments(self, parser):
        parser.add_argument('method', choices=list(self.methods))
        return parser

    # Instantiate one of each of the subclasses of this class.
    def load_subclasses(self):
        module_dir = os.path.dirname(__file__)
        module_name = os.path.basename(os.path.normpath(module_dir))
        parent_class = self.__class__
        modules = {}
        # Load all the modules it the package:
        for (module_loader, name, ispkg) in pkgutil.iter_modules([module_dir]):
            modules[name] = importlib.import_module('.' + name, module_name)

        # Instantiate one of each class, passing the keyword arguments.
        ret = {}
        for cls in parent_class.__subclasses__():
            path = cls.__module__.split('.')
            ret[path[-1]] = cls(**self._kwargs)
        return ret

How do I convert Int/Decimal to float in C#?

You don't even need to cast, it is implicit.

int i = 3;

float f = i;

A full list/table of implicit numeric conversions can be seen here http://msdn.microsoft.com/en-us/library/y5b434w4.aspx

Regular expression field validation in jQuery

If you wanted to search some elements based on a regex, you can use the filter function. For example, say you wanted to make sure that in all the input boxes, the user has only entered numbers, so let's find all the inputs which don't match and highlight them.

$("input:text")
    .filter(function() {
        return this.value.match(/[^\d]/);
    })
    .addClass("inputError")
;

Of course if it was just something like this, you could use the form validation plugin, but this method could be applied to any sort of elements you like. Another example to show what I mean: Find all the elements whose id matches /[a-z]+_\d+/

$("[id]").filter(function() {
    return this.id.match(/[a-z]+_\d+/);
});

Checking if a key exists in a JS object

Above answers are good. But this is good too and useful.

!obj['your_key']  // if 'your_key' not in obj the result --> true

It's good for short style of code special in if statements:

if (!obj['your_key']){
    // if 'your_key' not exist in obj
    console.log('key not in obj');
} else {
    // if 'your_key' exist in obj
    console.log('key exist in obj');
}

Note: If your key be equal to null or "" your "if" statement will be wrong.

obj = {'a': '', 'b': null, 'd': 'value'}
!obj['a']    // result ---> true
!obj['b']    // result ---> true
!obj['c']    // result ---> true
!obj['d']    // result ---> false

So, best way for checking if a key exists in a obj is:'a' in obj

Conversion failed when converting the varchar value to data type int in sql

The problem located on the following line

SELECT  @Prefix + LEN(CAST(@maxCode AS VARCHAR(10))+1) + CAST(@maxCode AS VARCHAR(100))

Use this instead

SELECT  @Prefix + CAST(LEN(CAST(@maxCode AS VARCHAR(10))+1) AS VARCHAR(100)) + CAST(@maxCode AS VARCHAR(100))

Full Code:

CREATE PROC [dbo].[getVoucherNo]

AS

BEGIN

    DECLARE @Prefix VARCHAR(10)='J'

    DECLARE @startFrom INT=1

    DECLARE @maxCode VARCHAR(100)

    DECLARE @sCode INT

    IF((SELECT COUNT(*) FROM dbo.Journal_Entry) > 0)
    BEGIN
        SELECT @maxCode = CAST(MAX(CAST(SUBSTRING(VoucharNo,LEN(@startFrom)+1,LEN(VoucharNo)- LEN(@Prefix)) AS INT))+1 AS varchar(100)) FROM dbo.Journal_Entry;
        SET @sCode=CAST(@maxCode AS INT)
        SELECT  @Prefix + CAST(LEN(CAST(@maxCode AS VARCHAR(10))+1) AS VARCHAR(100)) + CAST(@maxCode AS VARCHAR(100))
    END
    ELSE
    BEGIN
        SELECT(@Prefix + CAST(@startFrom AS VARCHAR)) 
    END
END

jQuery datepicker set selected date, on the fly

or you can simply have

$('.date-pick').datePicker().val(new Date()).trigger('change')

how to add key value pair in the JSON object already declared

Object assign copies one or more source objects to the target object. So we could use Object.assign here.

Syntax: Object.assign(target, ...sources)

_x000D_
_x000D_
var obj  = {};_x000D_
_x000D_
Object.assign(obj, {"1":"aa", "2":"bb"})_x000D_
_x000D_
console.log(obj)
_x000D_
_x000D_
_x000D_

Pipenv: Command Not Found

This fixed it for me:

sudo -H pip install -U pipenv

Returning multiple values from a C++ function

It's entirely dependent upon the actual function and the meaning of the multiple values, and their sizes:

  • If they're related as in your fraction example, then I'd go with a struct or class instance.
  • If they're not really related and can't be grouped into a class/struct then perhaps you should refactor your method into two.
  • Depending upon the in-memory size of the values you're returning, you may want to return a pointer to a class instance or struct, or use reference parameters.

Windows batch script to unhide files hidden by virus

echo "Enter Drive letter" 
set /p driveletter=

attrib -s -h -a /s /d  %driveletter%:\*.*

Sort rows in data.table in decreasing order on string key `order(-x,v)` gives error on data.table 1.9.4 or earlier

Update

data.table v1.9.6+ now supports OP's original attempt and the following answer is no longer necessary.


You can use DT[order(-rank(x), y)].

   x y v
1: c 1 7
2: c 3 8
3: c 6 9
4: b 1 1
5: b 3 2
6: b 6 3
7: a 1 4
8: a 3 5
9: a 6 6

How to print to stderr in Python?

I am working in python 3.4.3. I am cutting out a little typing that shows how I got here:

[18:19 jsilverman@JSILVERMAN-LT7 pexpect]$ python3
>>> import sys
>>> print("testing", file=sys.stderr)
testing
>>>
[18:19 jsilverman@JSILVERMAN-LT7 pexpect]$ 

Did it work? Try redirecting stderr to a file and see what happens:

[18:22 jsilverman@JSILVERMAN-LT7 pexpect]$ python3 2> /tmp/test.txt
>>> import sys
>>> print("testing", file=sys.stderr)
>>> [18:22 jsilverman@JSILVERMAN-LT7 pexpect]$
[18:22 jsilverman@JSILVERMAN-LT7 pexpect]$ cat /tmp/test.txt
Python 3.4.3 (default, May  5 2015, 17:58:45)
[GCC 4.9.2] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
testing

[18:22 jsilverman@JSILVERMAN-LT7 pexpect]$

Well, aside from the fact that the little introduction that python gives you has been slurped into stderr (where else would it go?), it works.

How to rename with prefix/suffix?

In Bash and zsh you can do this with Brace Expansion. This simply expands a list of items in braces. For example:

# echo {vanilla,chocolate,strawberry}-ice-cream
vanilla-ice-cream chocolate-ice-cream strawberry-ice-cream

So you can do your rename as follows:

mv {,new.}original.filename

as this expands to:

mv original.filename new.original.filename

Bold & Non-Bold Text In A Single UILabel?

There's category based on bbrame's category. It works similar, but allows you boldify same UILabel multiple times with cumulative results.

UILabel+Boldify.h

@interface UILabel (Boldify)
- (void) boldSubstring: (NSString*) substring;
- (void) boldRange: (NSRange) range;
@end

UILabel+Boldify.m

@implementation UILabel (Boldify)
- (void)boldRange:(NSRange)range {
    if (![self respondsToSelector:@selector(setAttributedText:)]) {
        return;
    }
    NSMutableAttributedString *attributedText;
    if (!self.attributedText) {
        attributedText = [[NSMutableAttributedString alloc] initWithString:self.text];
    } else {
        attributedText = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    }
    [attributedText setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:self.font.pointSize]} range:range];
    self.attributedText = attributedText;
}

- (void)boldSubstring:(NSString*)substring {
    NSRange range = [self.text rangeOfString:substring];
    [self boldRange:range];
}
@end

With this corrections you may use it multiple times, eg:

myLabel.text = @"Updated: 2012/10/14 21:59 PM";
[myLabel boldSubstring: @"Updated:"];
[myLabel boldSubstring: @"21:59 PM"];

will result with: "Updated: 2012/10/14 21:59 PM".

How do I concatenate strings and variables in PowerShell?

I seem to struggle with this (and many other unintuitive things) every time I use PowerShell after time away from it, so I now opt for:

[string]::Concat("There are ", $count, " items in the list")

how to display data values on Chart.js

If you are using the plugin chartjs-plugin-datalabels then the following code options object will help

Make sure you import import 'chartjs-plugin-datalabels'; in your typescript file or add reference to <script src="chartjs-plugin-datalabels.js"></script> in your javascript file.

options: {
    maintainAspectRatio: false,
    responsive: true,
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true,
        }
      }]
    },
    plugins: {
      datalabels: {
        anchor: 'end',
        align: 'top',
        formatter: Math.round,
        font: {
          weight: 'bold'
        }
      }
    }
  }

IF/ELSE Stored Procedure

Just a tip for this, you don't need the BEGIN and END if it only contains a single statement.

ie:

IF(@Trans_type = 'subscr_signup')    
 set @tmpType = 'premium' 
ELSE iF(@Trans_type = 'subscr_cancel')  
     set    @tmpType = 'basic'

How to print HTML content on click of a button, but not the page?

_x000D_
_x000D_
@media print {
  .noPrint{
    display:none;
  }
}
h1{
  color:#f6f6;
}
_x000D_
<h1>
print me
</h1>
<h1 class="noPrint">
no print
</h1>
<button onclick="window.print();" class="noPrint">
Print Me
</button>
_x000D_
_x000D_
_x000D_

I came across another elegant solution for this:

Place your printable part inside a div with an id like this:

<div id="printableArea">
      <h1>Print me</h1>
</div>

<input type="button" onclick="printDiv('printableArea')" value="print a div!" />

Now let's create a really simple javascript:

function printDiv(divName) {
     var printContents = document.getElementById(divName).innerHTML;
     var originalContents = document.body.innerHTML;

     document.body.innerHTML = printContents;

     window.print();

     document.body.innerHTML = originalContents;
}

SOURCE : SO Answer

Jquery: Checking to see if div contains text, then action

Your code contains two problems:

  • The equality operator in JavaScript is ==, not =.
  • jQuery.text() joins all text nodes of matched elements into a single string. If you have two successive elements, of which the first contains 'some' and the second contains 'Text', then your code will incorrectly think that there exists an element that contains 'someText'.

I suggest the following instead:

if ($('#field > div.field-item:contains("someText")').length > 0) {
    $("#somediv").addClass("thisClass");
}

XMLHttpRequest cannot load file. Cross origin requests are only supported for HTTP

This error is happening because you are just opening html documents directly from the browser. To fix this you will need to serve your code from a webserver and access it on localhost. If you have Apache setup, use it to serve your files. Some IDE's have built in web servers, like JetBrains IDE's, Eclipse...

If you have Node.Js setup then you can use http-server. Just run npm install http-server -g and you will be able to use it in terminal like http-server C:\location\to\app. Kirill Fuchs

If you can decode JWT, how are they secure?

Let's discuss from the very beginning:

JWT is a very modern, simple and secure approach which extends for Json Web Tokens. Json Web Tokens are a stateless solution for authentication. So there is no need to store any session state on the server, which of course is perfect for restful APIs. Restful APIs should always be stateless, and the most widely used alternative to authentication with JWTs is to just store the user's log-in state on the server using sessions. But then of course does not follow the principle that says that restful APIs should be stateless and that's why solutions like JWT became popular and effective.

So now let's know how authentication actually works with Json Web Tokens. Assuming we already have a registered user in our database. So the user's client starts by making a post request with the username and the password, the application then checks if the user exists and if the password is correct, then the application will generate a unique Json Web Token for only that user.

The token is created using a secret string that is stored on a server. Next, the server then sends that JWT back to the client which will store it either in a cookie or in local storage. enter image description here

Just like this, the user is authenticated and basically logged into our application without leaving any state on the server.

So the server does in fact not know which user is actually logged in, but of course, the user knows that he's logged in because he has a valid Json Web Token which is a bit like a passport to access protected parts of the application.

So again, just to make sure you got the idea. A user is logged in as soon as he gets back his unique valid Json Web Token which is not saved anywhere on the server. And so this process is therefore completely stateless.

Then, each time a user wants to access a protected route like his user profile data, for example. He sends his Json Web Token along with a request, so it's a bit like showing his passport to get access to that route.

Once the request hits the server, our app will then verify if the Json Web Token is actually valid and if the user is really who he says he is, well then the requested data will be sent to the client and if not, then there will be an error telling the user that he's not allowed to access that resource. enter image description here

All this communication must happen over https, so secure encrypted Http in order to prevent that anyone can get access to passwords or Json Web Tokens. Only then we have a really secure system.

enter image description here

So a Json Web Token looks like left part of this screenshot which was taken from the JWT debugger at jwt.io. So essentially, it's an encoding string made up of three parts. The header, the payload and the signature Now the header is just some metadata about the token itself and the payload is the data that we can encode into the token, any data really that we want. So the more data we want to encode here the bigger the JWT. Anyway, these two parts are just plain text that will get encoded, but not encrypted.

So anyone will be able to decode them and to read them, we cannot store any sensitive data in here. But that's not a problem at all because in the third part, so in the signature, is where things really get interesting. The signature is created using the header, the payload, and the secret that is saved on the server.

And this whole process is then called signing the Json Web Token. The signing algorithm takes the header, the payload, and the secret to create a unique signature. So only this data plus the secret can create this signature, all right? Then together with the header and the payload, these signature forms the JWT, which then gets sent to the client. enter image description here

Once the server receives a JWT to grant access to a protected route, it needs to verify it in order to determine if the user really is who he claims to be. In other words, it will verify if no one changed the header and the payload data of the token. So again, this verification step will check if no third party actually altered either the header or the payload of the Json Web Token.

So, how does this verification actually work? Well, it is actually quite straightforward. Once the JWT is received, the verification will take its header and payload, and together with the secret that is still saved on the server, basically create a test signature.

But the original signature that was generated when the JWT was first created is still in the token, right? And that's the key to this verification. Because now all we have to do is to compare the test signature with the original signature. And if the test signature is the same as the original signature, then it means that the payload and the header have not been modified. enter image description here

Because if they had been modified, then the test signature would have to be different. Therefore in this case where there has been no alteration of the data, we can then authenticate the user. And of course, if the two signatures are actually different, well, then it means that someone tampered with the data. Usually by trying to change the payload. But that third party manipulating the payload does of course not have access to the secret, so they cannot sign the JWT. So the original signature will never correspond to the manipulated data. And therefore, the verification will always fail in this case. And that's the key to making this whole system work. It's the magic that makes JWT so simple, but also extremely powerful.

How do servlets work? Instantiation, sessions, shared variables and multithreading

Session in Java servlets is the same as session in other languages such as PHP. It is unique to the user. The server can keep track of it in different ways such as cookies, url rewriting etc. This Java doc article explains it in the context of Java servlets and indicates that exactly how session is maintained is an implementation detail left to the designers of the server. The specification only stipulates that it must be maintained as unique to a user across multiple connections to the server. Check out this article from Oracle for more information about both of your questions.

Edit There is an excellent tutorial here on how to work with session inside of servlets. And here is a chapter from Sun about Java Servlets, what they are and how to use them. Between those two articles, you should be able to answer all of your questions.

Find html label associated with a given input

First, scan the page for labels, and assign a reference to the label from the actual form element:

var labels = document.getElementsByTagName('LABEL');
for (var i = 0; i < labels.length; i++) {
    if (labels[i].htmlFor != '') {
         var elem = document.getElementById(labels[i].htmlFor);
         if (elem)
            elem.label = labels[i];         
    }
}

Then, you can simply go:

document.getElementById('MyFormElem').label.innerHTML = 'Look ma this works!';

No need for a lookup array :)

Apply CSS style attribute dynamically in Angular JS

Directly from ngStyle docs:

Expression which evals to an object whose keys are CSS style names and values are corresponding values for those CSS keys.

<div ng-style="{'width': '20px', 'height': '20px', ...}"></div>

So you could do this:

<div ng-style="{'background-color': data.backgroundCol}"></div>

Hope this helps!

How do you determine what SQL Tables have an identity column programmatically

sys.columns.is_identity = 1

e.g.,

select o.name, c.name
from sys.objects o inner join sys.columns c on o.object_id = c.object_id
where c.is_identity = 1

How do I fix a merge conflict due to removal of a file in a branch?

I normally just run git mergetool and it will prompt me if I want to keep the modified file or keep it deleted. This is the quickest way IMHO since it's one command instead of several per file.

If you have a bunch of deleted files in a specific subdirectory and you want all of them to be resolved by deleting the files, you can do this:

yes d | git mergetool -- the/subdirectory

The d is provided to choose deleting each file. You can also use m to keep the modified file. Taken from the prompt you see when you run mergetool:

Use (m)odified or (d)eleted file, or (a)bort?

How to get cumulative sum

Select *, (Select SUM(SOMENUMT) From @t S Where S.id <= M.id) From @t M

Unpacking a list / tuple of pairs into two lists / tuples

>>> source_list = ('1','a'),('2','b'),('3','c'),('4','d')
>>> list1, list2 = zip(*source_list)
>>> list1
('1', '2', '3', '4')
>>> list2
('a', 'b', 'c', 'd')

Edit: Note that zip(*iterable) is its own inverse:

>>> list(source_list) == zip(*zip(*source_list))
True

When unpacking into two lists, this becomes:

>>> list1, list2 = zip(*source_list)
>>> list(source_list) == zip(list1, list2)
True

Addition suggested by rocksportrocker.

LaTeX: remove blank page after a \part or \chapter

Although I guess you do not need an answer any longer, I am giving the solution for those who will come to see this post.

Derived from book.cls

\def\@endpart{\vfil\newpage
              \if@twoside
                \null
                \thispagestyle{empty}%
                \newpage
              \fi
              \if@tempswa
                \twocolumn
              \fi}

It is "\newpage" at the first line of this fragment that adds a redundant blank page after the part header page. So you must redefine the command \@endpart. Add the following snippet to the beggining of your tex file.

\makeatletter
\renewcommand\@endpart{\vfil
              \if@twoside
                \null
                \thispagestyle{empty}%
                \newpage
              \fi
              \if@tempswa
                \twocolumn
              \fi}
\makeatother

How do I make a Windows batch script completely silent?

Just add a >NUL at the end of the lines producing the messages.

For example,

COPY %scriptDirectory%test.bat %scriptDirectory%test2.bat >NUL

Running Node.js in apache?

If you're using PHP you can funnel your request to Node scripts via shell_exec, passing arguments to scripts as JSON strings in the command line. Example call:

<?php
    shell_exec("node nodeScript.js"); // without arguments
    shell_exec("node nodeScript.js '{[your JSON here]}'"); //with arguments
?>

The caveat is you need to be very careful about handling user data when it goes anywhere near a command line. Example nightmare:

<?php
    $evilUserData = "'; [malicious commands here];";
    shell_exec("node nodeScript.js '{$evilUserData}'");
?>

Use Async/Await with Axios in React.js

In my experience over the past few months, I've realized that the best way to achieve this is:

class App extends React.Component{
  constructor(){
   super();
   this.state = {
    serverResponse: ''
   }
  }
  componentDidMount(){
     this.getData();
  }
  async getData(){
   const res = await axios.get('url-to-get-the-data');
   const { data } = await res;
   this.setState({serverResponse: data})
 }
 render(){
  return(
     <div>
       {this.state.serverResponse}
     </div>
  );
 }
}

If you are trying to make post request on events such as click, then call getData() function on the event and replace the content of it like so:

async getData(username, password){
 const res = await axios.post('url-to-post-the-data', {
   username,
   password
 });
 ...
}

Furthermore, if you are making any request when the component is about to load then simply replace async getData() with async componentDidMount() and change the render function like so:

render(){
 return (
  <div>{this.state.serverResponse}</div>
 )
}

What is the correct XPath for choosing attributes that contain "foo"?

descendant-or-self::*[contains(@prop,'Foo')]

Or:

/bla/a[contains(@prop,'Foo')]

Or:

/bla/a[position() <= 3]

Dissected:

descendant-or-self::

The Axis - search through every node underneath and the node itself. It is often better to say this than //. I have encountered some implementations where // means anywhere (decendant or self of the root node). The other use the default axis.

* or /bla/a

The Tag - a wildcard match, and /bla/a is an absolute path.

[contains(@prop,'Foo')] or [position() <= 3]

The condition within [ ]. @prop is shorthand for attribute::prop, as attribute is another search axis. Alternatively you can select the first 3 by using the position() function.

SQL Server: Database stuck in "Restoring" state

Use the following command to solve this issue

RESTORE DATABASE [DatabaseName] WITH RECOVERY

Inner join vs Where

[For a bonus point...]

Using the JOIN syntax allows you to more easily comment out the join as its all included on one line. This can be useful if you are debugging a complex query

As everyone else says, they are functionally the same, however the JOIN is more clear of a statement of intent. It therefore may help the query optimiser either in current oracle versions in certain cases (I have no idea if it does), it may help the query optimiser in future versions of Oracle (no-one has any idea), or it may help if you change database supplier.

How to use random in BATCH script?

You'll probably want to get several random numbers, and may want to be able to specify a different range for each one, so you should define a function. In my example, I generate numbers from 25 through 30 with call:rand 25 30. And the result is in RAND_NUM after that function exits.

@echo off & setlocal EnableDelayedExpansion

for /L %%a in (1 1 10) do (
        call:rand 25 30
        echo !RAND_NUM!
)

goto:EOF

REM The script ends at the above goto:EOF.  The following are functions.

REM rand()
REM Input: %1 is min, %2 is max.
REM Output: RAND_NUM is set to a random number from min through max.
:rand
SET /A RAND_NUM=%RANDOM% * (%2 - %1 + 1) / 32768 + %1
goto:EOF

Service has zero application (non-infrastructure) endpoints

To prepare the configration for WCF is hard, and sometimes a service type definition go unnoticed.

I wrote only the namespace in the service tag, so I got the same error.

<service name="ServiceNameSpace">

Do not forget, the service tag needs a fully-qualified service class name.

<service name="ServiceNameSpace.ServiceClass">

For the other folks who are like me.

How Spring Security Filter Chain works

The Spring security filter chain is a very complex and flexible engine.

Key filters in the chain are (in the order)

  • SecurityContextPersistenceFilter (restores Authentication from JSESSIONID)
  • UsernamePasswordAuthenticationFilter (performs authentication)
  • ExceptionTranslationFilter (catch security exceptions from FilterSecurityInterceptor)
  • FilterSecurityInterceptor (may throw authentication and authorization exceptions)

Looking at the current stable release 4.2.1 documentation, section 13.3 Filter Ordering you could see the whole filter chain's filter organization:

13.3 Filter Ordering

The order that filters are defined in the chain is very important. Irrespective of which filters you are actually using, the order should be as follows:

  1. ChannelProcessingFilter, because it might need to redirect to a different protocol

  2. SecurityContextPersistenceFilter, so a SecurityContext can be set up in the SecurityContextHolder at the beginning of a web request, and any changes to the SecurityContext can be copied to the HttpSession when the web request ends (ready for use with the next web request)

  3. ConcurrentSessionFilter, because it uses the SecurityContextHolder functionality and needs to update the SessionRegistry to reflect ongoing requests from the principal

  4. Authentication processing mechanisms - UsernamePasswordAuthenticationFilter, CasAuthenticationFilter, BasicAuthenticationFilter etc - so that the SecurityContextHolder can be modified to contain a valid Authentication request token

  5. The SecurityContextHolderAwareRequestFilter, if you are using it to install a Spring Security aware HttpServletRequestWrapper into your servlet container

  6. The JaasApiIntegrationFilter, if a JaasAuthenticationToken is in the SecurityContextHolder this will process the FilterChain as the Subject in the JaasAuthenticationToken

  7. RememberMeAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, and the request presents a cookie that enables remember-me services to take place, a suitable remembered Authentication object will be put there

  8. AnonymousAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, an anonymous Authentication object will be put there

  9. ExceptionTranslationFilter, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate AuthenticationEntryPoint can be launched

  10. FilterSecurityInterceptor, to protect web URIs and raise exceptions when access is denied

Now, I'll try to go on by your questions one by one:

I'm confused how these filters are used. Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not? Does the form-login namespace element auto-configure these filters? Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Once you are configuring a <security-http> section, for each one you must at least provide one authentication mechanism. This must be one of the filters which match group 4 in the 13.3 Filter Ordering section from the Spring Security documentation I've just referenced.

This is the minimum valid security:http element which can be configured:

<security:http authentication-manager-ref="mainAuthenticationManager" 
               entry-point-ref="serviceAccessDeniedHandler">
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
</security:http>

Just doing it, these filters are configured in the filter chain proxy:

{
        "1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
        "2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
        "3": "org.springframework.security.web.header.HeaderWriterFilter",
        "4": "org.springframework.security.web.csrf.CsrfFilter",
        "5": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
        "6": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
        "7": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
        "8": "org.springframework.security.web.session.SessionManagementFilter",
        "9": "org.springframework.security.web.access.ExceptionTranslationFilter",
        "10": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
    }

Note: I get them by creating a simple RestController which @Autowires the FilterChainProxy and returns it's contents:

    @Autowired
    private FilterChainProxy filterChainProxy;

    @Override
    @RequestMapping("/filterChain")
    public @ResponseBody Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        return this.getSecurityFilterChainProxy();
    }

    public Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        Map<Integer, Map<Integer, String>> filterChains= new HashMap<Integer, Map<Integer, String>>();
        int i = 1;
        for(SecurityFilterChain secfc :  this.filterChainProxy.getFilterChains()){
            //filters.put(i++, secfc.getClass().getName());
            Map<Integer, String> filters = new HashMap<Integer, String>();
            int j = 1;
            for(Filter filter : secfc.getFilters()){
                filters.put(j++, filter.getClass().getName());
            }
            filterChains.put(i++, filters);
        }
        return filterChains;
    }

Here we could see that just by declaring the <security:http> element with one minimum configuration, all the default filters are included, but none of them is of a Authentication type (4th group in 13.3 Filter Ordering section). So it actually means that just by declaring the security:http element, the SecurityContextPersistenceFilter, the ExceptionTranslationFilter and the FilterSecurityInterceptor are auto-configured.

In fact, one authentication processing mechanism should be configured, and even security namespace beans processing claims for that, throwing an error during startup, but it can be bypassed adding an entry-point-ref attribute in <http:security>

If I add a basic <form-login> to the configuration, this way:

<security:http authentication-manager-ref="mainAuthenticationManager">
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
    <security:form-login />
</security:http>

Now, the filterChain will be like this:

{
        "1": "org.springframework.security.web.context.SecurityContextPersistenceFilter",
        "2": "org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter",
        "3": "org.springframework.security.web.header.HeaderWriterFilter",
        "4": "org.springframework.security.web.csrf.CsrfFilter",
        "5": "org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter",
        "6": "org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter",
        "7": "org.springframework.security.web.savedrequest.RequestCacheAwareFilter",
        "8": "org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter",
        "9": "org.springframework.security.web.authentication.AnonymousAuthenticationFilter",
        "10": "org.springframework.security.web.session.SessionManagementFilter",
        "11": "org.springframework.security.web.access.ExceptionTranslationFilter",
        "12": "org.springframework.security.web.access.intercept.FilterSecurityInterceptor"
    }

Now, this two filters org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter and org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter are created and configured in the FilterChainProxy.

So, now, the questions:

Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not?

Yes, it is used to try to complete a login processing mechanism in case the request matches the UsernamePasswordAuthenticationFilter url. This url can be configured or even changed it's behaviour to match every request.

You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy (such as HttpBasic, CAS, etc).

Does the form-login namespace element auto-configure these filters?

No, the form-login element configures the UsernamePasswordAUthenticationFilter, and in case you don't provide a login-page url, it also configures the org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter, which ends in a simple autogenerated login page.

The other filters are auto-configured by default just by creating a <security:http> element with no security:"none" attribute.

Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Every request should reach it, as it is the element which takes care of whether the request has the rights to reach the requested url. But some of the filters processed before might stop the filter chain processing just not calling FilterChain.doFilter(request, response);. For example, a CSRF filter might stop the filter chain processing if the request has not the csrf parameter.

What if I want to secure my REST API with JWT-token, which is retrieved from login? I must configure two namespace configuration http tags, rights? Other one for /login with UsernamePasswordAuthenticationFilter, and another one for REST url's, with custom JwtAuthenticationFilter.

No, you are not forced to do this way. You could declare both UsernamePasswordAuthenticationFilter and the JwtAuthenticationFilter in the same http element, but it depends on the concrete behaviour of each of this filters. Both approaches are possible, and which one to choose finnally depends on own preferences.

Does configuring two http elements create two springSecurityFitlerChains?

Yes, that's true

Is UsernamePasswordAuthenticationFilter turned off by default, until I declare form-login?

Yes, you could see it in the filters raised in each one of the configs I posted

How do I replace SecurityContextPersistenceFilter with one, which will obtain Authentication from existing JWT-token rather than JSESSIONID?

You could avoid SecurityContextPersistenceFilter, just configuring session strategy in <http:element>. Just configure like this:

<security:http create-session="stateless" >

Or, In this case you could overwrite it with another filter, this way inside the <security:http> element:

<security:http ...>  
   <security:custom-filter ref="myCustomFilter" position="SECURITY_CONTEXT_FILTER"/>    
</security:http>
<beans:bean id="myCustomFilter" class="com.xyz.myFilter" />

EDIT:

One question about "You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy". Will the latter overwrite the authentication performed by first one, if declaring multiple (Spring implementation) authentication filters? How this relates to having multiple authentication providers?

This finally depends on the implementation of each filter itself, but it's true the fact that the latter authentication filters at least are able to overwrite any prior authentication eventually made by preceding filters.

But this won't necesarily happen. I have some production cases in secured REST services where I use a kind of authorization token which can be provided both as a Http header or inside the request body. So I configure two filters which recover that token, in one case from the Http Header and the other from the request body of the own rest request. It's true the fact that if one http request provides that authentication token both as Http header and inside the request body, both filters will try to execute the authentication mechanism delegating it to the manager, but it could be easily avoided simply checking if the request is already authenticated just at the begining of the doFilter() method of each filter.

Having more than one authentication filter is related to having more than one authentication providers, but don't force it. In the case I exposed before, I have two authentication filter but I only have one authentication provider, as both of the filters create the same type of Authentication object so in both cases the authentication manager delegates it to the same provider.

And opposite to this, I too have a scenario where I publish just one UsernamePasswordAuthenticationFilter but the user credentials both can be contained in DB or LDAP, so I have two UsernamePasswordAuthenticationToken supporting providers, and the AuthenticationManager delegates any authentication attempt from the filter to the providers secuentially to validate the credentials.

So, I think it's clear that neither the amount of authentication filters determine the amount of authentication providers nor the amount of provider determine the amount of filters.

Also, documentation states SecurityContextPersistenceFilter is responsible of cleaning the SecurityContext, which is important due thread pooling. If I omit it or provide custom implementation, I have to implement the cleaning manually, right? Are there more similar gotcha's when customizing the chain?

I did not look carefully into this filter before, but after your last question I've been checking it's implementation, and as usually in Spring, nearly everything could be configured, extended or overwrited.

The SecurityContextPersistenceFilter delegates in a SecurityContextRepository implementation the search for the SecurityContext. By default, a HttpSessionSecurityContextRepository is used, but this could be changed using one of the constructors of the filter. So it may be better to write an SecurityContextRepository which fits your needs and just configure it in the SecurityContextPersistenceFilter, trusting in it's proved behaviour rather than start making all from scratch.

What is the proper use of an EventEmitter?

Yes, go ahead and use it.

EventEmitter is a public, documented type in the final Angular Core API. Whether or not it is based on Observable is irrelevant; if its documented emit and subscribe methods suit what you need, then go ahead and use it.

As also stated in the docs:

Uses Rx.Observable but provides an adapter to make it work as specified here: https://github.com/jhusain/observable-spec

Once a reference implementation of the spec is available, switch to it.

So they wanted an Observable like object that behaved in a certain way, they implemented it, and made it public. If it were merely an internal Angular abstraction that shouldn't be used, they wouldn't have made it public.

There are plenty of times when it's useful to have an emitter which sends events of a specific type. If that's your use case, go for it. If/when a reference implementation of the spec they link to is available, it should be a drop-in replacement, just as with any other polyfill.

Just be sure that the generator you pass to the subscribe() function follows the linked spec. The returned object is guaranteed to have an unsubscribe method which should be called to free any references to the generator (this is currently an RxJs Subscription object but that is indeed an implementation detail which should not be depended on).

export class MyServiceEvent {
    message: string;
    eventId: number;
}

export class MyService {
    public onChange: EventEmitter<MyServiceEvent> = new EventEmitter<MyServiceEvent>();

    public doSomething(message: string) {
        // do something, then...
        this.onChange.emit({message: message, eventId: 42});
    }
}

export class MyConsumer {
    private _serviceSubscription;

    constructor(private service: MyService) {
        this._serviceSubscription = this.service.onChange.subscribe({
            next: (event: MyServiceEvent) => {
                console.log(`Received message #${event.eventId}: ${event.message}`);
            }
        })
    }

    public consume() {
        // do some stuff, then later...

        this.cleanup();
    }

    private cleanup() {
        this._serviceSubscription.unsubscribe();
    }
}

All of the strongly-worded doom and gloom predictions seem to stem from a single Stack Overflow comment from a single developer on a pre-release version of Angular 2.

String Concatenation using '+' operator

It doesn't - the C# compiler does :)

So this code:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y which then needs to be copied again as part of the concatenation of (x + y) and z. Instead, we get it all done in one go.

EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.

Wireshark localhost traffic capture

On Windows platform, it is also possible to capture localhost traffic using Wireshark. What you need to do is to install the Microsoft loopback adapter, and then sniff on it.

What is the difference between <p> and <div>?

They have semantic difference - a <div> element is designed to describe a container of data whereas a <p> element is designed to describe a paragraph of content.

The semantics make all the difference. HTML is a markup language which means that it is designed to "mark up" content in a way that is meaningful to the consumer of the markup. Most developers believe that the semantics of the document are the default styles and rendering that browsers apply to these elements but that is not the case.

The elements that you choose to mark up your content should describe the content. Don't mark up your document based on how it should look - mark it up based on what it is.

If you need a generic container purely for layout purposes then use a <div>. If you need an element to describe a paragraph of content then use a <p>.

Note: It is important to understand that both <div> and <p> are block-level elements which means that most browsers will treat them in a similar fashion.

RGB to hex and hex to RGB

Shorthand version that accepts a string:

_x000D_
_x000D_
function rgbToHex(a){_x000D_
  a=a.replace(/[^\d,]/g,"").split(","); _x000D_
  return"#"+((1<<24)+(+a[0]<<16)+(+a[1]<<8)+ +a[2]).toString(16).slice(1)_x000D_
}_x000D_
_x000D_
document.write(rgbToHex("rgb(255,255,255)"));
_x000D_
_x000D_
_x000D_

To check if it's not already hexadecimal

_x000D_
_x000D_
function rgbToHex(a){_x000D_
  if(~a.indexOf("#"))return a;_x000D_
  a=a.replace(/[^\d,]/g,"").split(","); _x000D_
  return"#"+((1<<24)+(+a[0]<<16)+(+a[1]<<8)+ +a[2]).toString(16).slice(1)_x000D_
}_x000D_
_x000D_
document.write("rgb: "+rgbToHex("rgb(255,255,255)")+ " -- hex: "+rgbToHex("#e2e2e2"));
_x000D_
_x000D_
_x000D_

What's NSLocalizedString equivalent in Swift?

Helpfull for usage in unit tests:

This is a simple version which can be extended to different use cases (e.g. with the use of tableNames).

public func NSLocalizedString(key: String, referenceClass: AnyClass, comment: String = "") -> String 
{
    let bundle = NSBundle(forClass: referenceClass)
    return NSLocalizedString(key, tableName:nil, bundle: bundle, comment: comment)
}

Use it like this:

NSLocalizedString("YOUR-KEY", referenceClass: self)

Or like this with a comment:

NSLocalizedString("YOUR-KEY", referenceClass: self, comment: "usage description")

Do Java arrays have a maximum size?

Maximum number of elements of an array is (2^31)-1 or 2 147 483 647

How to run ssh-add on windows?

If you are trying to setup a key for using git with ssh, there's always an option to add a configuration for the identity file.

vi ~/.ssh/config

Host example.com
IdentityFile ~/.ssh/example_key

How to POST using HTTPclient content type = application/x-www-form-urlencoded

Another variant to POST this content type and which does not use a dictionary would be:

StringContent postData = new StringContent(JSON_CONTENT, Encoding.UTF8, "application/x-www-form-urlencoded");
using (HttpResponseMessage result = httpClient.PostAsync(url, postData).Result)
{
    string resultJson = result.Content.ReadAsStringAsync().Result;
}

How do I read / convert an InputStream into a String in Java?

Guava provides much shorter efficient autoclosing solution in case when input stream comes from classpath resource (which seems to be popular task):

byte[] bytes = Resources.toByteArray(classLoader.getResource(path));

or

String text = Resources.toString(classLoader.getResource(path), StandardCharsets.UTF_8);

There is also general concept of ByteSource and CharSource that gently take care of both opening and closing the stream.

So, for example, instead of explicitly opening a small file to read its contents:

String content = Files.asCharSource(new File("robots.txt"), StandardCharsets.UTF_8).read();
byte[] data = Files.asByteSource(new File("favicon.ico")).read();

or just

String content = Files.toString(new File("robots.txt"), StandardCharsets.UTF_8);
byte[] data = Files.toByteArray(new File("favicon.ico"));

Reshape an array in NumPy

numpy has a great tool for this task ("numpy.reshape") link to reshape documentation

a = [[ 0  1]
 [ 2  3]
 [ 4  5]
 [ 6  7]
 [ 8  9]
 [10 11]
 [12 13]
 [14 15]
 [16 17]]

`numpy.reshape(a,(3,3))`

you can also use the "-1" trick

`a = a.reshape(-1,3)`

the "-1" is a wild card that will let the numpy algorithm decide on the number to input when the second dimension is 3

so yes.. this would also work: a = a.reshape(3,-1)

and this: a = a.reshape(-1,2) would do nothing

and this: a = a.reshape(-1,9) would change the shape to (2,9)

What is the difference between display: inline and display: inline-block?

One thing not mentioned in answers is inline element can break among lines while inline-block can't (and obviously block)! So inline elements can be useful to style sentences of text and blocks inside them, but as they can't be padded you can use line-height instead.

_x000D_
_x000D_
<div style="width: 350px">_x000D_
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
  <div style="display: inline; background: #F00; color: #FFF">_x000D_
    Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
  </div>_x000D_
  Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
</div>_x000D_
<hr/>_x000D_
<div style="width: 350px">_x000D_
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
  <div style="display: inline-block; background: #F00; color: #FFF">_x000D_
    Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
  </div>_x000D_
  Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
</div>
_x000D_
_x000D_
_x000D_

enter image description here

How can I change the text color with jQuery?

Nowadays, animating text color is included in the jQuery UI Effects Core. It's pretty small. You can make a custom download here: http://jqueryui.com/download - but you don't actually need anything but the effects core itself (not even the UI core), and it brings with it different easing functions as well.

AngularJS $http-post - convert binary to excel file and download

Download the server response as an array buffer. Store it as a Blob using the content type from the server (which should be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet):

var httpPromise = this.$http.post(server, postData, { responseType: 'arraybuffer' });
httpPromise.then(response => this.save(new Blob([response.data],
    { type: response.headers('Content-Type') }), fileName));

Save the blob to the user's device:

save(blob, fileName) {
    if (window.navigator.msSaveOrOpenBlob) { // For IE:
        navigator.msSaveBlob(blob, fileName);
    } else { // For other browsers:
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(link.href);
    }
}

validate a dropdownlist in asp.net mvc

I just can't believe that there are people still using ViewData/ViewBag in ASP.NET MVC 3 instead of having strongly typed views and view models:

public class MyViewModel
{
    [Required]
    public string CategoryId { get; set; }

    public IEnumerable<Category> Categories { get; set; }
}

and in your controller:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            Categories = Repository.GetCategories()
        }
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            // there was a validation error =>
            // rebind categories and redisplay view
            model.Categories = Repository.GetCategories();
            return View(model);
        }
        // At this stage the model is OK => do something with the selected category
        return RedirectToAction("Success");
    }
}

and then in your strongly typed view:

@Html.DropDownListFor(
    x => x.CategoryId, 
    new SelectList(Model.Categories, "ID", "CategoryName"), 
    "-- Please select a category --"
)
@Html.ValidationMessageFor(x => x.CategoryId)

Also if you want client side validation don't forget to reference the necessary scripts:

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

How to pip or easy_install tkinter on Windows

I had the similar problem with Win-8 and python-3.4 32 bit , I got it resolved by downloading same version from python.org .

Next step will be to hit the repair button and Install the Tk/tkinter Package or Just hit the repair. Now should get Python34/Lib/tkinter Module present. The import tkinter should work ..

How to make an input type=button act like a hyperlink and redirect using a get request?

I think that is your need.

a href="#" onclick="document.forms[0].submit();return false;"

How can I quickly and easily convert spreadsheet data to JSON?

Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:

  1. Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:

    Rory Gallagher      Guitar
    Gerry McAvoy        Bass
    Rod de'Ath          Drums
    Lou Martin          Keyboards
    Donkey Kong Sioux   Self-Appointed Semi-official Stomper
    

    Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)

  2. Save the file as a CSV file.

  3. Copy the contents of the CSV file to the clipboard

  4. Go to http://www.convertcsv.com/csv-to-json.htm

  5. Verify that the "First row is column names" checkbox is checked

  6. Paste the CSV data into the content area

  7. Mash the "Convert CSV to JSON" button

    With the data shown above, you will now have:

    [
      {
        "MUSICIAN":"Rory Gallagher",
        "INSTRUMENT":"Guitar"
      },
      {
        "MUSICIAN":"Gerry McAvoy",
        "INSTRUMENT":"Bass"
      },
      {
        "MUSICIAN":"Rod D'Ath",
        "INSTRUMENT":"Drums"
      },
      {
        "MUSICIAN":"Lou Martin",
        "INSTRUMENT":"Keyboards"
      }
      {
        "MUSICIAN":"Donkey Kong Sioux",
        "INSTRUMENT":"Self-Appointed Semi-Official Stomper"
      }
    ]
    

    With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.

  8. Go here: http://jsonlint.com/

  9. Paste the JSON into the content area

  10. Pres the "Validate" button.

If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

Tried to download Gapps app and install it on Genymotion, but realized that its already included within the emulator itself

https://www.genymotion.com/blog/2-10-open-gapps-widget/

Git diff says subproject is dirty

In my case I wasn't sure what had caused this to happen, but I knew I just wanted the submodules to be reset to their latest remote commit and be done with it. This involved combining answers from a couple of different questions on here:

git submodule update --recursive --remote --init

Sources:

How do I revert my changes to a git submodule?

Easy way to pull latest of all git submodules

Change color of Button when Mouse is over

Try this- In this example Original color is green and mouseover color will be DarkGoldenrod

<Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="50" Height="50" HorizontalContentAlignment="Left" BorderBrush="{x:Null}" Foreground="{x:Null}" Margin="50,0,0,0">
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Background" Value="Green"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border Background="{TemplateBinding Background}">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Background" Value="DarkGoldenrod"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

How do I find numeric columns in Pandas?

Please see the below code:

if(dataset.select_dtypes(include=[np.number]).shape[1] > 0):
display(dataset.select_dtypes(include=[np.number]).describe())
if(dataset.select_dtypes(include=[np.object]).shape[1] > 0):
display(dataset.select_dtypes(include=[np.object]).describe())

This way you can check whether the value are numeric such as float and int or the srting values. the second if statement is used for checking the string values which is referred by the object.

"ImportError: No module named" when trying to run Python script

This answer applies to this question if

  1. You don't want to change your code
  2. You don't want to change PYTHONPATH permanently

Temporarily modify PYTHONPATH

path below can be relative

PYTHONPATH=/path/to/dir python script.py

Retrieve the maximum length of a VARCHAR column in SQL Server

For IBM Db2 its LENGTH, not LEN:

SELECT MAX(LENGTH(Desc)) FROM table_name;

Adding and removing style attribute from div with jquery

In case of .css method in jQuery for !important rule will not apply.

In this case we should use .attr function.

For Example: If you want to add style as below:

<div id='voltaic_holder' style='position:absolute;top:-75px !important'>

You should use:

$("#voltaic_holder").attr("style", "position:absolute;top:-75px !important");

Hope it helps some one.

C pass int array pointer as parameter into a function

Maybe you were trying to do this?

#include <stdio.h>

int func(int * B){

    /* B + OFFSET = 5 () You are pointing to the same region as B[OFFSET] */
    *(B + 2) = 5;
}

int main(void) {

    int B[10];

    func(B);

    /* Let's say you edited only 2 and you want to show it. */
    printf("b[0] = %d\n\n", B[2]);

    return 0;
}

Can't specify the 'async' modifier on the 'Main' method of a console app

C# 7.1 (using vs 2017 update 3) introduces async main

You can write:

   static async Task Main(string[] args)
  {
    await ...
  }

For more details C# 7 Series, Part 2: Async Main

Update:

You may get a compilation error:

Program does not contain a static 'Main' method suitable for an entry point

This error is due to that vs2017.3 is configured by default as c#7.0 not c#7.1.

You should explicitly modify the setting of your project to set c#7.1 features.

You can set c#7.1 by two methods:

Method 1: Using the project settings window:

  • Open the settings of your project
  • Select the Build tab
  • Click the Advanced button
  • Select the version you want As shown in the following figure:

enter image description here

Method2: Modify PropertyGroup of .csproj manually

Add this property:

    <LangVersion>7.1</LangVersion>

example:

    <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
        <PlatformTarget>AnyCPU</PlatformTarget>
        <DebugSymbols>true</DebugSymbols>
        <DebugType>full</DebugType>
        <Optimize>false</Optimize>
        <OutputPath>bin\Debug\</OutputPath>
        <DefineConstants>DEBUG;TRACE</DefineConstants>
        <ErrorReport>prompt</ErrorReport>
        <WarningLevel>4</WarningLevel>
        <Prefer32Bit>false</Prefer32Bit>
        <LangVersion>7.1</LangVersion>
    </PropertyGroup>    

You have not concluded your merge (MERGE_HEAD exists)

Try changing any temporary file. Like just remove any space or add space and then commit and push that file.

git add 'temporary_change_file'

git commit -m "git issue resolving"

git push origin develop

And then try git pull,

git pull origin develop

Hope this might help you.

Working copy XXX locked and cleanup failed in SVN

For me, it was actually Tortoise's fault, sort of. Tortoise just complained "cannot clean up, run clean up", but when I ran the command line (svn cleanup), it clearly told me that it couldn't delete some files that were in use, the solution to which was obvious. Once I closed Visual Studio (which was keeping the files open), then the cleanup worked fine.

Other programs can also keep files open in the repo causing this issue. Excel holding an xls open was a culprit in another instance so it may be wise to close all programs that may be using anything in the repo or even rebooting to force programs to close out and then trying cleanup again.

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive

following 2 steps will force refresh Visual Studio and IIS Express cache and usually resolve my similar issues:

  1. Simply switch Project framework from 4+ to .Net framework 3.5 and run it
  2. If it ran successfully you can revert it back to your desired 4+ target framework and see that it will probably work again.

What is the use of the @ symbol in PHP?

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

If you have set a custom error handler function with set_error_handler() then it will still get called, but this custom error handler can (and should) call error_reporting() which will return 0 when the call that triggered the error was preceded by an @.

<?php
/* Intentional file error */
$my_file = @file ('non_existent_file') or
    die ("Failed opening file: error was '$php_errormsg'");

// this works for any expression, not just functions:
$value = @$cache[$key];
// will not issue a notice if the index $key doesn't exist.

?>

Note:-

1) The @-operator works only on expressions.

2) A simple rule of thumb is: if you can take the value of something, you can prepend the @ operator to it. For instance, you can prepend it to variables, function and include calls, constants, and so forth. You cannot prepend it to function or class definitions, or conditional structures such as if and foreach, and so forth.

Warning:-

Currently the "@" error-control operator prefix will even disable error reporting for critical errors that will terminate script execution. Among other things, this means that if you use "@" to suppress errors from a certain function and either it isn't available or has been mistyped, the script will die right there with no indication as to why.

C# : Converting Base Class to Child Class

As long as the object is actually a SkyfilterClient, then a cast should work. Here is a contrived example to prove this:

using System;

class Program
{
    static void Main()
    {
        NetworkClient net = new SkyfilterClient();
        var sky = (SkyfilterClient)net;
    }
}

public class NetworkClient{}
public class SkyfilterClient : NetworkClient{}

However, if it is actually a NetworkClient, then you cannot magically make it become the subclass. Here is an example of that:

using System;

class Program
{
    static void Main()
    {
        NetworkClient net = new NetworkClient();
        var sky = (SkyfilterClient)net;
    }
}

public class NetworkClient{}
public class SkyfilterClient : NetworkClient{}

HOWEVER, you could create a converter class. Here is an example of that, also:

using System;

class Program
{
    static void Main()
    {
        NetworkClient net = new NetworkClient();
        var sky = SkyFilterClient.CopyToSkyfilterClient(net);
    }
}

public class NetworkClient
{  
  public int SomeVal {get;set;}
}

public class SkyfilterClient : NetworkClient
{
    public int NewSomeVal {get;set;}
    public static SkyfilterClient CopyToSkyfilterClient(NetworkClient networkClient)
    {
        return new SkyfilterClient{NewSomeVal = networkClient.SomeVal};
    }
}

But, keep in mind that there is a reason you cannot convert this way. You may be missing key information that the subclass needs.

Finally, if you just want to see if the attempted cast will work, then you can use is:

if(client is SkyfilterClient)
    cast

How do you create nested dict in Python?

If you want to create a nested dictionary given a list (arbitrary length) for a path and perform a function on an item that may exist at the end of the path, this handy little recursive function is quite helpful:

def ensure_path(data, path, default=None, default_func=lambda x: x):
    """
    Function:

    - Ensures a path exists within a nested dictionary

    Requires:

    - `data`:
        - Type: dict
        - What: A dictionary to check if the path exists
    - `path`:
        - Type: list of strs
        - What: The path to check

    Optional:

    - `default`:
        - Type: any
        - What: The default item to add to a path that does not yet exist
        - Default: None

    - `default_func`:
        - Type: function
        - What: A single input function that takes in the current path item (or default) and adjusts it
        - Default: `lambda x: x` # Returns the value in the dict or the default value if none was present
    """
    if len(path)>1:
        if path[0] not in data:
            data[path[0]]={}
        data[path[0]]=ensure_path(data=data[path[0]], path=path[1:], default=default, default_func=default_func)
    else:
        if path[0] not in data:
            data[path[0]]=default
        data[path[0]]=default_func(data[path[0]])
    return data

Example:

data={'a':{'b':1}}
ensure_path(data=data, path=['a','c'], default=[1])
print(data) #=> {'a':{'b':1, 'c':[1]}}
ensure_path(data=data, path=['a','c'], default=[1], default_func=lambda x:x+[2])
print(data) #=> {'a': {'b': 1, 'c': [1, 2]}}

How can I create an array/list of dictionaries in python?

I assume that motifWidth contains an integer.

In Python, lists do not change size unless you tell them to. Hence, Python throws an exception when you try to change an element that isn't there. I believe you want:

weightMatrix = []
for k in range(motifWidth):
    weightMatrix.append({'A':0,'C':0,'G':0,'T':0})

For what it's worth, when asking questions in the future, it would help if you included the stack trace showing the error that you're getting rather than just saying "it isn't working". That would help us directly figure out the cause of the problem, rather than trying to puzzle it out from your code.

Hope that helps!

Copying an array of objects into another array in javascript

Easy way to get this working is using:

var cloneArray = JSON.parse(JSON.stringify(originalArray));

I have issues with getting arr.concat() or arr.splice(0) to give a deep copy. Above snippet works perfectly.

In Mongoose, how do I sort by date? (node.js)

Sorting in Mongoose has evolved over the releases such that some of these answers are no longer valid. As of the 4.1.x release of Mongoose, a descending sort on the date field can be done in any of the following ways:

    Room.find({}).sort('-date').exec((err, docs) => { ... });
    Room.find({}).sort({date: -1}).exec((err, docs) => { ... });
    Room.find({}).sort({date: 'desc'}).exec((err, docs) => { ... });
    Room.find({}).sort({date: 'descending'}).exec((err, docs) => { ... });
    Room.find({}).sort([['date', -1]]).exec((err, docs) => { ... });
    Room.find({}, null, {sort: '-date'}, (err, docs) => { ... });
    Room.find({}, null, {sort: {date: -1}}, (err, docs) => { ... });

For an ascending sort, omit the - prefix on the string version or use values of 1, asc, or ascending.

Get current date in Swift 3?

You can do it in this way with Swift 3.0:

let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)

let year =  components.year
let month = components.month
let day = components.day

print(year)
print(month)
print(day)

BeautifulSoup getting href

You can use find_all in the following way to find every a element that has an href attribute, and print each one:

from BeautifulSoup import BeautifulSoup

html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''

soup = BeautifulSoup(html)

for a in soup.find_all('a', href=True):
    print "Found the URL:", a['href']

The output would be:

Found the URL: some_url
Found the URL: another_url

Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all instead.


If you want all tags with an href, you can omit the name parameter:

href_tags = soup.find_all(href=True)

Export P7b file with all the certificate chain into CER file

If you add -chain to your command line, it will export any chained certificates.

http://www.openssl.org/docs/apps/pkcs12.html

href image link download on click

<a href="download.php?file=path/<?=$row['file_name']?>">Download</a>

download.php:

<?php

$file = $_GET['file'];

download_file($file);

function download_file( $fullPath ){

  // Must be fresh start
  if( headers_sent() )
    die('Headers Sent');

  // Required for some browsers
  if(ini_get('zlib.output_compression'))
    ini_set('zlib.output_compression', 'Off');

  // File Exists?
  if( file_exists($fullPath) ){

    // Parse Info / Get Extension
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);

    // Determine Content Type
    switch ($ext) {
      case "pdf": $ctype="application/pdf"; break;
      case "exe": $ctype="application/octet-stream"; break;
      case "zip": $ctype="application/zip"; break;
      case "doc": $ctype="application/msword"; break;
      case "xls": $ctype="application/vnd.ms-excel"; break;
      case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
      case "gif": $ctype="image/gif"; break;
      case "png": $ctype="image/png"; break;
      case "jpeg":
      case "jpg": $ctype="image/jpg"; break;
      default: $ctype="application/force-download";
    }

    header("Pragma: public"); // required
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false); // required for certain browsers
    header("Content-Type: $ctype");
    header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" );
    header("Content-Transfer-Encoding: binary");
    header("Content-Length: ".$fsize);
    ob_clean();
    flush();
    readfile( $fullPath );

  } else
    die('File Not Found');

}
?>

PHP remove all characters before specific string

You can use strstr to do this.

echo strstr($str, 'www/audio');

Why es6 react component works only with "export default"?

Add { } while importing and exporting: export { ... }; | import { ... } from './Template';

exportimport { ... } from './Template'

export defaultimport ... from './Template'


Here is a working example:

// ExportExample.js
import React from "react";

function DefaultExport() {
  return "This is the default export";
}

function Export1() {
  return "Export without default 1";
}

function Export2() {
  return "Export without default 2";
}

export default DefaultExport;
export { Export1, Export2 };

// App.js
import React from "react";
import DefaultExport, { Export1, Export2 } from "./ExportExample";

export default function App() {
  return (
    <>
      <strong>
        <DefaultExport />
      </strong>
      <br />
      <Export1 />
      <br />
      <Export2 />
    </>
  );
}

??Working sandbox to play around: https://codesandbox.io/s/export-import-example-react-jl839?fontsize=14&hidenavigation=1&theme=dark

Java List.add() UnsupportedOperationException

Not every List implementation supports the add() method.

One common example is the List returned by Arrays.asList(): it is documented not to support any structural modification (i.e. removing or adding elements) (emphasis mine):

Returns a fixed-size list backed by the specified array.

Even if that's not the specific List you're trying to modify, the answer still applies to other List implementations that are either immutable or only allow some selected changes.

You can find out about this by reading the documentation of UnsupportedOperationException and List.add(), which documents this to be an "(optional operation)". The precise meaning of this phrase is explained at the top of the List documentation.

As a workaround you can create a copy of the list to a known-modifiable implementation like ArrayList:

seeAlso = new ArrayList<>(seeAlso);

os.path.dirname(__file__) returns empty

can be used also like that:

dirname(dirname(abspath(__file__)))

SQL Developer is returning only the date, not the time. How do I fix this?

To expand on some of the previous answers, I found that Oracle DATE objects behave different from Oracle TIMESTAMP objects. In particular, if you set your NLS_DATE_FORMAT to include fractional seconds, the entire time portion is omitted.

  • Format "YYYY-MM-DD HH24:MI:SS" works as expected, for DATE and TIMESTAMP
  • Format "YYYY-MM-DD HH24:MI:SSXFF" displays just the date portion for DATE, works as expected for TIMESTAMP

My personal preference is to set DATE to "YYYY-MM-DD HH24:MI:SS", and to set TIMESTAMP to "YYYY-MM-DD HH24:MI:SSXFF".

How can I increment a date by one day in Java?

It's very simple, trying to explain in a simple word. get the today's date as below

Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime());// print today's date
calendar.add(Calendar.DATE, 1);

Now set one day ahead with this date by calendar.add method which takes (constant, value). Here constant could be DATE, hours, min, sec etc. and value is the value of constant. Like for one day, ahead constant is Calendar.DATE and its value are 1 because we want one day ahead value.

System.out.println(calendar.getTime());// print modified date which is tomorrow's date

Thanks

Find size of an array in Perl

There are various ways to print size of an array. Here are the meanings of all:

Let’s say our array is my @arr = (3,4);

Method 1: scalar

This is the right way to get the size of arrays.

print scalar @arr;  # Prints size, here 2

Method 2: Index number

$#arr gives the last index of an array. So if array is of size 10 then its last index would be 9.

print $#arr;     # Prints 1, as last index is 1
print $#arr + 1; # Adds 1 to the last index to get the array size

We are adding 1 here, considering the array as 0-indexed. But, if it's not zero-based then, this logic will fail.

perl -le 'local $[ = 4; my @arr = (3, 4); print $#arr + 1;'   # prints 6

The above example prints 6, because we have set its initial index to 4. Now the index would be 5 and 6, with elements 3 and 4 respectively.

Method 3:

When an array is used in a scalar context, then it returns the size of the array

my $size = @arr;
print $size;   # Prints size, here 2

Actually, method 3 and method 1 are same.

Setting selection to Nothing when programming Excel

I had this issue with Excel 2013. I had "freeze panes" set, which caused the problem. The issue was resolved when I removed the frozen panes.

How to fix curl: (60) SSL certificate: Invalid certificate chain

NOTE: This answer obviously defeats the purpose of SSL and should be used sparingly as a last resort.

For those having issues with scripts that download scripts that download scripts and want a quick fix, create a file called ~/.curlrc

With the contents

--insecure

This will cause curl to ignore SSL certificate problems by default.

Make sure you delete the file when done.

UPDATE

12 days later I got notified of an upvote on this answer, which made me go "Hmmm, did I follow my own advice remember to delete that .curlrc?", and discovered I hadn't. So that really underscores how easy it is to leave your curl insecure by following this method.

Open a local HTML file using window.open in Chrome

This worked for me fine:

File 1:

    <html>
    <head></head>
    <body>
        <a href="#" onclick="window.open('file:///D:/Examples/file2.html'); return false">CLICK ME</a>
    </body>
    <footer></footer>
    </html>

File 2:

    <html>
        ...
    </html>

This method works regardless of whether or not the 2 files are in the same directory, BUT both files must be local.

For obvious security reasons, if File 1 is located on a remote server you absolutely cannot open a file on some client's host computer and trying to do so will open a blank target.

Android Crop Center of Bitmap

To correct @willsteel solution:

if (landscape){
                int start = (tempBitmap.getWidth() - tempBitmap.getHeight()) / 2;
                croppedBitmap = Bitmap.createBitmap(tempBitmap, start, 0, tempBitmap.getHeight(), tempBitmap.getHeight(), matrix, true);
            } else {
                int start = (tempBitmap.getHeight() - tempBitmap.getWidth()) / 2;
                croppedBitmap = Bitmap.createBitmap(tempBitmap, 0, start, tempBitmap.getWidth(), tempBitmap.getWidth(), matrix, true);
            }

Matplotlib: "Unknown projection '3d'" error

Import mplot3d whole to use "projection = '3d'".

Insert the command below in top of your script. It should run fine.

from mpl_toolkits import mplot3d

RegEx to parse or validate Base64 data

The answers presented so far fail to check that the Base64 string has all pad bits set to 0, as required for it to be the canonical representation of Base64 (which is important in some environments, see https://tools.ietf.org/html/rfc4648#section-3.5) and therefore, they allow aliases that are different encodings for the same binary string. This could be a security problem in some applications.

Here is the regexp that verifies that the given string is not just valid base64, but also the canonical base64 string for the binary data:

^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/][AQgw]==|[A-Za-z0-9+/]{2}[AEIMQUYcgkosw048]=)?$

The cited RFC considers the empty string as valid (see https://tools.ietf.org/html/rfc4648#section-10) therefore the above regex also does.

The equivalent regular expression for base64url (again, refer to the above RFC) is:

^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-][AQgw]==|[A-Za-z0-9_-]{2}[AEIMQUYcgkosw048]=)?$

PHP cURL, extract an XML response

simple load xml file ..

$xml = @simplexml_load_string($retValuet);

$status = (string)$xml->Status; 
$operator_trans_id = (string)$xml->OPID;
$trns_id = (string)$xml->TID;

?>

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

The JAX-WS dependency library “jaxws-rt.jar” is missing.

Go here http://jax-ws.java.net/. Download JAX-WS RI distribution. Unzip it and copy “jaxws-rt.jar” to Tomcat library folder “{$TOMCAT}/lib“. Restart Tomcat.