Programs & Examples On #Dense rank

A SQL window-function that returns the a consecutive rank of rows, within a partition of a result-set.

Change a HTML5 input's placeholder color with CSS

This will work fine. DEMO HERE:

_x000D_
_x000D_
input::-webkit-input-placeholder,_x000D_
textarea::-webkit-input-placeholder {_x000D_
  color: #666;_x000D_
}_x000D_
input:-moz-placeholder,_x000D_
textarea:-moz-placeholder {_x000D_
  color: #666;_x000D_
}_x000D_
input::-moz-placeholder,_x000D_
textarea::-moz-placeholder {_x000D_
  color: #666;_x000D_
}_x000D_
input:-ms-input-placeholder,_x000D_
textarea:-ms-input-placeholder {_x000D_
  color: #666;_x000D_
}
_x000D_
<input type="text" placeholder="Value" />
_x000D_
_x000D_
_x000D_

Change value of input onchange?

You can't access your fieldname as a global variable. Use document.getElementById:

function updateInput(ish){
    document.getElementById("fieldname").value = ish;
}

and

onchange="updateInput(this.value)"

Add leading zeroes to number in Java?

Another option is to use DecimalFormat to format your numeric String. Here is one other way to do the job without having to use String.format if you are stuck in the pre 1.5 world:

static String intToString(int num, int digits) {
    assert digits > 0 : "Invalid number of digits";

    // create variable length array of zeros
    char[] zeros = new char[digits];
    Arrays.fill(zeros, '0');
    // format number as String
    DecimalFormat df = new DecimalFormat(String.valueOf(zeros));

    return df.format(num);
}

How to overlay images

Here is how I did it recently. Not perfect semantically, but gets the job done.

<div class="container" style="position: relative">
<img style="z-index: 32; left: 8px; position: relative;" alt="bottom image" src="images/bottom-image.jpg">
<div style="z-index: 100; left: 72px; position: absolute; top: 39px">
<img alt="top image" src="images/top-image.jpg"></div></div>

Quickest way to compare two generic lists for differences

Not for this Problem, but here's some code to compare lists for equal and not! identical objects:

public class EquatableList<T> : List<T>, IEquatable<EquatableList<T>> where    T : IEquatable<T>

/// <summary>
/// True, if this contains element with equal property-values
/// </summary>
/// <param name="element">element of Type T</param>
/// <returns>True, if this contains element</returns>
public new Boolean Contains(T element)
{
    return this.Any(t => t.Equals(element));
}

/// <summary>
/// True, if list is equal to this
/// </summary>
/// <param name="list">list</param>
/// <returns>True, if instance equals list</returns>
public Boolean Equals(EquatableList<T> list)
{
    if (list == null) return false;
    return this.All(list.Contains) && list.All(this.Contains);
}

curl: (6) Could not resolve host: application

Example for Slack.... (use your own web address you generate there)...

curl -X POST -H "Content-type:application/json" --data "{\"text\":\"A New Program Has Just Been Posted!!!\"}" https://hooks.slack.com/services/T7M0PFD42/BAA6NK48Y/123123123123123

Can't execute jar- file: "no main manifest attribute"

The Gradle answer is to add a jar/manifest/attributes setting like this:

apply plugin: 'java'

jar {
    manifest {
        attributes 'Main-Class': 'com.package.app.Class'
    }
}

jQuery Validation plugin: validate check box

You can validate group checkbox and radio button without extra js code, see below example.

Your JS should be look like:

$("#formid").validate();

You can play with HTML tag and attributes: eg. group checkbox [minlength=2 and maxlength=4]

<fieldset class="col-md-12">
  <legend>Days</legend>
  <div class="form-row">
    <div class="col-12 col-md-12 form-group">
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="1" required="required" data-msg-required="This value is required." minlength="2" maxlength="4" data-msg-maxlength="Max should be 4">Monday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="2">Tuesday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="3">Wednesday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="4">Thursday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="5">Friday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="6">Saturday
        </label>
        <label class="checkbox-inline">
          <input type="checkbox" name="daysgroup[]" value="7">Sunday
        </label>
        <label for="daysgroup[]" class="error">Your error message will be display here.</label>
    </div>
  </div>
</fieldset>

You can see here first or any one input should have required, minlength="2" and maxlength="4" attributes. minlength/maxlength as per your requirement.

eg. group radio button:

<fieldset class="col-md-12">
  <legend>Gender</legend>
  <div class="form-row">
    <div class="col-12 col-md-12 form-group">
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="m" required="required" data-msg-required="This value is required.">man
        </label>
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="w">woman
        </label>
        <label class="form-check-inline">
          <input type="radio" name="gendergroup[]" value="o">other
        </label>
        <label for="gendergroup[]" class="error">Your error message will be display here.</label>
    </div>
  </div>
</fieldset>

You can check working example here.

  • jQuery v3.3.x
  • jQuery Validation Plugin - v1.17.0

How can I debug my JavaScript code?

  • Internet Explorer 8 (Developer Tools - F12). Anything else is second rate in Internet Explorer land
  • Firefox and Firebug. Hit F12 to display.
  • Safari (Show Menu Bar, Preferences -> Advanced -> Show Develop menu bar)
  • Google Chrome JavaScript Console (F12 or (Ctrl + Shift + J)). Mostly the same browser as Safari, but Safari is better IMHO.
  • Opera (Tools -> Advanced -> Developer Tools)

Fixed height and width for bootstrap carousel

To have a consistent flow of the images on different devices, you'd have to specify the width and height value for each carousel image item, for instance here in my example the image would take the full width but with a height of "400px" (you can specify your personal value instead)

<div class="item">
        <img src="image.jpg" style="width:100%; height: 400px;">
      </div>

How to get WordPress post featured image URL

Check the code below and let me know if it works for you.

<?php if (has_post_thumbnail( $post->ID ) ): ?>
  <?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?>
  <div id="custom-bg" style="background-image: url('<?php echo $image[0]; ?>')">

  </div>
<?php endif; ?>

How to get the current time in Google spreadsheet using script editor?

The Date object is used to work with dates and times.

Date objects are created with new Date().

var date= new Date();

 function myFunction() {
        var currentTime = new Date();
        Logger.log(currentTime);
    }

Attach event to dynamic elements in javascript

I know that the topic is too old but I gave myself some minutes to create a very useful code that works fine and very easy using pure JAVASCRIPT. Here is the code with a simple example:

_x000D_
_x000D_
String.prototype.addEventListener=function(eventHandler, functionToDo){_x000D_
  let selector=this;_x000D_
  document.body.addEventListener(eventHandler, function(e){_x000D_
    e=(e||window.event);_x000D_
    e.preventDefault();_x000D_
    const path=e.path;_x000D_
    path.forEach(function(elem){_x000D_
      const selectorsArray=document.querySelectorAll(selector);_x000D_
      selectorsArray.forEach(function(slt){_x000D_
        if(slt==elem){_x000D_
          if(typeof functionToDo=="function") functionToDo(el=slt, e=e);_x000D_
        }_x000D_
      });_x000D_
    });_x000D_
  });_x000D_
}_x000D_
_x000D_
// And here is how we can use it actually !_x000D_
_x000D_
"input[type='number']".addEventListener("click", function(element, e){_x000D_
 console.log( e ); // Console log the value of the current number input_x000D_
});
_x000D_
<input type="number" value="25">_x000D_
<br>_x000D_
<input type="number" value="15">_x000D_
<br><br>_x000D_
<button onclick="addDynamicInput()">Add a Dynamic Input</button>_x000D_
<script type="text/javascript">_x000D_
  function addDynamicInput(){_x000D_
    const inpt=document.createElement("input");_x000D_
          inpt.type="number";_x000D_
          inpt.value=Math.floor(Math.random()*30+1);_x000D_
    document.body.prepend(inpt);_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

int value under 10 convert to string two digit number

I can't believe nobody suggested this:

int i = 9;
i.ToString("D2"); // Will give you the string "09"

or

i.ToString("D8"); // Will give you the string "00000009"

If you want hexadecimal:

byte b = 255;
b.ToString("X2"); // Will give you the string "FF"

You can even use just "C" to display as currency if you locale currency symbol. See here: https://docs.microsoft.com/en-us/dotnet/api/system.int32.tostring?view=netframework-4.7.2#System_Int32_ToString_System_String_

Find the nth occurrence of substring in a string

Avoid a failure or incorrect output when the input value for occurrence provided is higher than the actual count of occurrence. For example, in a string 'overflow' if you would check the 3rd occurrence of 'o' ( it has only 2 occurrences ) then below code will return a warning or message indicating that the occurrence value has exceeded.

Input Occurrence entered has exceeded the actual count of Occurrence.

def check_nth_occurrence (string, substr, n):

## Count the Occurrence of a substr
    cnt = 0
    for i in string:
        if i ==substr:
            cnt = cnt + 1
        else:
            pass

## Check if the Occurrence input has exceeded the actual count of Occurrence

    if n > cnt:
        print (f' Input Occurrence entered has exceeded the actual count of Occurrence')
        return

## Get the Index value for first Occurrence of the substr

   index = string.find(substr)

## Get the Index value for nth Occurrence of Index
    while index >= 0 and n > 1:
        index = string.find(substr, index+ 1)
        n -= 1
  return index

What does "implements" do on a class?

Interfaces are implemented through classes. They are purely abstract classes, if you will.

In PHP when a class implements from an interface, the methods defined in that interface are to be strictly followed. When a class inherits from a parent class, method parameters may be altered. That is not the case for interfaces:

interface ImplementMeStrictly {
   public function foo($a, $b);
}

class Obedient implements ImplementMeStrictly {
   public function foo($a, $b, $c) 
      {
      }
}

will cause an error, because the interface wasn't implemented as defined. Whereas:

class InheritMeLoosely {
   public function foo($a)
      {
      }
}

class IDoWhateverWithFoo extends InheritMeLoosely {
   public function foo()
      {
      }
}

Is allowed.

Why does corrcoef return a matrix?

You can use the following function to return only the correlation coefficient:

def pearson_r(x, y):
"""Compute Pearson correlation coefficient between two arrays."""

   # Compute correlation matrix
   corr_mat = np.corrcoef(x, y)

   # Return entry [0,1]
   return corr_mat[0,1]

Pattern matching using a wildcard

You can also use package data.table and it's Like function, details given below How to select R data.table rows based on substring match (a la SQL like)

Jackson enum Serializing and DeSerializer

I've found a very nice and concise solution, especially useful when you cannot modify enum classes as it was in my case. Then you should provide a custom ObjectMapper with a certain feature enabled. Those features are available since Jackson 1.6. So you only need to write toString() method in your enum.

public class CustomObjectMapper extends ObjectMapper {
    @PostConstruct
    public void customConfiguration() {
        // Uses Enum.toString() for serialization of an Enum
        this.enable(WRITE_ENUMS_USING_TO_STRING);
        // Uses Enum.toString() for deserialization of an Enum
        this.enable(READ_ENUMS_USING_TO_STRING);
    }
}

There are more enum-related features available, see here:

https://github.com/FasterXML/jackson-databind/wiki/Serialization-Features https://github.com/FasterXML/jackson-databind/wiki/Deserialization-Features

generate a random number between 1 and 10 in c

Here is a ready to run source code for random number generator using c taken from this site: http://www.random-number.com/random-number-c/ . The implementation here is more general (a function that gets 3 parameters: min,max and number of random numbers to generate)

#include <time.h>
#include <stdlib.h>
#include <stdio.h>

// the random function
void RandomNumberGenerator(const int nMin, const int nMax, const int  nNumOfNumsToGenerate)
{
  int nRandonNumber = 0;
  for (int i = 0; i < nNumOfNumsToGenerate; i++)
  {
    nRandonNumber = rand()%(nMax-nMin) + nMin;
    printf("%d ", nRandonNumber);
  }
  printf("\n");
}

void main()
{
  srand(time(NULL));
  RandomNumberGenerator(1,70,5);
}

How can I conditionally import an ES6 module?

obscuring it in an eval worked for me, hiding it from the static analyzer ...

if (typeof __CLI__ !== 'undefined') {
  eval("require('fs');")
}

How to drop all tables from a database with one SQL query?

Use the INFORMATION_SCHEMA.TABLES view to get the list of tables. Generate Drop scripts in the select statement and drop it using Dynamic SQL:

DECLARE @sql NVARCHAR(max)=''

SELECT @sql += ' Drop table ' + QUOTENAME(TABLE_SCHEMA) + '.'+ QUOTENAME(TABLE_NAME) + '; '
FROM   INFORMATION_SCHEMA.TABLES
WHERE  TABLE_TYPE = 'BASE TABLE'

Exec Sp_executesql @sql

Sys.Tables Version

DECLARE @sql NVARCHAR(max)=''

SELECT @sql += ' Drop table ' + QUOTENAME(s.NAME) + '.' + QUOTENAME(t.NAME) + '; '
FROM   sys.tables t
       JOIN sys.schemas s
         ON t.[schema_id] = s.[schema_id]
WHERE  t.type = 'U'

Exec sp_executesql @sql

Note: If you have any foreign Keys defined between tables then first run the below query to disable all foreign keys present in your database.

EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

For more information, check here.

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

Have you tried JQuery? Vanilla javascript can be tough. Try using this:

$('.container-element').add('<div>Insert Div Content</div>');

.container-element is a JQuery selector that marks the element with the class "container-element" (presumably the parent element in which you want to insert your divs). Then the add() function inserts HTML into the container-element.

Disable button after click in JQuery

Consider also .attr()

$("#roommate_but").attr("disabled", true); worked for me.

Putting a simple if-then-else statement on one line

General ternary syntax:

value_true if <test> else value_false

Another way can be:

[value_false, value_true][<test>]

e.g:

count = [0,N+1][count==N]

This evaluates both branches before choosing one. To only evaluate the chosen branch:

[lambda: value_false, lambda: value_true][<test>]()

e.g.:

count = [lambda:0, lambda:N+1][count==N]()

How to set ObjectId as a data type in mongoose

The solution provided by @dex worked for me. But I want to add something else that also worked for me: Use

let UserSchema = new Schema({
   username: {
     type: String
   },
   events: [{
     type: ObjectId,
     ref: 'Event' // Reference to some EventSchema
   }]
})

if what you want to create is an Array reference. But if what you want is an Object reference, which is what I think you might be looking for anyway, remove the brackets from the value prop, like this:

let UserSchema = new Schema({
   username: {
     type: String
   },
   events: {
     type: ObjectId,
     ref: 'Event' // Reference to some EventSchema
   }
})

Look at the 2 snippets well. In the second case, the value prop of key events does not have brackets over the object def.

How to select min and max values of a column in a datatable?

The most efficient way to do this (believe it or not) is to make two variables and write a for loop.

How to find column names for all tables in all databases in SQL Server

I just realized that the following query would give you all column names from the table in your database (SQL SERVER 2017)

SELECT DISTINCT NAME FROM SYSCOLUMNS 
ORDER BY Name 

OR SIMPLY

SELECT Name FROM SYSCOLUMNS

If you do not care about duplicated names.

Another option is SELECT Column names from INFORMATION_SCHEMA

SELECT DISTINCT column_name  FROM INFORMATION_SCHEMA.COLUMNS
ORDER BY column_name

It is usually more interesting to have the TableName as well as the ColumnName ant the query below does just that.

SELECT 
   Object_Name(Id) As TableName,
   Name As ColumnName
FROM SysColumns

And the results would look like

  TableName    ColumnName
0    Table1    column11
1    Table1    Column12
2    Table2    Column21
3    Table2    Column22
4    Table3    Column23

Find and replace specific text characters across a document with JS

Vanilla JavaScript solution:

document.body.innerHTML = document.body.innerHTML.replace(/Original/g, "New")

twitter-bootstrap: how to get rid of underlined button text when hovering over a btn-group within an <a>-tag?

.btn is the best way, in modern website, it's not good while using anchor element without href so make the anchor tag to button is better.

Which equals operator (== vs ===) should be used in JavaScript comparisons?

I tested this in Firefox with Firebug using code like this:

_x000D_
_x000D_
console.time("testEquality");
var n = 0;
while (true) {
  n++;
  if (n == 100000)
    break;
}
console.timeEnd("testEquality");
_x000D_
_x000D_
_x000D_

and

_x000D_
_x000D_
console.time("testTypeEquality");
var n = 0;
while (true) {
  n++;
  if (n === 100000)
    break;
}
console.timeEnd("testTypeEquality");
_x000D_
_x000D_
_x000D_

My results (tested five times each and averaged):

==: 115.2
===: 114.4

So I'd say that the miniscule difference (this is over 100000 iterations, remember) is negligible. Performance isn't a reason to do ===. Type safety (well, as safe as you're going to get in JavaScript), and code quality is.

Add space between HTML elements only using CSS

span:not(:last-child) {
    margin-right: 10px;
}

Check if something is (not) in a list in Python

The bug is probably somewhere else in your code, because it should work fine:

>>> 3 not in [2, 3, 4]
False
>>> 3 not in [4, 5, 6]
True

Or with tuples:

>>> (2, 3) not in [(2, 3), (5, 6), (9, 1)]
False
>>> (2, 3) not in [(2, 7), (7, 3), "hi"]
True

Assigning default values to shell variables with a single command in bash

see here under 3.5.3(shell parameter expansion)

so in your case

${VARIABLE:-default}

.htaccess 301 redirect of single page

You could also use a RewriteRule if you wanted the ability to template match and redirect urls.

AttributeError: Can only use .dt accessor with datetimelike values

When you write

df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
df['Date'] = df['Date'].dt.strftime('%m/%d')

It can fixed

Trying to get property of non-object in

Your error

Notice: Trying to get property of non-object in C:\wamp\www\phone\pages\init.php on line 22

Your comment

@22 is <?php echo $sidemenu->mname."<br />";?>

$sidemenu is not an object, and you are trying to access one of its properties.

That is the reason for your error.

How to properly set the 100% DIV height to match document/window height?

hows this

<style type="text/css">
#wrapper{
width: 900px;
margin: 0 auto 0 auto;
background: url('image.JPG') 250px 0px repeat-y;
}
</style>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">

function handleResize() {
var h = $(window).height();
        $('#wrapper').css({'height':h+'px'});
}
$(function(){
        handleResize();

        $(window).resize(function(){
        handleResize();
    });
});
</script>
</head>
<body>
        <div id="wrapper">
                ...some content
        </div>
</body>

Difference between timestamps with/without time zone in PostgreSQL

I try to explain it more understandably than the referred PostgreSQL documentation.

Neither TIMESTAMP variants store a time zone (or an offset), despite what the names suggest. The difference is in the interpretation of the stored data (and in the intended application), not in the storage format itself:

  • TIMESTAMP WITHOUT TIME ZONE stores local date-time (aka. wall calendar date and wall clock time). Its time zone is unspecified as far as PostgreSQL can tell (though your application may knows what it is). Hence, PostgreSQL does no time zone related conversion on input or output. If the value was entered into the database as '2011-07-01 06:30:30', then no mater in what time zone you display it later, it will still say year 2011, month 07, day 01, 06 hours, 30 minutes, and 30 seconds (in some format). Also, any offset or time zone you specify in the input is ignored by PostgreSQL, so '2011-07-01 06:30:30+00' and '2011-07-01 06:30:30+05' are the same as just '2011-07-01 06:30:30'. For Java developers: it's analogous to java.time.LocalDateTime.

  • TIMESTAMP WITH TIME ZONE stores a point on the UTC time line. How it looks (how many hours, minutes, etc.) depends on your time zone, but it always refers to the same "physical" instant (like the moment of an actual physical event). The input is internally converted to UTC, and that's how it's stored. For that, the offset of the input must be known, so when the input contains no explicit offset or time zone (like '2011-07-01 06:30:30') it's assumed to be in the current time zone of the PostgreSQL session, otherwise the explicitly specified offset or time zone is used (as in '2011-07-01 06:30:30+05'). The output is displayed converted to the current time zone of the PostgreSQL session. For Java developers: It's analogous to java.time.Instant (with lower resolution though), but with JDBC and JPA 2.2 you are supposed to map it to java.time.OffsetDateTime (or to java.util.Date or java.sql.Timestamp of course).

Some say that both TIMESTAMP variations store UTC date-time. Kind of, but it's confusing to put it that way in my opinion. TIMESTAMP WITHOUT TIME ZONE is stored like a TIMESTAMP WITH TIME ZONE, which rendered with UTC time zone happens to give the same year, month, day, hours, minutes, seconds, and microseconds as they are in the local date-time. But it's not meant to represent the point on the time line that the UTC interpretation says, it's just the way the local date-time fields are encoded. (It's some cluster of dots on the time line, as the real time zone is not UTC; we don't know what it is.)

How to set time to 24 hour format in Calendar

Here you will get all kinds of time related problems. I hope this will solve your problem.

public class MyClass {

    public static void main(String[] args) {


        Calendar cal = Calendar.getInstance();

        // To get the current hour
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        System.out.println("hour: " + hour);

        // To get the current time in 12 hours format
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a",Locale.US);
        String a = sdf.format(cal.getTime());
        System.out.println("Time: " + a);

        // To get the desired time in 12 hours format from 23 hours format
        cal.set(Calendar.HOUR_OF_DAY, 24);
        SimpleDateFormat sdf1 = new SimpleDateFormat("hh:mm a",Locale.ENGLISH);
        String a1 = sdf1.format(cal.getTime());
        System.out.println("Time: " + a1);

        /*  H Hour in day (0-23) 
            k Hour in day (1-24) 
        */

        //To get the desired time in 24 hours format as 0-23 or 1-24
        cal.set(Calendar.HOUR_OF_DAY, 24);
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm",Locale.ENGLISH);
        SimpleDateFormat sdf3 = new SimpleDateFormat("kk:mm",Locale.ENGLISH);
        String a2 = sdf2.format(cal.getTime());
        String a3 = sdf3.format(cal.getTime());
        System.out.println("Time: " + a2);
        System.out.println("Time: " + a3);

        //For example, time like 12:30 PM. How can i convert to 24 hours time in java?

        SimpleDateFormat bigFormat = new SimpleDateFormat("kk:mm");
        SimpleDateFormat smallFormat = new SimpleDateFormat("hh:mm a");

        Date date = null;
        try {
            date = smallFormat.parse("12:30 AM");
        } catch (ParseException e) {
            e.printStackTrace();
        }        
        System.out.println(smallFormat.format(date) + " = " + bigFormat.format(date));

    }

}

How to check if a value exists in an array in Ruby

There are multiple ways to accomplish this. A few of them are as follows:

a = [1,2,3,4,5]

2.in? a  #=> true

8.in? a #=> false

a.member? 1 #=> true

a.member? 8 #=> false

ActiveSheet.UsedRange.Columns.Count - 8 what does it mean?

I think if you try:

Sub Macro3()
a = ActiveSheet.UsedRange.Columns.Count - 3
End Sub  

with a watch on a you will see it does make a difference.

WPF: ItemsControl with scrollbar (ScrollViewer)

Put your ScrollViewer in a DockPanel and set the DockPanel MaxHeight property

[...]
<DockPanel MaxHeight="700">
  <ScrollViewer VerticalScrollBarVisibility="Auto">
   <ItemsControl ItemSource ="{Binding ...}">
     [...]
   </ItemsControl>
  </ScrollViewer>
</DockPanel>
[...]

How can I use grep to show just filenames on Linux?

The standard option grep -l (that is a lowercase L) could do this.

From the Unix standard:

-l
    (The letter ell.) Write only the names of files containing selected
    lines to standard output. Pathnames are written once per file searched.
    If the standard input is searched, a pathname of (standard input) will
    be written, in the POSIX locale. In other locales, standard input may be
    replaced by something more appropriate in those locales.

You also do not need -H in this case.

Array initialization syntax when not in a declaration

Why is this blocked by Java?

You'd have to ask the Java designers. There might be some subtle grammatical reason for the restriction. Note that some of the array creation / initialization constructs were not in Java 1.0, and (IIRC) were added in Java 1.1.

But "why" is immaterial ... the restriction is there, and you have to live with it.

I know how to work around it, but from time to time it would be simpler.

You can write this:

AClass[] array;
...
array = new AClass[]{object1, object2};

Transfer data between databases with PostgreSQL

  1. If your source and target database resides in the same local machine, you can use:

Note:- Sourcedb already exists in your database.

CREATE DATABASE targetdb WITH TEMPLATE sourcedb;

This statement copies the sourcedb to the targetdb.

  1. If your source and target databases resides on different servers, you can use following steps:

Step 1:- Dump the source database to a file.

pg_dump -U postgres -O sourcedb sourcedb.sql

Note:- Here postgres is the username so change the name accordingly.

Step 2:- Copy the dump file to the remote server.

Step 3:- Create a new database in the remote server

CREATE DATABASE targetdb;

Step 4:- Restore the dump file on the remote server

psql -U postgres -d targetdb -f sourcedb.sql

(pg_dump is a standalone application (i.e., something you run in a shell/command-line) and not an Postgres/SQL command.)

This should do it.

data.map is not a function

data needs to be Json object, to do so please make sure the follow:

data = $.parseJSON(data);

Now you can do something like:

data.map(function (...) {
            ...
        });

I hope this help some one

What is the best way to get the count/length/size of an iterator?

Your code will give you an exception when you reach the end of the iterator. You could do:

int i = 0;
while(iterator.hasNext()) {
    i++;
    iterator.next();
}

If you had access to the underlying collection, you would be able to call coll.size()...

EDIT OK you have amended...

Creating SVG elements dynamically with javascript inside HTML

To facilitate svg editing you can use an intermediate function:

function getNode(n, v) {
  n = document.createElementNS("http://www.w3.org/2000/svg", n);
  for (var p in v)
    n.setAttributeNS(null, p, v[p]);
  return n
}

Now you can write:

svg.appendChild( getNode('rect', { width:200, height:20, fill:'#ff0000' }) );

Example (with an improved getNode function allowing camelcase for property with dash, eg strokeWidth > stroke-width):

_x000D_
_x000D_
function getNode(n, v) {_x000D_
  n = document.createElementNS("http://www.w3.org/2000/svg", n);_x000D_
  for (var p in v)_x000D_
    n.setAttributeNS(null, p.replace(/[A-Z]/g, function(m, p, o, s) { return "-" + m.toLowerCase(); }), v[p]);_x000D_
  return n_x000D_
}_x000D_
_x000D_
var svg = getNode("svg");_x000D_
document.body.appendChild(svg);_x000D_
_x000D_
var r = getNode('rect', { x: 10, y: 10, width: 100, height: 20, fill:'#ff00ff' });_x000D_
svg.appendChild(r);_x000D_
_x000D_
var r = getNode('rect', { x: 20, y: 40, width: 100, height: 40, rx: 8, ry: 8, fill: 'pink', stroke:'purple', strokeWidth:7 });_x000D_
svg.appendChild(r);
_x000D_
_x000D_
_x000D_

How do I search for files in Visual Studio Code?

If you just want to search a single file name

Just Ctrl+P, then type and choose your one

If you want to open all files whose name contains a particular string

  1. Open search panel
  2. Put any common words inside those files
  3. in 'files to include', put the search string with *, e.g. *Signaller*

enter image description here

Centering the image in Bootstrap

Update 2018

Bootstrap 2.x

You could create a new CSS class such as:

.img-center {margin:0 auto;}

And then, add this to each IMG:

 <img src="images/2.png" class="img-responsive img-center">

OR, just override the .img-responsive if you're going to center all images..

 .img-responsive {margin:0 auto;}

Demo: http://bootply.com/86123

Bootstrap 3.x

EDIT - With the release of Bootstrap 3.0.1, the center-block class can now be used without any additional CSS..

 <img src="images/2.png" class="img-responsive center-block">

Bootstrap 4

In Bootstrap 4, the mx-auto class (auto x-axis margins) can be used to center images that are display:block. However, img is display:inline by default so text-center can be used on the parent.

<div class="container">
    <div class="row">
        <div class="col-12">
            <img class="mx-auto d-block" src="//placehold.it/200">  
        </div>
    </div>
    <div class="row">
        <div class="col-12 text-center">
            <img src="//placehold.it/200">  
        </div>
    </div>
</div>

Bootsrap 4 - center image demo

How to install Python MySQLdb module using pip?

on RHEL 7:

sudo yum install yum-utils mariadb-devel python-pip python-devel gcc

sudo /bin/pip2 install MySQL-python

How to display the string html contents into webbrowser control?

Try this:

webBrowser1.DocumentText =
    "<html><body>Please enter your name:<br/>" +
    "<input type='text' name='userName'/><br/>" +
    "<a href='http://www.microsoft.com'>continue</a>" +
    "</body></html>";

How to prevent multiple definitions in C?

The underscore is put there by the compiler and used by the linker. The basic path is:

main.c
test.h ---> [compiler] ---> main.o --+
                                     |
test.c ---> [compiler] ---> test.o --+--> [linker] ---> main.exe

So, your main program should include the header file for the test module which should consist only of declarations, such as the function prototype:

void test(void);

This lets the compiler know that it exists when main.c is being compiled but the actual code is in test.c, then test.o.

It's the linking phase that joins together the two modules.

By including test.c into main.c, you're defining the test() function in main.o. Presumably, you're then linking main.o and test.o, both of which contain the function test().

When to catch java.lang.Error?

If you are crazy enough to be creating a new unit test framework, your test runner will probably need to catch java.lang.AssertionError thrown by any test cases.

Otherwise, see other answers.

Create line after text with css

Here is how I do this: http://jsfiddle.net/Zz7Wq/2/

I use a background instead of after and use my H1 or H2 to cover the background. Not quite your method above but does work well for me.

CSS

.title-box { background: #fff url('images/bar-orange.jpg') repeat-x left; text-align: left; margin-bottom: 20px;}
.title-box h1 { color: #000; background-color: #fff; display: inline; padding: 0 50px 0 50px; }

HTML

<div class="title-box"><h1>Title can go here</h1></div>
<div class="title-box"><h1>Title can go here this one is really really long</h1></div>

Material UI and Grid system

I hope this is not too late to give a response.

I was also looking for a simple, robust, flexible and highly customizable bootstrap like react grid system to use in my projects.

The best I know of is react-pure-grid https://www.npmjs.com/package/react-pure-grid

react-pure-grid gives you the power to customize every aspect of your grid system, while at the same time it has built in defaults which probably suits any project

Usage

npm install react-pure-grid --save

-

import {Container, Row, Col} from 'react-pure-grid';

const App = () => (
      <Container>
        <Row>
          <Col xs={6} md={4} lg={3}>Hello, world!</Col>
        </Row>
        <Row>
            <Col xsOffset={5} xs={7}>Welcome!</Col>
        </Row>
      </Container>
);

Sorting a vector of custom objects

A simple example using std::sort

struct MyStruct
{
    int key;
    std::string stringValue;

    MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
};

struct less_than_key
{
    inline bool operator() (const MyStruct& struct1, const MyStruct& struct2)
    {
        return (struct1.key < struct2.key);
    }
};

std::vector < MyStruct > vec;

vec.push_back(MyStruct(4, "test"));
vec.push_back(MyStruct(3, "a"));
vec.push_back(MyStruct(2, "is"));
vec.push_back(MyStruct(1, "this"));

std::sort(vec.begin(), vec.end(), less_than_key());

Edit: As Kirill V. Lyadvinsky pointed out, instead of supplying a sort predicate, you can implement the operator< for MyStruct:

struct MyStruct
{
    int key;
    std::string stringValue;

    MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}

    bool operator < (const MyStruct& str) const
    {
        return (key < str.key);
    }
};

Using this method means you can simply sort the vector as follows:

std::sort(vec.begin(), vec.end());

Edit2: As Kappa suggests you can also sort the vector in the descending order by overloading a > operator and changing call of sort a bit:

struct MyStruct
{
    int key;
    std::string stringValue;

    MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}

    bool operator > (const MyStruct& str) const
    {
        return (key > str.key);
    }
};

And you should call sort as:

std::sort(vec.begin(), vec.end(),greater<MyStruct>());

How to List All Redis Databases?

Or you can just run the following command and you will see all databases of the Redis instance without firing up redis-cli:

$ redis-cli INFO | grep ^db
db0:keys=1500,expires=2
db1:keys=200000,expires=1
db2:keys=350003,expires=1

How to load all the images from one of my folder into my web page, using Jquery/Javascript

If, as in my case, you would like to load the images from a local folder on your own machine, then there is a simple way to do it with a very short Windows batch file. This uses the ability to send the output of any command to a file using > (to overwrite a file) and >> (to append to a file).

Potentially, you could output a list of filenames to a plain text file like this:

dir /B > filenames.txt

However, reading in a text file requires more faffing around, so I output a javascript file instead, which can then be loaded in your to create a global variable with all the filenames in it.

echo var g_FOLDER_CONTENTS = mlString(function() { /*! > folder_contents.js
dir /B images >> folder_contents.js
echo */}); >> folder_contents.js

The reason for the weird function with comment inside notation is to get around the limitation on multi-line strings in Javascript. The output of the dir command cannot be formatted to write a correct string, so I found a workaround here.

function mlString(f) {
    return f.toString().
        replace(/^[^\/]+\/\*!?/, '').
        replace(/\*\/[^\/]+$/, '');
}

Add this in your main code before the generated javascript file is run, and then you will have a global variable called g_FOLDER_CONTENTS, which is a string containing the output from the dir command. This can then be tokenized and you'll have a list of filenames, with which you can do what you like.

var filenames = g_FOLDER_CONTENTS.match(/\S+/g);

Here's an example of it all put together: image_loader.zip

In the example, run.bat generates the Javascript file and opens index.html, so you needn't open index.html yourself.

NOTE: .bat is an executable type in Windows, so open them in a text editor before running if you are downloading from some random internet link like this one.

If you are running Linux or OSX, you can probably do something similar to the batch file and produce a correctly formatted javascript string without any of the mlString faff.

How to change the default docker registry from docker.io to my private registry?

I tried to add the following options in the /etc/docker/daemon.json. (I used CentOS7)

"add-registry": ["192.168.100.100:5001"],
"block-registry": ["docker.io"],

after that, restarted docker daemon. And it's working without docker.io. I hope this someone will be helpful.

How to extract the substring between two markers?

Using regular expressions - documentation for further reference

import re

text = 'gfgfdAAA1234ZZZuijjk'

m = re.search('AAA(.+?)ZZZ', text)
if m:
    found = m.group(1)

# found: 1234

or:

import re

text = 'gfgfdAAA1234ZZZuijjk'

try:
    found = re.search('AAA(.+?)ZZZ', text).group(1)
except AttributeError:
    # AAA, ZZZ not found in the original string
    found = '' # apply your error handling

# found: 1234

How do I get a range's address including the worksheet name, but not the workbook name, in Excel VBA?

Only way I can think of is to concatenate the worksheet name with the cell reference, as follows:

Dim cell As Range
Dim cellAddress As String
Set cell = ThisWorkbook.Worksheets(1).Cells(1, 1)
cellAddress = cell.Parent.Name & "!" & cell.Address(External:=False)

EDIT:

Modify last line to :

cellAddress = "'" & cell.Parent.Name & "'!" & cell.Address(External:=False) 

if you want it to work even if there are spaces or other funny characters in the sheet name.

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

Pretty straight forward approach using filterBy in angularJs

For working plnkr follow this link

http://plnkr.co/edit/US6xE4h0gD5CEYV0aMDf?p=preview

This has specially used a single property to search against multiple column but not all.

<!DOCTYPE html>
<html ng-app="myApp">

  <head>
    <script data-require="[email protected]" data-semver="1.4.1" src="https://code.angularjs.org/1.4.1/angular.js"></script>
    <script data-require="[email protected]" data-semver="0.5.2" src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.2/angular-filter.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="myCtrl as vm">
  <input type="text" placeholder="enter your search text" ng-model="vm.searchText" />
   <table>
     <tr ng-repeat="row in vm.tableData | filterBy: ['col1','col2']: vm.searchText">
       <td>{{row.col1}}</td>
       <td>{{row.col2}}</td>
       <td>{{row.col3}}</td>
     </tr>
   </table>
   <p>This will show filter from <b>two columns</b> only(col1 and col2) . Not from all. Whatever columns you add into filter array they
   will be searched. all columns will be used by default if you use <b>filter: vm.searchText</b></p>
  </body>
</html>

controller

// Code goes here
(function(){

  var myApp = angular.module('myApp',['angular.filter']);

  myApp.controller('myCtrl', function($scope){
    var vm= this;
    vm.x = 20;

    vm.tableData = [
      {
        col1: 'Ashok',
        col2: 'Tewatia',
        col3: '12'
      },{
        col1: 'Babita',
        col2: 'Malik',
        col3: '34'
      },{
        col1: 'Dinesh',
        col2: 'Tewatia',
        col3: '56'
      },{
        col1: 'Sabita',
        col2: 'Malik',
        col3: '78'
      }
      ];
  })

})();

Call Javascript function from URL/address bar

There isn't from a hyperlink, no. Not unless the page has script inside specifically for this and it's checking for some parameter....but for your question, no, there's no built-in support in browsers for this.

There are however bookmarklets you can bookmark to quickly run JavaScript functions from your address bar; not sure if that meets your needs, but it's as close as it gets.

How to update Pandas from Anaconda and is it possible to use eclipse with this last

The answer above did not work for me (python 3.6, Anaconda, pandas 0.20.3). It worked with

conda install -c anaconda pandas 

Unfortunately I do not know how to help with Eclipse.

How to set character limit on the_content() and the_excerpt() in wordpress

wp_trim_words This function trims text to a certain number of words and returns the trimmed text.

Example:-

echo wp_trim_words( get_the_content(), 40, '...' );

How to convert integer to decimal in SQL Server query?

You can either cast Height as a decimal:

select cast(@height as decimal(10, 5))/10 as heightdecimal

or you place a decimal point in your value you are dividing by:

declare @height int
set @height = 1023

select @height/10.0 as heightdecimal

see sqlfiddle with an example

GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

Here is My Code

protected void btnExcel_Click(object sender, ImageClickEventArgs e)
    {
        if (gvDetail.Rows.Count > 0)
        {
            System.IO.StringWriter stringWrite1 = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite1 = new HtmlTextWriter(stringWrite1);
            gvDetail.RenderControl(htmlWrite1);

            gvDetail.AllowPaging = false;
            Search();
            sh.ExportToExcel(gvDetail, "Report");
        }
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
           server control at run time. */
    }

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

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

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

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

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

Referring to the first thread / another possibility VS cant open or find pdb file of the process is when you have your executable running in the background. I was working with mpiexec and ran into this issue. Always check your task manager and kill any exec process that your gonna build in your project. Once I did that, it debugged or built fine.

Also, if you try to continue with the warning , the breakpoints would not be hit and it would not have the current executable

Restart node upon changing a file

A good option is Node-supervisor and Node.js Restart on File Change is good article on how to use it, typically:

 npm install supervisor -g

and after migrating to the root of your application use the following

 supervisor app.js

Get the element with the highest occurrence in an array

Here is my way. I try to group data fist.

const _ = require("underscore")

var test  = [ 1, 1, 2, 1 ];
var groupResult = _.groupBy(test, (e)=> e);

The groupResult should be

{
  1: [1, 1, 1]
  2: [2] 
}

Then find the property which has the longest array

function findMax(groupResult){
   var maxArr = []
   var max;
   for(var item in groupResult){
     if(!max) { 
        max = { value:item, count: groupResult[item].length } ; 
        maxArr.push(max); 
        continue;
     }
     if(max.count < groupResult[item].length){ 
        maxArr = [];
        max = { value:item, count: groupResult[item].length }
        maxArr.push(max)
     } else if(max === groupResult[item].length)
        maxArr.push({ value:item, count: groupResult[item].length })
   }
   return maxArr;
}

The complete code looks like

const _ = require("underscore")

var test  = [ 1, 1, 2, 1 ];
var groupResult= _.groupBy(test, (e)=> e);
console.log(findMax(groupResult)[0].value);

function findMax(groupResult){
   var maxArr = []
   var max;
   for(var item in groupResult){
     if(!max) { 
        max = { value:item, count: groupResult[item].length } ; 
        maxArr.push(max); 
        continue;
     }
     if(max.count < groupResult[item].length){ 
        maxArr = [];
        max = { value:item, count: groupResult[item].length }
        maxArr.push(max)
     } else if(max === groupResult[item].length)
        maxArr.push({ value:item, count: groupResult[item].length })
   }
   return maxArr;
}

What are all the differences between src and data-src attributes?

If you want the image to load and display a particular image, then use .src to load that image URL.

If you want a piece of meta data (on any tag) that can contain a URL, then use data-src or any data-xxx that you want to select.

MDN documentation on data-xxxx attributes: https://developer.mozilla.org/en-US/docs/DOM/element.dataset

Example of src on an image tag where the image loads the JPEG for you and displays it:

<img id="myImage" src="http://mydomain.com/foo.jpg">

<script>
    var imageUrl = document.getElementById("myImage").src;
</script>

Example of 'data-src' on a non-image tag where the image is not loaded yet - it's just a piece of meta data on the div tag:

<div id="myDiv" data-src="http://mydomain.com/foo.jpg">

<script>
    // in all browsers
    var imageUrl = document.getElementById("myDiv").getAttribute("data-src");

    // or in modern browsers
    var imageUrl = document.getElementById("myDiv").dataset.src;
</script>

Example of data-src on an image tag used as a place to store the URL of an alternate image:

<img id="myImage" src="http://mydomain.com/foo.jpg" data-src="http://mydomain.com/foo.jpg">

<script>
    var item = document.getElementById("myImage");
    // switch the image to the URL specified in data-src
    item.src = item.dataset.src;
</script>

How to specify preference of library path?

This is an old question, but no one seems to have mentioned this.

You were getting lucky that the thing was linking at all.

You needed to change

g++ -g -Wall -o my_binary -L/my/dir -lfoo bar.cpp

to this:

g++ -g -Wall -o my_binary -L/my/dir bar.cpp -lfoo

Your linker keeps track of symbols it needs to resolve. If it reads the library first, it doesn't have any needed symbols, so it ignores the symbols in it. Specify the libraries after the things that need to link to them so that your linker has symbols to find in them.

Also, -lfoo makes it search specifically for a file named libfoo.a or libfoo.so as needed. Not libfoo.so.0. So either ln the name or rename the library as appopriate.

To quote the gcc man page:

-l library
   ...
   It makes a difference where in the command you 
   write this option; the linker searches and processes 
   libraries and object files in the order they are 
   specified.  Thus, foo.o -lz bar.o searches library z 
   after file foo.o but before bar.o.  If bar.o refers 
   to functions in z, those functions may not be loaded.

Adding the file directly to g++'s command line should have worked, unless of course, you put it prior to bar.cpp, causing the linker to ignore it for lacking any needed symbols, because no symbols were needed yet.

android:layout_height 50% of the screen size

You should do something like that:

<LinearLayout
    android:id="@+id/widget34"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:layout_below="@+id/tv_scanning_for"
    android:layout_centerHorizontal="true">

    <ListView
        android:id="@+id/lv_events"
        android:textSize="18sp"         
        android:cacheColorHint="#00000000"
        android:layout_height="1"
        android:layout_width="fill_parent"
        android:layout_weight="0dp"
        android:layout_below="@+id/tv_scanning_for"
        android:layout_centerHorizontal="true"
        />

</LinearLayout>

Also use dp instead px or read about it here.

Take nth column in a text file

One more simple variant -

$ while read line
  do
      set $line          # assigns words in line to positional parameters
      echo "$3 $5"
  done < file

How to access environment variable values?

The original question (first part) was "how to check environment variables in Python."

Here's how to check if $FOO is set:

try:  
   os.environ["FOO"]
except KeyError: 
   print "Please set the environment variable FOO"
   sys.exit(1)

How do I save JSON to local text file

Here is a solution on pure js. You can do it with html5 saveAs. For example this lib could be helpful: https://github.com/eligrey/FileSaver.js
Look at the demo: http://eligrey.com/demos/FileSaver.js/
P.S. There is no information about json save, but you can do it changing file type to "application/json" and format to .json

How do I set the path to a DLL file in Visual Studio?

In your Project properties(Right click on project, click on property button) ? Configuration Properties ? Build Events ? Post Build Events ? Command Line.

Edit and add one instruction to command line. for example copy botan.dll from source path to location where is being executed the program.

copy /Y "$(SolutionDir)ProjectDirs\x64\Botan\lib\botan.dll" "$(TargetDir)"

Project Properties

JPA: how do I persist a String into a database field, type MYSQL Text

for mysql 'text':

@Column(columnDefinition = "TEXT")
private String description;

for mysql 'longtext':

@Lob
private String description;

Undo git stash pop that results in merge conflict

As it turns out, Git is smart enough not to drop a stash if it doesn't apply cleanly. I was able to get to the desired state with the following steps:

  1. To unstage the merge conflicts: git reset HEAD . (note the trailing dot)
  2. To save the conflicted merge (just in case): git stash
  3. To return to master: git checkout master
  4. To pull latest changes: git fetch upstream; git merge upstream/master
  5. To correct my new branch: git checkout new-branch; git rebase master
  6. To apply the correct stashed changes (now 2nd on the stack): git stash apply stash@{1}

How to properly -filter multiple strings in a PowerShell copy script

Get-ChildItem $originalPath\* -Include @("*.gif", "*.jpg", "*.xls*", "*.doc*", "*.pdf*", "*.wav*", "*.ppt")

How to Multi-thread an Operation Within a Loop in Python

Edit 2018-02-06: revision based on this comment

Edit: forgot to mention that this works on Python 2.7.x

There's multiprocesing.pool, and the following sample illustrates how to use one of them:

from multiprocessing.pool import ThreadPool as Pool
# from multiprocessing import Pool

pool_size = 5  # your "parallelness"

# define worker function before a Pool is instantiated
def worker(item):
    try:
        api.my_operation(item)
    except:
        print('error with item')

pool = Pool(pool_size)

for item in items:
    pool.apply_async(worker, (item,))

pool.close()
pool.join()

Now if you indeed identify that your process is CPU bound as @abarnert mentioned, change ThreadPool to the process pool implementation (commented under ThreadPool import). You can find more details here: http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers

How to open spss data files in excel?

You can do it via ODBC. The steps to do it:

  1. Install IBM SPSS Statistics Data File Driver. Standalone Driver is enough.
  2. Create DNS via ODBC manager.
  3. Use the data importer in Excel via ODBC by selecting created DNS.

urllib2 and json

To read json response use json.loads(). Here is the sample.

import json
import urllib
import urllib2

post_params = {
    'foo' : bar
}

params = urllib.urlencode(post_params)
response = urllib2.urlopen(url, params)
json_response = json.loads(response.read())

SQL query to check if a name begins and ends with a vowel

You can use LEFT() and RIGHT() functions. Left(CITY,1) will get the first character of CITY from left. Right(CITY,1) will get the first character of CITY from right (last character of CITY).

DISTINCT is used to remove duplicates. To make the comparison case-insensitive, we will use the LOWER() function.

SELECT DISTINCT CITY
FROM STATION
WHERE LOWER(LEFT(CITY,1)) IN ('a', 'e', 'i', 'o', 'u') AND
      LOWER(RIGHT(CITY,1)) IN ('a', 'e', 'i', 'o', 'u')

How to define custom exception class in Java, the easiest way?

A typical custom exception I'd define is something like this:

public class CustomException extends Exception {

    public CustomException(String message) {
        super(message);
    }

    public CustomException(String message, Throwable throwable) {
        super(message, throwable);
    }

}

I even create a template using Eclipse so I don't have to write all the stuff over and over again.

Bootstrap 3 Glyphicons CDN

If you only want to have glyphicons icons without any additional css you can create a css file and put the code below and include it into main css file.

I have to create this extra file as link below was messing with my site styles too.

//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css

Instead to using it directly I created a css file bootstrap-glyphicons.css

_x000D_
_x000D_
@font-face{font-family:'Glyphicons Halflings';src:url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot');src:url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.woff') format('woff'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.ttf') format('truetype'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:normal;line-height:1;-webkit-font-smoothing:antialiased;}_x000D_
.glyphicon-asterisk:before{content:"\2a";}_x000D_
.glyphicon-plus:before{content:"\2b";}_x000D_
.glyphicon-euro:before{content:"\20ac";}_x000D_
.glyphicon-minus:before{content:"\2212";}_x000D_
.glyphicon-cloud:before{content:"\2601";}_x000D_
.glyphicon-envelope:before{content:"\2709";}_x000D_
.glyphicon-pencil:before{content:"\270f";}_x000D_
.glyphicon-glass:before{content:"\e001";}_x000D_
.glyphicon-music:before{content:"\e002";}_x000D_
.glyphicon-search:before{content:"\e003";}_x000D_
.glyphicon-heart:before{content:"\e005";}_x000D_
.glyphicon-star:before{content:"\e006";}_x000D_
.glyphicon-star-empty:before{content:"\e007";}_x000D_
.glyphicon-user:before{content:"\e008";}_x000D_
.glyphicon-film:before{content:"\e009";}_x000D_
.glyphicon-th-large:before{content:"\e010";}_x000D_
.glyphicon-th:before{content:"\e011";}_x000D_
.glyphicon-th-list:before{content:"\e012";}_x000D_
.glyphicon-ok:before{content:"\e013";}_x000D_
.glyphicon-remove:before{content:"\e014";}_x000D_
.glyphicon-zoom-in:before{content:"\e015";}_x000D_
.glyphicon-zoom-out:before{content:"\e016";}_x000D_
.glyphicon-off:before{content:"\e017";}_x000D_
.glyphicon-signal:before{content:"\e018";}_x000D_
.glyphicon-cog:before{content:"\e019";}_x000D_
.glyphicon-trash:before{content:"\e020";}_x000D_
.glyphicon-home:before{content:"\e021";}_x000D_
.glyphicon-file:before{content:"\e022";}_x000D_
.glyphicon-time:before{content:"\e023";}_x000D_
.glyphicon-road:before{content:"\e024";}_x000D_
.glyphicon-download-alt:before{content:"\e025";}_x000D_
.glyphicon-download:before{content:"\e026";}_x000D_
.glyphicon-upload:before{content:"\e027";}_x000D_
.glyphicon-inbox:before{content:"\e028";}_x000D_
.glyphicon-play-circle:before{content:"\e029";}_x000D_
.glyphicon-repeat:before{content:"\e030";}_x000D_
.glyphicon-refresh:before{content:"\e031";}_x000D_
.glyphicon-list-alt:before{content:"\e032";}_x000D_
.glyphicon-flag:before{content:"\e034";}_x000D_
.glyphicon-headphones:before{content:"\e035";}_x000D_
.glyphicon-volume-off:before{content:"\e036";}_x000D_
.glyphicon-volume-down:before{content:"\e037";}_x000D_
.glyphicon-volume-up:before{content:"\e038";}_x000D_
.glyphicon-qrcode:before{content:"\e039";}_x000D_
.glyphicon-barcode:before{content:"\e040";}_x000D_
.glyphicon-tag:before{content:"\e041";}_x000D_
.glyphicon-tags:before{content:"\e042";}_x000D_
.glyphicon-book:before{content:"\e043";}_x000D_
.glyphicon-print:before{content:"\e045";}_x000D_
.glyphicon-font:before{content:"\e047";}_x000D_
.glyphicon-bold:before{content:"\e048";}_x000D_
.glyphicon-italic:before{content:"\e049";}_x000D_
.glyphicon-text-height:before{content:"\e050";}_x000D_
.glyphicon-text-width:before{content:"\e051";}_x000D_
.glyphicon-align-left:before{content:"\e052";}_x000D_
.glyphicon-align-center:before{content:"\e053";}_x000D_
.glyphicon-align-right:before{content:"\e054";}_x000D_
.glyphicon-align-justify:before{content:"\e055";}_x000D_
.glyphicon-list:before{content:"\e056";}_x000D_
.glyphicon-indent-left:before{content:"\e057";}_x000D_
.glyphicon-indent-right:before{content:"\e058";}_x000D_
.glyphicon-facetime-video:before{content:"\e059";}_x000D_
.glyphicon-picture:before{content:"\e060";}_x000D_
.glyphicon-map-marker:before{content:"\e062";}_x000D_
.glyphicon-adjust:before{content:"\e063";}_x000D_
.glyphicon-tint:before{content:"\e064";}_x000D_
.glyphicon-edit:before{content:"\e065";}_x000D_
.glyphicon-share:before{content:"\e066";}_x000D_
.glyphicon-check:before{content:"\e067";}_x000D_
.glyphicon-move:before{content:"\e068";}_x000D_
.glyphicon-step-backward:before{content:"\e069";}_x000D_
.glyphicon-fast-backward:before{content:"\e070";}_x000D_
.glyphicon-backward:before{content:"\e071";}_x000D_
.glyphicon-play:before{content:"\e072";}_x000D_
.glyphicon-pause:before{content:"\e073";}_x000D_
.glyphicon-stop:before{content:"\e074";}_x000D_
.glyphicon-forward:before{content:"\e075";}_x000D_
.glyphicon-fast-forward:before{content:"\e076";}_x000D_
.glyphicon-step-forward:before{content:"\e077";}_x000D_
.glyphicon-eject:before{content:"\e078";}_x000D_
.glyphicon-chevron-left:before{content:"\e079";}_x000D_
.glyphicon-chevron-right:before{content:"\e080";}_x000D_
.glyphicon-plus-sign:before{content:"\e081";}_x000D_
.glyphicon-minus-sign:before{content:"\e082";}_x000D_
.glyphicon-remove-sign:before{content:"\e083";}_x000D_
.glyphicon-ok-sign:before{content:"\e084";}_x000D_
.glyphicon-question-sign:before{content:"\e085";}_x000D_
.glyphicon-info-sign:before{content:"\e086";}_x000D_
.glyphicon-screenshot:before{content:"\e087";}_x000D_
.glyphicon-remove-circle:before{content:"\e088";}_x000D_
.glyphicon-ok-circle:before{content:"\e089";}_x000D_
.glyphicon-ban-circle:before{content:"\e090";}_x000D_
.glyphicon-arrow-left:before{content:"\e091";}_x000D_
.glyphicon-arrow-right:before{content:"\e092";}_x000D_
.glyphicon-arrow-up:before{content:"\e093";}_x000D_
.glyphicon-arrow-down:before{content:"\e094";}_x000D_
.glyphicon-share-alt:before{content:"\e095";}_x000D_
.glyphicon-resize-full:before{content:"\e096";}_x000D_
.glyphicon-resize-small:before{content:"\e097";}_x000D_
.glyphicon-exclamation-sign:before{content:"\e101";}_x000D_
.glyphicon-gift:before{content:"\e102";}_x000D_
.glyphicon-leaf:before{content:"\e103";}_x000D_
.glyphicon-eye-open:before{content:"\e105";}_x000D_
.glyphicon-eye-close:before{content:"\e106";}_x000D_
.glyphicon-warning-sign:before{content:"\e107";}_x000D_
.glyphicon-plane:before{content:"\e108";}_x000D_
.glyphicon-random:before{content:"\e110";}_x000D_
.glyphicon-comment:before{content:"\e111";}_x000D_
.glyphicon-magnet:before{content:"\e112";}_x000D_
.glyphicon-chevron-up:before{content:"\e113";}_x000D_
.glyphicon-chevron-down:before{content:"\e114";}_x000D_
.glyphicon-retweet:before{content:"\e115";}_x000D_
.glyphicon-shopping-cart:before{content:"\e116";}_x000D_
.glyphicon-folder-close:before{content:"\e117";}_x000D_
.glyphicon-folder-open:before{content:"\e118";}_x000D_
.glyphicon-resize-vertical:before{content:"\e119";}_x000D_
.glyphicon-resize-horizontal:before{content:"\e120";}_x000D_
.glyphicon-hdd:before{content:"\e121";}_x000D_
.glyphicon-bullhorn:before{content:"\e122";}_x000D_
.glyphicon-certificate:before{content:"\e124";}_x000D_
.glyphicon-thumbs-up:before{content:"\e125";}_x000D_
.glyphicon-thumbs-down:before{content:"\e126";}_x000D_
.glyphicon-hand-right:before{content:"\e127";}_x000D_
.glyphicon-hand-left:before{content:"\e128";}_x000D_
.glyphicon-hand-up:before{content:"\e129";}_x000D_
.glyphicon-hand-down:before{content:"\e130";}_x000D_
.glyphicon-circle-arrow-right:before{content:"\e131";}_x000D_
.glyphicon-circle-arrow-left:before{content:"\e132";}_x000D_
.glyphicon-circle-arrow-up:before{content:"\e133";}_x000D_
.glyphicon-circle-arrow-down:before{content:"\e134";}_x000D_
.glyphicon-globe:before{content:"\e135";}_x000D_
.glyphicon-tasks:before{content:"\e137";}_x000D_
.glyphicon-filter:before{content:"\e138";}_x000D_
.glyphicon-fullscreen:before{content:"\e140";}_x000D_
.glyphicon-dashboard:before{content:"\e141";}_x000D_
.glyphicon-heart-empty:before{content:"\e143";}_x000D_
.glyphicon-link:before{content:"\e144";}_x000D_
.glyphicon-phone:before{content:"\e145";}_x000D_
.glyphicon-usd:before{content:"\e148";}_x000D_
.glyphicon-gbp:before{content:"\e149";}_x000D_
.glyphicon-sort:before{content:"\e150";}_x000D_
.glyphicon-sort-by-alphabet:before{content:"\e151";}_x000D_
.glyphicon-sort-by-alphabet-alt:before{content:"\e152";}_x000D_
.glyphicon-sort-by-order:before{content:"\e153";}_x000D_
.glyphicon-sort-by-order-alt:before{content:"\e154";}_x000D_
.glyphicon-sort-by-attributes:before{content:"\e155";}_x000D_
.glyphicon-sort-by-attributes-alt:before{content:"\e156";}_x000D_
.glyphicon-unchecked:before{content:"\e157";}_x000D_
.glyphicon-expand:before{content:"\e158";}_x000D_
.glyphicon-collapse-down:before{content:"\e159";}_x000D_
.glyphicon-collapse-up:before{content:"\e160";}_x000D_
.glyphicon-log-in:before{content:"\e161";}_x000D_
.glyphicon-flash:before{content:"\e162";}_x000D_
.glyphicon-log-out:before{content:"\e163";}_x000D_
.glyphicon-new-window:before{content:"\e164";}_x000D_
.glyphicon-record:before{content:"\e165";}_x000D_
.glyphicon-save:before{content:"\e166";}_x000D_
.glyphicon-open:before{content:"\e167";}_x000D_
.glyphicon-saved:before{content:"\e168";}_x000D_
.glyphicon-import:before{content:"\e169";}_x000D_
.glyphicon-export:before{content:"\e170";}_x000D_
.glyphicon-send:before{content:"\e171";}_x000D_
.glyphicon-floppy-disk:before{content:"\e172";}_x000D_
.glyphicon-floppy-saved:before{content:"\e173";}_x000D_
.glyphicon-floppy-remove:before{content:"\e174";}_x000D_
.glyphicon-floppy-save:before{content:"\e175";}_x000D_
.glyphicon-floppy-open:before{content:"\e176";}_x000D_
.glyphicon-credit-card:before{content:"\e177";}_x000D_
.glyphicon-transfer:before{content:"\e178";}_x000D_
.glyphicon-cutlery:before{content:"\e179";}_x000D_
.glyphicon-header:before{content:"\e180";}_x000D_
.glyphicon-compressed:before{content:"\e181";}_x000D_
.glyphicon-earphone:before{content:"\e182";}_x000D_
.glyphicon-phone-alt:before{content:"\e183";}_x000D_
.glyphicon-tower:before{content:"\e184";}_x000D_
.glyphicon-stats:before{content:"\e185";}_x000D_
.glyphicon-sd-video:before{content:"\e186";}_x000D_
.glyphicon-hd-video:before{content:"\e187";}_x000D_
.glyphicon-subtitles:before{content:"\e188";}_x000D_
.glyphicon-sound-stereo:before{content:"\e189";}_x000D_
.glyphicon-sound-dolby:before{content:"\e190";}_x000D_
.glyphicon-sound-5-1:before{content:"\e191";}_x000D_
.glyphicon-sound-6-1:before{content:"\e192";}_x000D_
.glyphicon-sound-7-1:before{content:"\e193";}_x000D_
.glyphicon-copyright-mark:before{content:"\e194";}_x000D_
.glyphicon-registration-mark:before{content:"\e195";}_x000D_
.glyphicon-cloud-download:before{content:"\e197";}_x000D_
.glyphicon-cloud-upload:before{content:"\e198";}_x000D_
.glyphicon-tree-conifer:before{content:"\e199";}_x000D_
.glyphicon-tree-deciduous:before{content:"\e200";}_x000D_
.glyphicon-briefcase:before{content:"\1f4bc";}_x000D_
.glyphicon-calendar:before{content:"\1f4c5";}_x000D_
.glyphicon-pushpin:before{content:"\1f4cc";}_x000D_
.glyphicon-paperclip:before{content:"\1f4ce";}_x000D_
.glyphicon-camera:before{content:"\1f4f7";}_x000D_
.glyphicon-lock:before{content:"\1f512";}_x000D_
.glyphicon-bell:before{content:"\1f514";}_x000D_
.glyphicon-bookmark:before{content:"\1f516";}_x000D_
.glyphicon-fire:before{content:"\1f525";}_x000D_
.glyphicon-wrench:before{content:"\1f527";}
_x000D_
_x000D_
_x000D_

And imported the created css file into my main css file which enable me to just import the glyphicons only. Hope this help

@import url("bootstrap-glyphicons.css");

Execute a file with arguments in Python shell

You're confusing loading a module into the current interpreter process and calling a Python script externally.

The former can be done by importing the file you're interested in. execfile is similar to importing but it simply evaluates the file rather than creates a module out of it. Similar to "sourcing" in a shell script.

The latter can be done using the subprocess module. You spawn off another instance of the interpreter and pass whatever parameters you want to that. This is similar to shelling out in a shell script using backticks.

Android Camera : data intent returns null

Kotlin code that works for me:

 private fun takePhotoFromCamera() {
          val intent = Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE)
        startActivityForResult(intent, PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA)
      }

And get Result :

 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
 if (requestCode == PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA) {
         if (resultCode == Activity.RESULT_OK) {
           val photo: Bitmap? =  MediaStore.Images.Media.getBitmap(this.contentResolver, Uri.parse( data!!.dataString)   )
            // Do something here : set image to an ImageView or save it ..   
              imgV_pic.imageBitmap = photo 
        } else if (resultCode == Activity.RESULT_CANCELED) {
            Log.i(TAG, "Camera  , RESULT_CANCELED ")
        }

    }

}

and don't forget to declare request code:

companion object {
 const val PERMISSIONS_REQUEST_TAKE_PICTURE_CAMERA = 300
  }

PHP Function with Optional Parameters

func( "1", "2", default, default, default, default, default, "eight" );

How to access local files of the filesystem in the Android emulator?

In Android Studio 3.0 and later do this:

View > Tool Windows > Device File Explorer

Recursive Fibonacci

The reason is because Fibonacci sequence starts with two known entities, 0 and 1. Your code only checks for one of them (being one).

Change your code to

int fib(int x) {
    if (x == 0)
        return 0;

    if (x == 1)
        return 1;

    return fib(x-1)+fib(x-2);
}

To include both 0 and 1.

ASP.NET MVC: What is the correct way to redirect to pages/actions in MVC?

1) When the user logs out (Forms signout in Action) I want to redirect to a login page.

public ActionResult Logout() {
    //log out the user
    return RedirectToAction("Login");
}

2) In a Controller or base Controller event eg Initialze, I want to redirect to another page (AbsoluteRootUrl + Controller + Action)

Why would you want to redirect from a controller init?

the routing engine automatically handles requests that come in, if you mean you want to redirect from the index action on a controller simply do:

public ActionResult Index() {
    return RedirectToAction("whateverAction", "whateverController");
}

List to array conversion to use ravel() function

Use the following code:

import numpy as np

myArray=np.array([1,2,4])  #func used to convert [1,2,3] list into an array
print(myArray)

How do you check if a variable is an array in JavaScript?

From w3schools:

function isArray(myArray) {
    return myArray.constructor.toString().indexOf("Array") > -1;
}

Run a script in Dockerfile

RUN and ENTRYPOINT are two different ways to execute a script.

RUN means it creates an intermediate container, runs the script and freeze the new state of that container in a new intermediate image. The script won't be run after that: your final image is supposed to reflect the result of that script.

ENTRYPOINT means your image (which has not executed the script yet) will create a container, and runs that script.

In both cases, the script needs to be added, and a RUN chmod +x /bootstrap.sh is a good idea.

It should also start with a shebang (like #!/bin/sh)

Considering your script (bootstrap.sh: a couple of git config --global commands), it would be best to RUN that script once in your Dockerfile, but making sure to use the right user (the global git config file is %HOME%/.gitconfig, which by default is the /root one)

Add to your Dockerfile:

RUN /bootstrap.sh

Then, when running a container, check the content of /root/.gitconfig to confirm the script was run.

Read files from a Folder present in project

below code should work:

string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Data\Names.txt");
string[] files = File.ReadAllLines(path);

Using querySelectorAll to retrieve direct children

if you know for sure the element is unique (such as your case with the ID):

myDiv.parentElement.querySelectorAll("#myDiv > .foo");

For a more "global" solution: (use a matchesSelector shim)

function getDirectChildren(elm, sel){
    var ret = [], i = 0, l = elm.childNodes.length;
    for (var i; i < l; ++i){
        if (elm.childNodes[i].matchesSelector(sel)){
            ret.push(elm.childNodes[i]);
        }
    }
    return ret;
}

where elm is your parent element, and sel is your selector. Could totally be used as a prototype as well.

How do I output the difference between two specific revisions in Subversion?

To compare entire revisions, it's simply:

svn diff -r 8979:11390


If you want to compare the last committed state against your currently saved working files, you can use convenience keywords:

svn diff -r PREV:HEAD

(Note, without anything specified afterwards, all files in the specified revisions are compared.)


You can compare a specific file if you add the file path afterwards:

svn diff -r 8979:HEAD /path/to/my/file.php

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

You can do something like this:

select case when o.NegotiatedPrice > o.SuggestedPrice 
then o.NegotiatedPrice
else o.SuggestedPrice
end

Axios having CORS issue

your server should enable the cross origin requests, not the client. To do this, you can check this nice page with implementations and configurations for multiple platforms

Java regex email

This is a valid regex for validating e-mails. It's totally compliant with RFC822 and accepts IP address and server names (for intranet purposes).

public static boolean isEmailValid(String email) {
    final Pattern EMAIL_REGEX = Pattern.compile("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", Pattern.CASE_INSENSITIVE);
    return EMAIL_REGEX.matcher(email).matches();
}

Here are some output examples, when you call isEmailValid(emailVariable):

[email protected] // valid
[email protected] // valid
[email protected] // valid (with +label - Gmail accepts it!)
[email protected] // valid (with IP addresses)
[email protected] // valid (with +label and IP address)
john.foo@someserver // valid (with no first domain level)
[email protected] // valid (case insensitive)
@someserver // invalid
@someserver.com // invalid
john@. // invalid
[email protected] // invalid

How to add \newpage in Rmarkdown in a smart way?

Simply \newpage or \pagebreak will work, e.g.

hello world
\newpage
```{r, echo=FALSE}
1+1
```
\pagebreak
```{r, echo=FALSE}
plot(1:10)
```

This solution assumes you are knitting PDF. For HTML, you can achieve a similar effect by adding a tag <P style="page-break-before: always">. Note that you likely won't see a page break in your browser (HTMLs don't have pages per se), but the printing layout will have it.

Ubuntu says "bash: ./program Permission denied"

chmod u+x program_name. Then execute it.

If that does not work, copy the program from the USB device to a native volume on the system. Then chmod u+x program_name on the local copy and execute that.

Unix and Unix-like systems generally will not execute a program unless it is marked with permission to execute. The way you copied the file from one system to another (or mounted an external volume) may have turned off execute permission (as a safety feature). The command chmod u+x name adds permission for the user that owns the file to execute it.

That command only changes the permissions associated with the file; it does not change the security controls associated with the entire volume. If it is security controls on the volume that are interfering with execution (for example, a noexec option may be specified for a volume in the Unix fstab file, which says not to allow execute permission for files on the volume), then you can remount the volume with options to allow execution. However, copying the file to a local volume may be a quicker and easier solution.

failed to find target with hash string 'android-22'

I modified build.gradle compileSdkVersion to 23 from 22 and targetSdkVersion to 23 from 22.

My API level was 23. I had to update the API version to 23 as well.

I had to import my project from Eclipse to Android Studio. It worked for me.

Copy or rsync command

The command as written will create new directories and files with the current date and time stamp, and yourself as the owner. If you are the only user on your system and you are doing this daily it may not matter much. But if preserving those attributes matters to you, you can modify your command with

cp -pur /home/abc/* /mnt/windowsabc/

The -p will preserve ownership, timestamps, and mode of the file. This can be pretty important depending on what you're backing up.

The alternative command with rsync would be

rsync -avh /home/abc/* /mnt/windowsabc

With rsync, -a indicates "archive" which preserves all those attributes mentioned above. -v indicates "verbose" which just lists what it's doing with each file as it runs. -z is left out here for local copies, but is for compression, which will help if you are backing up over a network. Finally, the -h tells rsync to report sizes in human-readable formats like MB,GB,etc.

Out of curiosity, I ran one copy to prime the system and avoid biasing against the first run, then I timed the following on a test run of 1GB of files from an internal SSD drive to a USB-connected HDD. These simply copied to empty target directories.

cp -pur    : 19.5 seconds
rsync -ah  : 19.6 seconds
rsync -azh : 61.5 seconds

Both commands seem to be about the same, although zipping and unzipping obviously tax the system where bandwidth is not a bottleneck.

How to write "not in ()" sql query using join

This article:

may be if interest to you.

In a couple of words, this query:

SELECT  d1.short_code
FROM    domain1 d1
LEFT JOIN
        domain2 d2
ON      d2.short_code = d1.short_code
WHERE   d2.short_code IS NULL

will work but it is less efficient than a NOT NULL (or NOT EXISTS) construct.

You can also use this:

SELECT  short_code
FROM    domain1
EXCEPT
SELECT  short_code
FROM    domain2

This is using neither NOT IN nor WHERE (and even no joins!), but this will remove all duplicates on domain1.short_code if any.

Is there a wikipedia API just for retrieve content summary?

This is the code I'm using right now for a website I'm making that needs to get the leading paragraphs / summary / section 0 of off Wikipedia articles, and it's all done within the browser (client side javascript) thanks to the magick of JSONP! --> http://jsfiddle.net/gautamadude/HMJJg/1/

It uses the Wikipedia API to get the leading paragraphs (called section 0) in HTML like so: http://en.wikipedia.org/w/api.php?format=json&action=parse&page=Stack_Overflow&prop=text&section=0&callback=?

It then strips the HTML and other undesired data, giving you a clean string of an article summary, if you want you can, with a little tweaking, get a "p" html tag around the leading paragraphs but right now there is just a newline character between them.

Code:

var url = "http://en.wikipedia.org/wiki/Stack_Overflow";
var title = url.split("/").slice(4).join("/");

//Get Leading paragraphs (section 0)
$.getJSON("http://en.wikipedia.org/w/api.php?format=json&action=parse&page=" + title + "&prop=text&section=0&callback=?", function (data) {
    for (text in data.parse.text) {
        var text = data.parse.text[text].split("<p>");
        var pText = "";

        for (p in text) {
            //Remove html comment
            text[p] = text[p].split("<!--");
            if (text[p].length > 1) {
                text[p][0] = text[p][0].split(/\r\n|\r|\n/);
                text[p][0] = text[p][0][0];
                text[p][0] += "</p> ";
            }
            text[p] = text[p][0];

            //Construct a string from paragraphs
            if (text[p].indexOf("</p>") == text[p].length - 5) {
                var htmlStrip = text[p].replace(/<(?:.|\n)*?>/gm, '') //Remove HTML
                var splitNewline = htmlStrip.split(/\r\n|\r|\n/); //Split on newlines
                for (newline in splitNewline) {
                    if (splitNewline[newline].substring(0, 11) != "Cite error:") {
                        pText += splitNewline[newline];
                        pText += "\n";
                    }
                }
            }
        }
        pText = pText.substring(0, pText.length - 2); //Remove extra newline
        pText = pText.replace(/\[\d+\]/g, ""); //Remove reference tags (e.x. [1], [4], etc)
        document.getElementById('textarea').value = pText
        document.getElementById('div_text').textContent = pText
    }
});

Why are my CSS3 media queries not working on mobile devices?

I encountered this issue recently too, and I later found out it was because I didn't put a space between and and (. This was the error

@media screen and(max-width:768px){
}

Then I changed it to this to correct it

@media screen and (max-width:768px){
}

How can I throw CHECKED exceptions from inside Java 8 streams?

If you use Spring Framework you can use ReflectionUtils.rethrowRuntimeException(ex) described here https://docs.spring.io/spring/docs/5.2.8.RELEASE/javadoc-api/org/springframework/util/ReflectionUtils.html#rethrowRuntimeException-java.lang.Throwable- The beauty of this util method is that it re-throws exactly same exception but of Runtime type, so your catch block that expects exception of checked type will still catch it as intended.

Get records of current month

Try this query:

SELECT *
FROM table 
WHERE MONTH(FROM_UNIXTIME(columnName))= MONTH(CURDATE())

www-data permissions?

sudo chown -R yourname:www-data cake

then

sudo chmod -R g+s cake

First command changes owner and group.

Second command adds s attribute which will keep new files and directories within cake having the same group permissions.

How to install VS2015 Community Edition offline

The following worked for me on a Windows 8.1 machine to download and prepare the setup folder, and then on a Windows 10 laptop to install:

  1. Go to https://my.visualstudio.com/downloads?q=visual%20studio%20community%202015
  2. Select “Visual Studio Community 2015 with Update 3” x64, English, DVD, and Download.
  3. Open the folder containing the download, which is called: en_visual_studio_community_2015_with_update_3_x86_x64_dvd_8923300.iso and its size is 7,617,847,296 bytes.
  4. Right-click on the file name: Mount
  5. On the mount folder, shift-right-click on an empty space: Open command window here
  6. On the command window: vs_community.exe /layout "blah blah blah blah \Visual Studio 2015\Setup" (or whatever path you want; the Setup folder gets created).
  7. Follow the dialog box instructions.

When I did this, it remained for exactly two hours and ten secs in the Acquiring: Optional items. Don’t despair.

When it completed, the size of the Setup folder was 12.9 GB. Compare with the size of the .iso above.

After completion, I succeeded on installing without a network connection, and that even though on completion I had got the following: enter image description here

How do I set an ASP.NET Label text from code behind on page load?

In your ASP.NET page:

<asp:Label ID="UserNameLabel" runat="server" />

In your code behind (assuming you're using C#):

function Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
       UserNameLabel.Text = "User Name";
    }
}

Android Studio: “Execution failed for task ':app:mergeDebugResources'” if project is created on drive C:

Adding the right repository in Project build.gradle solved the issue. In my case Google Maven Repository was needed and was added as below in the build.gradle

repositories {
google()
}

refer to this link for declaring repositories: https://docs.gradle.org/current/userguide/declaring_repositories.html

Pandas: rolling mean by time interval

Check that your index is really datetime, not str Can be helpful:

data.index = pd.to_datetime(data['Index']).values

How do I declare an array with a custom class?

In order to create an array of objects, the objects need a constructor that doesn't take any paramters (that creates a default form of the object, eg. with both strings empty). This is what the error message means. The compiler automatically generates a constructor which creates an empty object unless there are any other constructors.

If it makes sense for the array elements to be created empty (in which case the members acquire their default values, in this case, empty strings), you should:

-Write an empty constructor:

class name {
  public:
    string first;
    string last;

  name() { }
  name(string a, string b){
    first = a;
    last = b;
  }
};

-Or, if you don't need it, remove the existing constructor.

If an "empty" version of your class makes no sense, there is no good solution to provide initialisation paramters to all the elements of the array at compile time. You can:

  • Have a constructor create an empty version of the class anyway, and an init() function which does the real initialisation
  • Use a vector, and on initialisation create the objects and insert them into the vector, either using vector::insert or a loop, and trust that not doing it at compile time doesn't matter.
  • If the object can't be copied either, you can use an array/vector of smart pointers to the object and allocate them on initialisation.
  • If you can use C++11 I think (?) you can use initialiser lists to initialise a vector and intialise it (I'm not sure if that works with any contructor or only if the object is created from a single value of another type). Eg: .
 std::vector<std::string> v = { "xyzzy", "plugh", "abracadabra" };

`

Replace String in all files in Eclipse

Ctrl+F gives me Find/Replace dialog box.

Or you can,

First Alt+A

Next Alt+F

Then press on Replace button.

If non of them worked:

Goto -> Window -> Preferences -> General -> Keys and search for replace then you will see binding for Find and replace. In the bottom of that window, you can add your key to Binding text box. There you can add or edit any keys as shortcut.

Mac install and open mysql using terminal

This command works for me:

./mysql -u root -p

(PS: I'm working on mac through terminal)

Get MD5 hash of big files in Python

Break the file into 8192-byte chunks (or some other multiple of 128 bytes) and feed them to MD5 consecutively using update().

This takes advantage of the fact that MD5 has 128-byte digest blocks (8192 is 128×64). Since you're not reading the entire file into memory, this won't use much more than 8192 bytes of memory.

In Python 3.8+ you can do

import hashlib
with open("your_filename.txt", "rb") as f:
    file_hash = hashlib.md5()
    while chunk := f.read(8192):
        file_hash.update(chunk)
print(file_hash.digest())
print(file_hash.hexdigest())  # to get a printable str instead of bytes

How to open existing project in Eclipse

Window->Show View->Navigator, should pop up the navigator panel on the left hand side, showing the projects list.

It's probably already open in the workspace, but you may have closed the navigator panel, so it looks like you don't have the project open.

Eclipse using ADT Build v22.0.0-675183 on Linux.

How do you run your own code alongside Tkinter's event loop?

When writing your own loop, as in the simulation (I assume), you need to call the update function which does what the mainloop does: updates the window with your changes, but you do it in your loop.

def task():
   # do something
   root.update()

while 1:
   task()  

Is there a way to add/remove several classes in one single instruction with classList?

I found a very simple method which is more modern and elegant way.


const el = document.querySelector('.m-element');

// To toggle
['class1', 'class2'].map((e) => el.classList.toggle(e));

// To add
['class1', 'class2'].map((e) => el.classList.add(e));

// To remove
['class1', 'class2'].map((e) => el.classList.remove(e));

Good thing is you can extend the class array or use any coming from API easily.

nvarchar(max) still being truncated

The problem with creating dynamic SQL using string expression is that SQL does limit the evaluation of string expressions to 4,000 chars. You can assign a longer string to an nvarchar(max) variable, but as soon as you include + in the expression (such as + CASE ... END + ), then the expression result is limited to 4,000 chars.

One way to fix this is to use CONCAT instead of +. For example:

SET @sql = CONCAT(@sql, N'
     ... dynamic SQL statements ...
    ', CASE ... END, N'
     ... dynamic SQL statements ...
    ')

Where @sql is declared as nvarchar(max).

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

Change the group permission for the folder

sudo chown -R w3cert /home/w3cert/.composer/cache/repo/https---packagist.org

and the Files folder too

sudo chown -R w3cert /home/w3cert/.composer/cache/files/

I'm assuming w3cert is your username, if not change the 4th parameter to your username.

If the problem still persists try

sudo chown -R w3cert /home/w3cert/.composer

Now, there is a chance that you won't be able to create your app directory, if that happens do the same for your html folder or the folder you are trying to create your laravel project in.

Hope this helps.

How do I view executed queries within SQL Server Management Studio?

Run the following query from Management Studio on a running process:

DBCC inputbuffer( spid# )

This will return the SQL currently being run against the database for the SPID provided. Note that you need appropriate permissions to run this command.

This is better than running a trace since it targets a specific SPID. You can see if it's long running based on its CPUTime and DiskIO.

Example to get details of SPID 64:

DBCC inputbuffer(64)

Cannot open local file - Chrome: Not allowed to load local resource

This solution worked for me in PHP. It opens the PDF in the browser.

// $path is the path to the pdf file
public function showPDF($path) {
    if($path) {
        header("Content-type: application/pdf");
        header("Content-Disposition: inline; filename=filename.pdf");
        @readfile($path);
    }
}

JavaFX Application Icon

stage.getIcons().add(new Image(<yourclassname>.class.getResourceAsStream("/icon.png" )));

You can add more than one icon with different sizes using this method.The images should be different sizes of the same image and the best size will be chosen. eg. 16x16, 32,32

round() for float in C++

There are 2 problems we are looking at:

  1. rounding conversions
  2. type conversion.

Rounding conversions mean rounding ± float/double to nearest floor/ceil float/double. May be your problem ends here. But if you are expected to return Int/Long, you need to perform type conversion, and thus "Overflow" problem might hit your solution. SO, do a check for error in your function

long round(double x) {
   assert(x >= LONG_MIN-0.5);
   assert(x <= LONG_MAX+0.5);
   if (x >= 0)
      return (long) (x+0.5);
   return (long) (x-0.5);
}

#define round(x) ((x) < LONG_MIN-0.5 || (x) > LONG_MAX+0.5 ?\
      error() : ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))

from : http://www.cs.tut.fi/~jkorpela/round.html

Select where count of one field is greater than one

Here you go:

SELECT Field1, COUNT(Field1)
  FROM Table1 
 GROUP BY Field1
HAVING COUNT(Field1) > 1
ORDER BY Field1 desc

How to use clock() in C++

#include <iostream>
#include <ctime>
#include <cstdlib> //_sleep()  --- just a function that waits a certain amount of milliseconds

using namespace std;

int main()
{

    clock_t cl;     //initializing a clock type

    cl = clock();   //starting time of clock

    _sleep(5167);   //insert code here

    cl = clock() - cl;  //end point of clock

    _sleep(1000);   //testing to see if it actually stops at the end point

    cout << cl/(double)CLOCKS_PER_SEC << endl;  //prints the determined ticks per second (seconds passed)


    return 0;
}

//outputs "5.17"

VirtualBox Cannot register the hard disk already exists

If there is no possibility to remove or change path to a hard disc file using Virtual Media Manager (in my case) then:

  1. Open '.vbox' and '.vbox-prev' (if exist) files in any text editor.
  2. Edit 'location' attribute of the element 'HardDisk' to your path, for example: "d:/VM/VirtualBox/Win10/Win10.vmdk" (screenshot).

Git diff between current branch and master but not including unmerged master commits

Here's what worked for me:

git diff origin/master...

This shows only the changes between my currently selected local branch and the remote master branch, and ignores all changes in my local branch that came from merge commits.

CodeIgniter: How to use WHERE clause and OR clause

$where = "name='Joe' AND status='boss' OR status='active'";

$this->db->where($where);

vbscript output to console

There are five ways to output text to the console:

Dim StdOut : Set StdOut = CreateObject("Scripting.FileSystemObject").GetStandardStream(1)

WScript.Echo "Hello"
WScript.StdOut.Write "Hello"
WScript.StdOut.WriteLine "Hello"
Stdout.WriteLine "Hello"
Stdout.Write "Hello"

WScript.Echo will output to console but only if the script is started using cscript.exe. It will output to message boxes if started using wscript.exe.

WScript.StdOut.Write and WScript.StdOut.WriteLine will always output to console.

StdOut.Write and StdOut.WriteLine will also always output to console. It requires extra object creation but it is about 10% faster than WScript.Echo.

Which is better: <script type="text/javascript">...</script> or <script>...</script>

You need to use <script type="text/javascript"> </script> unless you're using html5. In that case you are encouraged to prefer <script> ... </script> (because type attribute is specified by default to that value)

Could not resolve this reference. Could not locate the assembly

in 2020, this behavior still present with VS2019. (even if I clean projects from the solution explorer in VS2019, this not solves the problem)

The solution that worked for me was to open the folder of the project, and manually remove the \bin and \obj directories.

Creating virtual directories in IIS express

@Be.St.'s aprroach is true, but incomplete. I'm just copying his explanation with correcting the incorrect part.

IIS express configuration is managed by applicationhost.config.
You can find it in

Users\<username>\Documents\IISExpress\config folder.

Inside you can find the sites section that hold a section for each IIS Express configured site.

Add (or modify) a site section like this:

<site name="WebSiteWithVirtualDirectory" id="20">
   <application path="/" applicationPool="Clr4IntegratedAppPool">
     <virtualDirectory path="/" physicalPath="c:\temp\website1" />
     <virtualDirectory path="/OffSiteStuff" physicalPath="d:\temp\SubFolderApp" />
   </application>
   <bindings>
      <binding protocol="http" bindingInformation="*:1132:localhost" />
   </bindings>
</site>

Instead of adding a new application block, you should just add a new virtualDirectory element to the application parent element.

Edit - Visual Studio 2015

If you're looking for the applicationHost.config file and you're using VS2015 you'll find it in:

[solution_directory]/.vs/config/applicationHost.config

UTF-8 encoding in JSP page

This are special characters in html. Why dont you encode it? Check it out: http://www.degraeve.com/reference/specialcharacters.php

How to get unique values in an array

Here is an approach with customizable equals function which can be used for primitives as well as for custom objects:

Array.prototype.pushUnique = function(element, equalsPredicate = (l, r) => l == r) {
    let res = !this.find(item => equalsPredicate(item, element))
    if(res){
        this.push(element)
    }
    return res
}

usage:

//with custom equals for objects
myArrayWithObjects.pushUnique(myObject, (left, right) => left.id == right.id)

//with default equals for primitives
myArrayWithPrimitives.pushUnique(somePrimitive)

Change Timezone in Lumen or Laravel 5

In Lumen's .env file, specify the timezones. For India, it would be like:

APP_TIMEZONE = 'Asia/Calcutta'
DB_TIMEZONE = '+05:30'

How to use jquery $.post() method to submit form values

Get the value of your textboxes using val() and store them in a variable. Pass those values through $.post. In using the $.Post Submit button you can actually remove the form.

<script>

    username = $("#username").val(); 
    password = $("#password").val();

    $("#post-btn").click(function(){        
        $.post("process.php", { username:username, password:password } ,function(data){
            alert(data);
        });
    });
</script>

Update multiple rows using select statement

None of above answers worked for me in MySQL, the following query worked though:

UPDATE
    Table1 t1
    JOIN
    Table2 t2 ON t1.ID=t2.ID 
SET
    t1.value =t2.value
WHERE
    ...

Where is virtualenvwrapper.sh after pip install?

/usr/local/bin/virtualenvwrapper.sh

Add a column to a table, if it does not already exist

Here's another variation that worked for me.

IF NOT EXISTS (SELECT 1
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE upper(TABLE_NAME) = 'TABLENAME'
        AND upper(COLUMN_NAME) = 'COLUMNNAME')
BEGIN
    ALTER TABLE [dbo].[Person] ADD Column
END
GO

EDIT: Note that INFORMATION_SCHEMA views may not always be updated, use SYS.COLUMNS instead:

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS....

Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'

Similar error messages will pop up when transitioning from version 5 to 6. Here is an answer for the change to rxjs-6.

Import the individual operators, then use pipe instead of chaining.

import { map, delay, catchError } from 'rxjs/operators'; 

source.pipe(
  map(x => x + x),
  delay(4000),
  catchError(err => of('error found')),
).subscribe(printResult);

Error: More than one module matches. Use skip-import option to skip importing the component into the closest module

I had this warning when had this in angular.json config:

"prefix": "app_ng"

When changed to "app" all worked perfectly fine.

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

Definitely a great question. I've noted this also as a sub question of the choice for versions within IDEa that this link may help to address...

http://www.jetbrains.com/idea/features/editions_comparison_matrix.html

it as well potentially possesses a ground work for looking at your other IDE choices and the options they provide.

I'm thinking WebStorm is best for JavaScript and Git repo management, meaning the HTML5 CSS Cordova kinds of stacks, which is really where (I believe along with others) the future lies and energies should be focused now... but ya it depends on your needs, etc.

Anyway this tells that story too... http://www.jetbrains.com/products.html

Python Script Uploading files via FTP

To avoid getting the encryption error you can also try out below commands

ftp = ftplib.FTP_TLS("ftps.dummy.com")
ftp.login("username", "password")
ftp.prot_p()
file = open("filename", "rb")
ftp.storbinary("STOR filename", file)
file.close()
ftp.close()

ftp.prot_p() ensure that your connections are encrypted

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

I know this thread is a year old now but having experienced the same problem I managed to solve the problem by setting a target server for my project.

i.e. right-click on your project and select 'Properties' -> 'Targeted Runtimes' and select the server you going to run your web app on (Tomcat 6 or 7).

JavaScript single line 'if' statement - best syntax, this alternative?

As has already been stated, you can use:

&& style

lemons && document.write("foo gave me a bar");  

or

bracket-less style

if (lemons) document.write("foo gave me a bar");

short-circuit return

If, however, you wish to use the one line if statement to short-circuit a function though, you'd need to go with the bracket-less version like so:

if (lemons) return "foo gave me a bar";

as

lemons && return "foo gave me a bar"; // does not work!

will give you a SyntaxError: Unexpected keyword 'return'

Are HTTP headers case-sensitive?

tldr; both HTTP/1.1 and HTTP/2 headers are case-insensitive.

According to RFC 7230 (HTTP/1.1):

Each header field consists of a case-insensitive field name followed by a colon (":"), optional leading whitespace, the field value, and optional trailing whitespace.

https://tools.ietf.org/html/rfc7230#section-3.2

Also, RFC 7540 (HTTP/2):

Just as in HTTP/1.x, header field names are strings of ASCII
characters that are compared in a case-insensitive fashion.

https://tools.ietf.org/html/rfc7540#section-8.1.2

Instantiate and Present a viewController in Swift

I created a library that will handle this much more easier with better syntax:

https://github.com/Jasperav/Storyboardable

Just change Storyboard.swift and let the ViewControllers conform to Storyboardable.

What exactly does Double mean in java?

Double is a wrapper class,

The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double.

In addition, this class provides several methods for converting a double to a String and a String to a double, as well as other constants and methods useful when dealing with a double.

The double data type,

The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

Check each datatype with their ranges : Java's Primitive Data Types.


Important Note : If you'r thinking to use double for precise values, you need to re-think before using it. Java Traps: double

How to convert a full date to a short date in javascript?

var d = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)"); 
document.getElementById("demo").innerHTML = d.toLocaleDateString();

SQL DELETE with JOIN another table for WHERE condition

Due to the locking implementation issues, MySQL does not allow referencing the affected table with DELETE or UPDATE.

You need to make a JOIN here instead:

DELETE  gc.*
FROM    guide_category AS gc 
LEFT JOIN
        guide AS g 
ON      g.id_guide = gc.id_guide
WHERE   g.title IS NULL

or just use a NOT IN:

DELETE  
FROM    guide_category AS gc 
WHERE   id_guide NOT IN
        (
        SELECT  id_guide
        FROM    guide
        )

Resize HTML5 canvas to fit window

CSS

body { margin: 0; } 
canvas { display: block; } 

JavaScript

window.addEventListener("load", function()
{
    var canvas = document.createElement('canvas'); document.body.appendChild(canvas);
    var context = canvas.getContext('2d');

    function draw()
    {
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.beginPath();
        context.moveTo(0, 0); context.lineTo(canvas.width, canvas.height); 
        context.moveTo(canvas.width, 0); context.lineTo(0, canvas.height); 
        context.stroke();
    }
    function resize()
    {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        draw();
    }
    window.addEventListener("resize", resize);
    resize();
});

Getting activity from context in android

I used convert Activity

Activity activity = (Activity) context;

How can I convert a char to int in Java?

The ASCII table is arranged so that the value of the character '9' is nine greater than the value of '0'; the value of the character '8' is eight greater than the value of '0'; and so on.

So you can get the int value of a decimal digit char by subtracting '0'.

char x = '9';
int y = x - '0'; // gives the int value 9

How best to read a File into List<string>

Don't store it if possible. Just read through it if you are memory constrained. You can use a StreamReader:

using (var reader = new StreamReader("file.txt"))
{
    var line = reader.ReadLine();
    // process line here
}

This can be wrapped in a method which yields strings per line read if you want to use LINQ.

'Property does not exist on type 'never'

if you're receiving the error in parameter, so keep any or any[] type of input like below

getOptionLabel={(option: any) => option!.name}
 <Autocomplete
    options={tests}
    getOptionLabel={(option: any) => option!.name}
    ....
  />

OWIN Security - How to Implement OAuth2 Refresh Tokens

I don't think that you should be using an array to maintain tokens. Neither you need a guid as a token.

You can easily use context.SerializeTicket().

See my below code.

public class RefreshTokenProvider : IAuthenticationTokenProvider
{
    public async Task CreateAsync(AuthenticationTokenCreateContext context)
    {
        Create(context);
    }

    public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
    {
        Receive(context);
    }

    public void Create(AuthenticationTokenCreateContext context)
    {
        object inputs;
        context.OwinContext.Environment.TryGetValue("Microsoft.Owin.Form#collection", out inputs);

        var grantType = ((FormCollection)inputs)?.GetValues("grant_type");

        var grant = grantType.FirstOrDefault();

        if (grant == null || grant.Equals("refresh_token")) return;

        context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(Constants.RefreshTokenExpiryInDays);

        context.SetToken(context.SerializeTicket());
    }

    public void Receive(AuthenticationTokenReceiveContext context)
    {
        context.DeserializeTicket(context.Token);

        if (context.Ticket == null)
        {
            context.Response.StatusCode = 400;
            context.Response.ContentType = "application/json";
            context.Response.ReasonPhrase = "invalid token";
            return;
        }

        if (context.Ticket.Properties.ExpiresUtc <= DateTime.UtcNow)
        {
            context.Response.StatusCode = 401;
            context.Response.ContentType = "application/json";
            context.Response.ReasonPhrase = "unauthorized";
            return;
        }

        context.Ticket.Properties.ExpiresUtc = DateTime.UtcNow.AddDays(Constants.RefreshTokenExpiryInDays);
        context.SetTicket(context.Ticket);
    }
}

Equivalent of Clean & build in Android Studio?

Android studio is based on Intellij Idea. In Intellij Idea you have to do the following from the GUI menu.

Build -> Rebuild Project

How do I print out the contents of a vector?

This worked for me:

    for (auto& i : name)
    {
    int r = 0;
    for (int j = 0; j < name[r].size();j++) 
    {
    std::cout << i[j];
    }
    r++;
    std::cout << std::endl;
    }

HttpServletRequest - how to obtain the referring URL?

Actually it's: request.getHeader("Referer"), or even better, and to be 100% sure, request.getHeader(HttpHeaders.REFERER), where HttpHeaders is com.google.common.net.HttpHeaders

What Vim command(s) can be used to quote/unquote words?

Here's some mapping that could help:

:nnoremap <Leader>q" ciw""<Esc>P
:nnoremap <Leader>q' ciw''<Esc>P
:nnoremap <Leader>qd daW"=substitute(@@,"'\\\|\"","","g")<CR>P

If you haven't changed the mapleader variable, then activate the mapping with \q" \q' or \qd. They add double quote around the word under the cursor, single quote around the word under the cursor, delete any quotes around the word under the cursor respectively.

How to read a text file into a list or an array with Python

So you want to create a list of lists... We need to start with an empty list

list_of_lists = []

next, we read the file content, line by line

with open('data') as f:
    for line in f:
        inner_list = [elt.strip() for elt in line.split(',')]
        # in alternative, if you need to use the file content as numbers
        # inner_list = [int(elt.strip()) for elt in line.split(',')]
        list_of_lists.append(inner_list)

A common use case is that of columnar data, but our units of storage are the rows of the file, that we have read one by one, so you may want to transpose your list of lists. This can be done with the following idiom

by_cols = zip(*list_of_lists)

Another common use is to give a name to each column

col_names = ('apples sold', 'pears sold', 'apples revenue', 'pears revenue')
by_names = {}
for i, col_name in enumerate(col_names):
    by_names[col_name] = by_cols[i]

so that you can operate on homogeneous data items

 mean_apple_prices = [money/fruits for money, fruits in
                     zip(by_names['apples revenue'], by_names['apples_sold'])]

Most of what I've written can be speeded up using the csv module, from the standard library. Another third party module is pandas, that lets you automate most aspects of a typical data analysis (but has a number of dependencies).


Update While in Python 2 zip(*list_of_lists) returns a different (transposed) list of lists, in Python 3 the situation has changed and zip(*list_of_lists) returns a zip object that is not subscriptable.

If you need indexed access you can use

by_cols = list(zip(*list_of_lists))

that gives you a list of lists in both versions of Python.

On the other hand, if you don't need indexed access and what you want is just to build a dictionary indexed by column names, a zip object is just fine...

file = open('some_data.csv')
names = get_names(next(file))
columns = zip(*((x.strip() for x in line.split(',')) for line in file)))
d = {}
for name, column in zip(names, columns): d[name] = column

ERROR 1049 (42000): Unknown database

blog_development doesn't exist

You can see this in sql by the 0 rows affected message

create it in mysql with

mysql> create database blog_development

However as you are using rails you should get used to using

$ rake db:create

to do the same task. It will use your database.yml file settings, which should include something like:

development:
  adapter: mysql2
  database: blog_development
  pool: 5

Also become familiar with:

$ rake db:migrate  # Run the database migration
$ rake db:seed     # Run thew seeds file create statements
$ rake db:drop     # Drop the database

How to convert string to Date in Angular2 \ Typescript?

You can use date filter to convert in date and display in specific format.

In .ts file (typescript):

let dateString = '1968-11-16T00:00:00' 
let newDate = new Date(dateString);

In HTML:

{{dateString |  date:'MM/dd/yyyy'}}

Below are some formats which you can implement :

Backend:

public todayDate = new Date();

HTML :

<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>   
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>      
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option> 
</select>

Get all files that have been modified in git branch

I use grep so I only get the lines with diff --git which are the files path:

git diff branchA branchB | grep 'diff --git'
// OUTPUTS ALL FILES WITH CHANGES, SIMPLE HA :)
diff --git a/package-lock.json b/package-lock.json

Shell script current directory?

As already mentioned, the location will be where the script was called from. If you wish to have the script reference it's installed location, it's quite simple. Below is a snippet that will print the PWD and the installed directory:

#!/bin/bash
echo "Script executed from: ${PWD}"

BASEDIR=$(dirname $0)
echo "Script location: ${BASEDIR}"

You're weclome

Convert JSON String to Pretty Print JSON output using Jackson

You can achieve this using bellow ways:

1. Using Jackson from Apache

    String formattedData=new ObjectMapper().writerWithDefaultPrettyPrinter()
.writeValueAsString(YOUR_JSON_OBJECT);

Import bellow class:

import com.fasterxml.jackson.databind.ObjectMapper;

It's gradle dependency is :

compile 'com.fasterxml.jackson.core:jackson-core:2.7.3'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.3'
compile 'com.fasterxml.jackson.core:jackson-databind:2.7.3'

2. Using Gson from Google

String formattedData=new GsonBuilder().setPrettyPrinting()
    .create().toJson(YOUR_OBJECT);

Import bellow class:

import com.google.gson.Gson;

It's gradle is:

compile 'com.google.code.gson:gson:2.8.2'

Here, you can also download correct updated version from repository.

How to default to other directory instead of home directory

Add the line to the .bashrc file in the home directory (create the file if it doesn't exist):

cd ~
touch .bashrc
echo "cd ~/Desktop/repos/" >> .bashrc

How to check that Request.QueryString has a specific value or not in ASP.NET?

What about a more direct approach?

if (Request.QueryString.AllKeys.Contains("mykey")

Reading/Writing a MS Word file in PHP

You can use Antiword, it is a free MS Word reader for Linux and most popular OS.

$document_file = 'c:\file.doc';
$text_from_doc = shell_exec('/usr/local/bin/antiword '.$document_file);

How to execute an action before close metro app WinJS

If I am not mistaken, it will be onunload event.

"Occurs when the application is about to be unloaded." - MSDN

How do we determine the number of days for a given month in python

Just for the sake of academic interest, I did it this way...

(dt.replace(month = dt.month % 12 +1, day = 1)-timedelta(days=1)).day

Total size of the contents of all the files in a directory

stat's "%s" format gives you the actual number of bytes in a file.

 find . -type f |
 xargs stat --format=%s |
 awk '{s+=$1} END {print s}'

Feel free to substitute your favourite method for summing numbers.

What is default list styling (CSS)?

You cannot. Whenever there is any style sheet being applied that assigns a property to an element, there is no way to get to the browser defaults, for any instance of the element.

The (disputable) idea of reset.css is to get rid of browser defaults, so that you can start your own styling from a clean desk. No version of reset.css does that completely, but to the extent they do, the author using reset.css is supposed to completely define the rendering.

How to retrieve an element from a set without removing it?

Two options that don't require copying the whole set:

for e in s:
    break
# e is now an element from s

Or...

e = next(iter(s))

But in general, sets don't support indexing or slicing.

Curl Command to Repeat URL Request

You might be interested in Apache Bench tool which is basically used to do simple load testing.

example :

ab -n 500 -c 20 http://www.example.com/

n = total number of request, c = number of concurrent request

maven-dependency-plugin (goals "copy-dependencies", "unpack") is not supported by m2e

It seems to be a known issue. You can instruct m2e to ignore this.

Option 1: pom.xml

Add the following inside your <build/> tag:

<pluginManagement>
<plugins>
    <!-- Ignore/Execute plugin execution -->
    <plugin>
        <groupId>org.eclipse.m2e</groupId>
        <artifactId>lifecycle-mapping</artifactId>
        <version>1.0.0</version>
        <configuration>
            <lifecycleMappingMetadata>
                <pluginExecutions>
                    <!-- copy-dependency plugin -->
                    <pluginExecution>
                        <pluginExecutionFilter>
                            <groupId>org.apache.maven.plugins</groupId>
                            <artifactId>maven-dependency-plugin</artifactId>
                            <versionRange>[1.0.0,)</versionRange>
                            <goals>
                                <goal>copy-dependencies</goal>
                            </goals>
                        </pluginExecutionFilter>
                        <action>
                            <ignore />
                        </action>
                    </pluginExecution>
                </pluginExecutions>
            </lifecycleMappingMetadata>
        </configuration>
    </plugin>
   </plugins></pluginManagement>

You will need to do Maven... -> Update Project Configuration on your project after this.

Read more: http://wiki.eclipse.org/M2E_plugin_execution_not_covered#m2e_maven_plugin_coverage_status

Option 2: Global Eclipse Override

To avoid changing your POM files, the ignore override can be applied to the whole workspace via Eclipse settings.

Save this file somewhere on the disk: https://gist.github.com/maksimov/8906462

In Eclipse/Preferences/Maven/Lifecycle Mappings browse to this file and click OK:

Eclipse Settings

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

In Apache Derby DB, refrain from using table names as "user" or so because they are reserved keywords on Apache Derby but will work fine on MySql.

In the Query, you must specify the name of the Entity class that you want to fetch the data from in the FROM clause of the Query.

List<User> users=session.createQuery("from User").list();

Here, User is the name of my Java Entity class(Consider the casing of the name as in Java it matters.)

Access Enum value using EL with JSTL

I do it this way when there are many points to use...

public enum Status { 

    VALID("valid"), OLD("old");

    private final String val;

    Status(String val) {
        this.val = val;
    }

    public String getStatus() {
        return val;
    }

    public static void setRequestAttributes(HttpServletRequest request) {
        Map<String,String> vals = new HashMap<String,String>();
        for (Status val : Status.values()) {
            vals.put(val.name(), val.value);
        }
        request.setAttribute("Status", vals);
    }

}

JSP

<%@ page import="...Status" %>
<% Status.setRequestAttributes(request) %>

<c:when test="${dp.status eq Status.VALID}">
...

How to install pandas from pip on windows cmd?

install pip, securely download get-pip.py

Then run the following:

python get-pip.py

On Windows, to get Pandas running,follow the step given in following link

https://github.com/svaksha/PyData-Workshop-Sprint/wiki/windows-install-pandas

Python pip install fails: invalid command egg_info

try the following command:

pip install setuptools==28.8.0

Shell script to copy files from one location to another location and rename add the current date to every file

There is a proper way to split the filename and the extension: Extract filename and extension in Bash

You can apply it like this:

date=$(date +"%m%d%y")
for FILE in folder1/*.csv
do
    bname=$(basename "$FILE")
    extension="${bname##*.}"
    filenamewoext="${bname%.*}"
    newfilename="${filenamewoext}${date}.${extension}
    cp folder1/${FILE} folder2/${newfilename}
done

How to extract request http headers from a request using NodeJS connect

To see a list of HTTP request headers, you can use :

console.log(JSON.stringify(req.headers));

to return a list in JSON format.

{
"host":"localhost:8081",
"connection":"keep-alive",
"cache-control":"max-age=0",
"accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"upgrade-insecure-requests":"1",
"user-agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36",
"accept-encoding":"gzip, deflate, sdch",
"accept-language":"en-US,en;q=0.8,et;q=0.6"
}

Remove trailing newline from the elements of a string list

This can be done using list comprehensions as defined in PEP 202

[w.strip() for w in  ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']]

VB6 IDE cannot load MSCOMCTL.OCX after update KB 2687323

The problem has been resolved by running the following in elevated command prompt:

command :

cd C:\Windows\System32\
regtlib msdatsrc.tlb

or

cd C:\Windows\SysWOW64\
regtlib msdatsrc.tlb

I hope this helps.

Get unique values from arraylist in java

Here's straightforward way without resorting to custom comparators or stuff like that:

Set<String> gasNames = new HashSet<String>();
List<YourRecord> records = ...;

for(YourRecord record : records) {
  gasNames.add(record.getGasName());
}

// now gasNames is a set of unique gas names, which you could operate on:
List<String> sortedGasses = new ArrayList<String>(gasNames);
Collections.sort(sortedGasses);

Note: Using TreeSet instead of HashSet would give directly sorted arraylist and above Collections.sort could be skipped, but TreeSet is otherwise less efficent, so it's often better, and rarely worse, to use HashSet even when sorting is needed.

How to get records randomly from the oracle database?

SAMPLE() is not guaranteed to give you exactly 20 rows, but might be suitable (and may perform significantly better than a full query + sort-by-random for large tables):

SELECT *
FROM   table SAMPLE(20);

Note: the 20 here is an approximate percentage, not the number of rows desired. In this case, since you have 100 rows, to get approximately 20 rows you ask for a 20% sample.

Match at every second occurrence

Use grouping.

foo.*?(foo)