Programs & Examples On #Wse2.0

WSE 2.0 is version 2.0 of the obsolete Web Services Enhancements product from Microsoft. See the WSE tag for more information.

Fixed header table with horizontal scrollbar and vertical scrollbar on

Here's a solution which again is not a CSS only solution. It is similar to avrahamcool's solution in that it uses a few lines of jQuery, but instead of changing heights and moving the header along, all it does is changing the width of tbody based on how far its parent table is scrolled along to the right.

An added bonus with this solution is that it works with a semantically valid HTML table.

It works great on all recent browser versions (IE10, Chrome, FF) and that's it, the scrolling functionality breaks on older versions.

But then the fact that you are using a semantically valid HTML table will save the day and ensure the table is still displayed properly, it's only the scrolling functionality that won't work on older browsers.

Here's a jsFiddle for demonstration purposes.

CSS

table {
    width: 300px;
    overflow-x: scroll;
    display: block;
}
thead, tbody {
    display: block;
}
tbody {
    overflow-y: scroll;
    overflow-x: hidden;
    height: 140px;
}
td, th {
    min-width: 100px;
}

JS

$("table").on("scroll", function () {
    $("table > *").width($("table").width() + $("table").scrollLeft());
});

I needed a version which degrades nicely in IE9 (no scrolling, just a normal table). Posting the fiddle here as it is an improved version. All you need to do is set a height on the tr.

Additional CSS to make this solution degrade nicely in IE9

tr {
    height: 25px; /* This could be any value, it just needs to be set. */ 
}

Here's a jsFiddle demonstrating the nicely degrading in IE9 version of this solution.

Edit: Updated fiddle links to link to a version of the fiddle which contains fixes for issues mentioned in the comments. Just adding a snippet with the latest and greatest version while I'm at it:

_x000D_
_x000D_
$('table').on('scroll', function() {_x000D_
  $("table > *").width($("table").width() + $("table").scrollLeft());_x000D_
});
_x000D_
html {_x000D_
  font-family: verdana;_x000D_
  font-size: 10pt;_x000D_
  line-height: 25px;_x000D_
}_x000D_
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
  width: 300px;_x000D_
  overflow-x: scroll;_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
thead {_x000D_
  background-color: #EFEFEF;_x000D_
}_x000D_
_x000D_
thead,_x000D_
tbody {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
tbody {_x000D_
  overflow-y: scroll;_x000D_
  overflow-x: hidden;_x000D_
  height: 140px;_x000D_
}_x000D_
_x000D_
td,_x000D_
th {_x000D_
  min-width: 100px;_x000D_
  height: 25px;_x000D_
  border: dashed 1px lightblue;_x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
  max-width: 100px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Column 1</th>_x000D_
      <th>Column 2</th>_x000D_
      <th>Column 3</th>_x000D_
      <th>Column 4</th>_x000D_
      <th>Column 5</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>AAAAAAAAAAAAAAAAAAAAAAAAAA</td>_x000D_
      <td>Row 1</td>_x000D_
      <td>Row 1</td>_x000D_
      <td>Row 1</td>_x000D_
      <td>Row 1</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 2</td>_x000D_
      <td>Row 2</td>_x000D_
      <td>Row 2</td>_x000D_
      <td>Row 2</td>_x000D_
      <td>Row 2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 3</td>_x000D_
      <td>Row 3</td>_x000D_
      <td>Row 3</td>_x000D_
      <td>Row 3</td>_x000D_
      <td>Row 3</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 4</td>_x000D_
      <td>Row 4</td>_x000D_
      <td>Row 4</td>_x000D_
      <td>Row 4</td>_x000D_
      <td>Row 4</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 5</td>_x000D_
      <td>Row 5</td>_x000D_
      <td>Row 5</td>_x000D_
      <td>Row 5</td>_x000D_
      <td>Row 5</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 6</td>_x000D_
      <td>Row 6</td>_x000D_
      <td>Row 6</td>_x000D_
      <td>Row 6</td>_x000D_
      <td>Row 6</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 7</td>_x000D_
      <td>Row 7</td>_x000D_
      <td>Row 7</td>_x000D_
      <td>Row 7</td>_x000D_
      <td>Row 7</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 8</td>_x000D_
      <td>Row 8</td>_x000D_
      <td>Row 8</td>_x000D_
      <td>Row 8</td>_x000D_
      <td>Row 8</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 9</td>_x000D_
      <td>Row 9</td>_x000D_
      <td>Row 9</td>_x000D_
      <td>Row 9</td>_x000D_
      <td>Row 9</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 10</td>_x000D_
      <td>Row 10</td>_x000D_
      <td>Row 10</td>_x000D_
      <td>Row 10</td>_x000D_
      <td>Row 10</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Add back button to action bar

if anyone else need the solution

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == android.R.id.home) {
        onBackPressed();
    }

    return super.onOptionsItemSelected(item);
}

select count(*) from table of mysql in php

You can as well use this and upgrade to mysqli_ (stop using mysql_* extension...)

$result = mysqli_query($conn, "SELECT COUNT(*) AS `count` FROM `Students`");
$row = mysqli_fetch_array($result);
$count = $row['count'];
echo $count;

Oracle find a constraint

maybe this can help..

SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = "my_table_name";

React Native - Image Require Module using Dynamic Names

Say if you have an application which has similar functionality as that of mine. Where your app is mostly offline and you want to render the Images one after the other. Then below is the approach that worked for me in React Native version 0.60.

  1. First create a folder named Resources/Images and place all your images there.
  2. Now create a file named Index.js (at Resources/Images) which is responsible for Indexing all the images in the Reources/Images folder.

const Images = { 'image1': require('./1.png'), 'image2': require('./2.png'), 'image3': require('./3.png') }

  1. Now create a Component named ImageView at your choice of folder. One can create functional, class or constant component. I have used Const component. This file is responsible for returning the Image depending on the Index.
import React from 'react';
import { Image, Dimensions } from 'react-native';
import Images from './Index';
const ImageView = ({ index }) => {
    return (
        <Image
            source={Images['image' + index]}
        />
    )
}
export default ImageView;
  1. Now from the component wherever you want to render the Static Images dynamically, just use the ImageView component and pass the index.

    < ImageView index={this.qno + 1} />

I need to convert an int variable to double

I think you should casting variable or use Integer class by call out method doubleValue().

How to construct a relative path in Java from two absolute paths (or URLs)?

Here a method that resolves a relative path from a base path regardless they are in the same or in a different root:

public static String GetRelativePath(String path, String base){

    final String SEP = "/";

    // if base is not a directory -> return empty
    if (!base.endsWith(SEP)){
        return "";
    }

    // check if path is a file -> remove last "/" at the end of the method
    boolean isfile = !path.endsWith(SEP);

    // get URIs and split them by using the separator
    String a = "";
    String b = "";
    try {
        a = new File(base).getCanonicalFile().toURI().getPath();
        b = new File(path).getCanonicalFile().toURI().getPath();
    } catch (IOException e) {
        e.printStackTrace();
    }
    String[] basePaths = a.split(SEP);
    String[] otherPaths = b.split(SEP);

    // check common part
    int n = 0;
    for(; n < basePaths.length && n < otherPaths.length; n ++)
    {
        if( basePaths[n].equals(otherPaths[n]) == false )
            break;
    }

    // compose the new path
    StringBuffer tmp = new StringBuffer("");
    for(int m = n; m < basePaths.length; m ++)
        tmp.append(".."+SEP);
    for(int m = n; m < otherPaths.length; m ++)
    {
        tmp.append(otherPaths[m]);
        tmp.append(SEP);
    }

    // get path string
    String result = tmp.toString();

    // remove last "/" if path is a file
    if (isfile && result.endsWith(SEP)){
        result = result.substring(0,result.length()-1);
    }

    return result;
}

How to get folder path from file path with CMD

In order to assign these to variables, be sure not to add spaces in front or after the equals sign:

set filepath=%~dp1
set filename=%~nx1

Then you should have no issues.

Easiest way to pass an AngularJS scope variable from directive to controller?

Edited on 2014/8/25: Here was where I forked it.

Thanks @anvarik.

Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @

<div ng-controller="MyCtrl">
    <h2>Parent Scope</h2>
    <input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i>    
    <br><br>
    <!-- attribute-foo binds to a DOM attribute which is always
    a string. That is why we are wrapping it in curly braces so
    that it can be interpolated. -->
    <my-component attribute-foo="{{foo}}" binding-foo="foo"
        isolated-expression-foo="updateFoo(newFoo)" >
        <h2>Attribute</h2>
        <div>
            <strong>get:</strong> {{isolatedAttributeFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedAttributeFoo">
            <i>// This does not update the parent scope.</i>
        </div>
        <h2>Binding</h2>
        <div>
            <strong>get:</strong> {{isolatedBindingFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedBindingFoo">
            <i>// This does update the parent scope.</i>
        </div>
        <h2>Expression</h2>    
        <div>
            <input ng-model="isolatedFoo">
            <button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
            <i>// And this calls a function on the parent scope.</i>
        </div>
    </my-component>
</div>
var myModule = angular.module('myModule', [])
    .directive('myComponent', function () {
        return {
            restrict:'E',
            scope:{
                /* NOTE: Normally I would set my attributes and bindings
                to be the same name but I wanted to delineate between
                parent and isolated scope. */                
                isolatedAttributeFoo:'@attributeFoo',
                isolatedBindingFoo:'=bindingFoo',
                isolatedExpressionFoo:'&'
            }        
        };
    })
    .controller('MyCtrl', ['$scope', function ($scope) {
        $scope.foo = 'Hello!';
        $scope.updateFoo = function (newFoo) {
            $scope.foo = newFoo;
        }
    }]);

Which encoding opens CSV files correctly with Excel on both Mac and Windows?

The lowdown is: There is no solution. Excel 2011/Mac cannot correctly interpret a CSV file containing umlauts and diacritical marks no matter what encoding or hoop jumping you do. I'd be glad to hear someone tell me different!

Can't find System.Windows.Media namespace?

You should add reference to PresentationCore.dll.

How do you specify a debugger program in Code::Blocks 12.11?

Click on settings in top tool bar;

Click on debugger;

In tree, highlight "gdb/cdb debugger" by clicking it

Click "create configuration"

Click default configuration, a dialogue will appear to the right for "executable path" with a button to the right.

Click on that button and it will bring up the file that codeblocks is installed in. Just keep clicking until you create the path to the gdb.exe (it sort of finds itself).

Editing the git commit message in GitHub

For intellij users: If you want to make changes in interactive way for past commits, which are not pushed follow below steps in Intellij:

  • Select Version Control
  • Select Log
  • Right click the commit for which you want to amend comment
  • Click reword
  • Done

Hope it helps

How to read file contents into a variable in a batch file?

just do:

type version.txt

and it will be displayed as if you typed:

set /p Build=<version.txt
echo %Build%

How to connect to a MySQL Data Source in Visual Studio

This seems to be a common problem. I had to uninstall the latest Connector/NET driver (6.7.4) and install an older version (6.6.5) for it to work. Others report 6.6.6 working for them.

See other topic with more info: MySQL Data Source not appearing in Visual Studio

How to instantiate a javascript class in another js file?

// Create Customer class as follows:
export default class Customer {}

// Import the class 
// no need for .js extension in path cos gets inferred automatically
import Customer from './path/to/Customer'; 
// or
const Customer = require('./path/to/Customer') 

// Use the class
var customer = new Customer();
var name = customer.getName();

Pandas merge two dataframes with different columns

I had this problem today using any of concat, append or merge, and I got around it by adding a helper column sequentially numbered and then doing an outer join

helper=1
for i in df1.index:
    df1.loc[i,'helper']=helper
    helper=helper+1
for i in df2.index:
    df2.loc[i,'helper']=helper
    helper=helper+1
df1.merge(df2,on='helper',how='outer')

Date query with ISODate in mongodb doesn't seem to work

This worked for me while searching for value less than or equal than now:

db.collectionName.find({ "dt": { "$lte" : new Date() + "" } });

Python decorators in classes

The simple way to do it. All you need is to put the decorator method outside the class. You can still use it inside.

def my_decorator(func):
    #this is the key line. There's the aditional self parameter
    def wrap(self, *params, **kwargs):
        # you can use self here as if you were inside the class
        return func()
    return wrap

class Test(object):
    @my_decorator
    def bar(self):
        pass

R numbers from 1 to 100

Your mistake is looking for range, which gives you the range of a vector, for example:

range(c(10, -5, 100))

gives

 -5 100

Instead, look at the : operator to give sequences (with a step size of one):

1:100

or you can use the seq function to have a bit more control. For example,

##Step size of 2
seq(1, 100, by=2)

or

##length.out: desired length of the sequence
seq(1, 100, length.out=5)

Request redirect to /Account/Login?ReturnUrl=%2f since MVC 3 install on server

I solved the problem by adding the following lines to the AppSettings section of my web.config file:

<add key="autoFormsAuthentication" value="false" />
<add key="enableSimpleMembership" value="false"/>

How can I create numbered map markers in Google Maps V3?

My two cents showing how to use the Google Charts API to solve this problem.

Exception 'open failed: EACCES (Permission denied)' on Android

Google has a new feature on Android Q: filtered view for external storage. A quick fix for that is to add this code in the AndroidManifest.xml file:

<manifest ... >
    <!-- This attribute is "false" by default on apps targeting Android Q. -->
    <application android:requestLegacyExternalStorage="true" ... >
     ...
    </application>
</manifest>

You can read more about it here: https://developer.android.com/training/data-storage/compatibility

Why is sed not recognizing \t as a tab?

I used this on Mac:

sed -i '' $'$i\\\n\\\thello\n' filename

Used this link for reference

Count immediate child div elements using jQuery

In response to mrCoders answer using jsperf why not just use the dom node ?

var $foo = $('#foo');
var count = $foo[0].childElementCount

You can try the test here: http://jsperf.com/jquery-child-ele-size/7

This method gets 46,095 op/s while the other methods at best 2000 op/s

Writing an Excel file in EPPlus

Have you looked at the samples provided with EPPlus?

This one shows you how to create a file http://epplus.codeplex.com/wikipage?title=ContentSheetExample

This one shows you how to use it to stream back a file http://epplus.codeplex.com/wikipage?title=WebapplicationExample

This is how we use the package to generate a file.

var newFile = new FileInfo(ExportFileName);
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{                       
    // do work here                            
    xlPackage.Save();
}

Range with step of type float

This is what I would use:

numbers = [float(x)/10 for x in range(10)]

rather than:

numbers = [x*0.1 for x in range(10)]
that would return :
[0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9]

hope it helps.

PostgreSQL: days/months/years between two dates

I spent some time looking for the best answer, and I think I have it.

This sql will give you the number of days between two dates as integer:

SELECT
    (EXTRACT(epoch from age('2017-6-15', now())) / 86400)::int

..which, when run today (2017-3-28), provides me with:

?column?
------------
77

The misconception about the accepted answer:

select age('2010-04-01', '2012-03-05'),
   date_part('year',age('2010-04-01', '2012-03-05')),
   date_part('month',age('2010-04-01', '2012-03-05')),
   date_part('day',age('2010-04-01', '2012-03-05'));

..is that you will get the literal difference between the parts of the date strings, not the amount of time between the two dates.

I.E:

Age(interval)=-1 years -11 mons -4 days;

Years(double precision)=-1;

Months(double precision)=-11;

Days(double precision)=-4;

Difference between arguments and parameters in Java

In java, there are two types of parameters, implicit parameters and explicit parameters. Explicit parameters are the arguments passed into a method. The implicit parameter of a method is the instance that the method is called from. Arguments are simply one of the two types of parameters.

Loop through all the rows of a temp table and call a stored procedure for each row

You always don't need a cursor for this. You can do it with a while loop. You should avoid cursors whenever possible. While loop is faster than cursors.

How to remove all ListBox items?

I think it would be better to actually bind your listBoxes to a datasource, since it looks like you are adding the same elements to each listbox. A simple example would be something like this:

    private List<String> _weight = new List<string>() { "kilogram", "pound" };
    private List<String> _height = new List<string>() { "foot", "inch", "meter" };

    public Window1()
    {            
        InitializeComponent();
    }        

    private void Weight_Click(object sender, RoutedEventArgs e)
    {
        listBox1.ItemsSource = _weight;
        listBox2.ItemsSource = _weight;
    }

    private void Height_Click(object sender, RoutedEventArgs e)
    {
        listBox1.ItemsSource = _height;
        listBox2.ItemsSource = _height;
    }

Get a list of dates between two dates using a function

All you have to do is just change the hard coded value in the code provided below

DECLARE @firstDate datetime
    DECLARE @secondDate datetime
    DECLARE @totalDays  INT
    SELECT @firstDate = getDate() - 30
    SELECT @secondDate = getDate()

    DECLARE @index INT
    SELECT @index = 0
    SELECT @totalDays = datediff(day, @firstDate, @secondDate)

    CREATE TABLE #temp
    (
         ID INT NOT NULL IDENTITY(1,1)
        ,CommonDate DATETIME NULL
    )

    WHILE @index < @totalDays
        BEGIN

            INSERT INTO #temp (CommonDate) VALUES  (DATEADD(Day, @index, @firstDate))   
            SELECT @index = @index + 1
        END

    SELECT CONVERT(VARCHAR(10), CommonDate, 102) as [Date Between] FROM #temp

    DROP TABLE #temp

How to draw a custom UIView that is just a circle - iPhone app

Here is another way by using UIBezierPath (maybe it's too late ^^) Create a circle and mask UIView with it, as follows:

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
view.backgroundColor = [UIColor blueColor];

CAShapeLayer *shape = [CAShapeLayer layer];
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:view.center radius:(view.bounds.size.width / 2) startAngle:0 endAngle:(2 * M_PI) clockwise:YES];
shape.path = path.CGPath;
view.layer.mask = shape;

What does enctype='multipart/form-data' mean?

  • enctype(ENCode TYPE) attribute specifies how the form-data should be encoded when submitting it to the server.
  • multipart/form-data is one of the value of enctype attribute, which is used in form element that have a file upload. multi-part means form data divides into multiple parts and send to server.

pass parameter by link_to ruby on rails

Try:

<%= link_to "Add to cart", {:controller => "car", :action => "add_to_cart", :car => car.id }%>

and then in your controller

@car = Car.find(params[:car])

which, will find in your 'cars' table (as with rails pluralization) in your DB a car with id == to car.id

hope it helps! happy coding

more than a year later, but if you see it or anyone does, i could use the points ;D

Bootstrap 3 - Responsive mp4-video

This worked for me:

<video src="file.mp4" controls style="max-width:100%; height:auto"></video>

How can I install the Beautiful Soup module on the Mac?

On advice from http://for-ref-only.blogspot.de/2012/08/installing-beautifulsoup-for-python-3.html, I used the Windows command prompt with:

C:\Python\Scripts\easy_install c:\Python\BeautifulSoup\beautifulsoup4-4.3.1

where BeautifulSoup\beautifulsoup4-4.3.1 is the downloaded and extracted beautifulsoup4-4.3.1.tar file. It works.

How do I copy to the clipboard in JavaScript?

I use this very successfully (without jQuery or any other framework).

function copyToClp(txt){
    txt = document.createTextNode(txt);
    var m = document;
    var w = window;
    var b = m.body;
    b.appendChild(txt);
    if (b.createTextRange) {
        var d = b.createTextRange();
        d.moveToElementText(txt);
        d.select();
        m.execCommand('copy');
    } 
    else {
        var d = m.createRange();
        var g = w.getSelection;
        d.selectNodeContents(txt);
        g().removeAllRanges();
        g().addRange(d);
        m.execCommand('copy');
        g().removeAllRanges();
    }
    txt.remove();
}

Warning

Tabs are converted to spaces (at least in Chrome).

VirtualBox error "Failed to open a session for the virtual machine"

Normally this error occurs when it try to load the previous state. This happened in Mac Virtual box. I tried after restarting the virtual box but again also i've encountered this issue. Right Click on the operating system in the virtual box and then Click on the Discard Saved State.. .This fixed the issue.

React-Native: Application has not been registered error

This solved it for me

AppRegistry.registerComponent('main', () => App);

So my index.js file

import { AppRegistry } from 'react-native';
import App from './App';
AppRegistry.registerComponent('main', () => App);

And my package.json file:

"dependencies": {
    "react": "^16.13.1",
    "react-dom": "~16.9.0",
    "react-native": "~0.61.5"
},

How to horizontally center an element

With Sass (SCSS syntax) you can do this with a mixin:

With translate

// Center horizontal mixin
@mixin center-horizontally {
  position: absolute;
  left: 50%;
  transform: translate(-50%, -50%);
}

// Center horizontal class
.center-horizontally {
    @include center-horizontally;
}

In an HTML tag:

<div class="center-horizontally">
    I'm centered!
</div>

Remember to add position: relative; to the parent HTML element.


With Flexbox

Using flex, you can do this:

@mixin center-horizontally {
  display: flex;
  justify-content: center;
}

// Center horizontal class
.center-horizontally {
    @include center-horizontally;
}

In an HTML tag:

<div class="center-horizontally">
    <div>I'm centered!</div>
</div>

Try this CodePen!

How do I point Crystal Reports at a new database

Choose Database | Set Datasource Location... Select the database node (yellow-ish cylinder) of the current connection, then select the database node of the desired connection (you may need to authenticate), then click Update.

You will need to do this for the 'Subreports' nodes as well.

FYI, you can also do individual tables by selecting each individually, then choosing Update.

Concatenating variables in Bash

Try doing this, there's no special character to concatenate in bash :

mystring="${arg1}12${arg2}endoffile"

explanations

If you don't put brackets, you will ask to concatenate $arg112 + $argendoffile (I guess that's not what you asked) like in the following example :

mystring="$arg112$arg2endoffile"

The brackets are delimiters for the variables when needed. When not needed, you can use it or not.

another solution

(less portable : require bash > 3.1)

$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile

See http://mywiki.wooledge.org/BashFAQ/013

How to download/upload files from/to SharePoint 2013 using CSOM?

Private Sub DownloadFile(relativeUrl As String, destinationPath As String, name As String)
    Try
        destinationPath = Replace(destinationPath + "\" + name, "\\", "\")
        Dim fi As FileInformation = Microsoft.SharePoint.Client.File.OpenBinaryDirect(Me.context, relativeUrl)
        Dim down As Stream = System.IO.File.Create(destinationPath)
        Dim a As Integer = fi.Stream.ReadByte()
        While a <> -1
            down.WriteByte(CType(a, Byte))
            a = fi.Stream.ReadByte()
        End While
    Catch ex As Exception
        ToLog(Type.ERROR, ex.Message)
    End Try
End Sub

How do write IF ELSE statement in a MySQL query

You probably want to use a CASE expression.

They look like this:

SELECT col1, col2, (case when (action = 2 and state = 0) 
 THEN
      1 
 ELSE
      0 
 END)
 as state from tbl1;

Today`s date in an excel macro

Try the Date function. It will give you today's date in a MM/DD/YYYY format. If you're looking for today's date in the MM-DD-YYYY format try Date$. Now() also includes the current time (which you might not need). It all depends on what you need. :)

How to move up a directory with Terminal in OS X

To move up a directory, the quickest way would be to add an alias to ~/.bash_profile

alias ..='cd ..'

and then one would need only to type '..[return]'.

How do I print my Java object without getting "SomeType@2f92e0f4"?

I think apache provides a better util class which provides a function to get the string

ReflectionToStringBuilder.toString(object)

Mongoose: Get full list of users

Well, if you really want to return a mapping from _id to user, you could always do:

server.get('/usersList', function(req, res) {
  User.find({}, function(err, users) {
    var userMap = {};

    users.forEach(function(user) {
      userMap[user._id] = user;
    });

    res.send(userMap);  
  });
});

find() returns all matching documents in an array, so your last code snipped sends that array to the client.

CodeIgniter removing index.php from url

Step 1 :

Add this in htaccess file

<IfModule mod_rewrite.c>
  RewriteEngine On
  #RewriteBase /

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^ index.php [QSA,L]
</IfModule>

Step 2 :

Remove index.php in codeigniter config

$config['base_url'] = ''; 
$config['index_page'] = '';

Step 3 :

Allow overriding htaccess in Apache Configuration (Command)

sudo nano /etc/apache2/apache2.conf

and edit the file & change to

AllowOverride All

for www folder

Step 4 :

Enabled apache mod rewrite (Command)

sudo a2enmod rewrite

Step 5 :

Restart Apache (Command)

sudo /etc/init.d/apache2 restart

How can we draw a vertical line in the webpage?

You can use <hr> for a vertical line as well.
Set the width to 1 and the size(height) as long as you want.
I used 500 in my example(demo):

With <hr width="1" size="500">

DEMO

Solution to INSTALL_FAILED_INSUFFICIENT_STORAGE error on Android

I ended up uninstalling the app from the device and then re-installing it back in Eclipse. This is a problem I get all the time on my device from regular use, but today I got that message from development.

Custom CSS Scrollbar for Firefox

Firefox 64 adds support for the spec draft CSS Scrollbars Module Level 1, which adds two new properties of scrollbar-width and scrollbar-color which give some control over how scrollbars are displayed.

You can set scrollbar-color to one of the following values (descriptions from MDN):

  • auto Default platform rendering for the track portion of the scrollbar, in the absence of any other related scrollbar color properties.
  • dark Show a dark scrollbar, which can be either a dark variant of scrollbar provided by the platform, or a custom scrollbar with dark colors.
  • light Show a light scrollbar, which can be either a light variant of scrollbar provided by the platform, or a custom scrollbar with light colors.
  • <color> <color> Applies the first color to the scrollbar thumb, the second to the scrollbar track.

Note that dark and light values are not currently implemented in Firefox.

macOS notes:

The auto-hiding semi-transparent scrollbars that are the macOS default cannot be colored with this rule (they still choose their own contrasting color based on the background). Only the permanently showing scrollbars (System Preferences > Show Scroll Bars > Always) are colored.

Visual Demo:

_x000D_
_x000D_
.scroll {_x000D_
  width: 20%;_x000D_
  height: 100px;_x000D_
  border: 1px solid grey;_x000D_
  overflow: scroll;_x000D_
  display: inline-block;_x000D_
}_x000D_
.scroll-color-auto {_x000D_
  scrollbar-color: auto;_x000D_
}_x000D_
.scroll-color-dark {_x000D_
  scrollbar-color: dark;_x000D_
}_x000D_
.scroll-color-light {_x000D_
  scrollbar-color: light;_x000D_
}_x000D_
.scroll-color-colors {_x000D_
  scrollbar-color: orange lightyellow;_x000D_
}
_x000D_
<div class="scroll scroll-color-auto">_x000D_
<p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-color-dark">_x000D_
<p>dark</p><p>dark</p><p>dark</p><p>dark</p><p>dark</p><p>dark</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-color-light">_x000D_
<p>light</p><p>light</p><p>light</p><p>light</p><p>light</p><p>light</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-color-colors">_x000D_
<p>colors</p><p>colors</p><p>colors</p><p>colors</p><p>colors</p><p>colors</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can set scrollbar-width to one of the following values (descriptions from MDN):

  • auto The default scrollbar width for the platform.
  • thin A thin scrollbar width variant on platforms that provide that option, or a thinner scrollbar than the default platform scrollbar width.
  • none No scrollbar shown, however the element will still be scrollable.

You can also set a specific length value, according to the spec. Both thin and a specific length may not do anything on all platforms, and what exactly it does is platform-specific. In particular, Firefox doesn't appear to be currently support a specific length value (this comment on their bug tracker seems to confirm this). The thin keywork does appear to be well-supported however, with macOS and Windows support at-least.

It's probably worth noting that the length value option and the entire scrollbar-width property are being considered for removal in a future draft, and if that happens this particular property may be removed from Firefox in a future version.

Visual Demo:

_x000D_
_x000D_
.scroll {_x000D_
  width: 30%;_x000D_
  height: 100px;_x000D_
  border: 1px solid grey;_x000D_
  overflow: scroll;_x000D_
  display: inline-block;_x000D_
}_x000D_
.scroll-width-auto {_x000D_
  scrollbar-width: auto;_x000D_
}_x000D_
.scroll-width-thin {_x000D_
  scrollbar-width: thin;_x000D_
}_x000D_
.scroll-width-none {_x000D_
  scrollbar-width: none;_x000D_
}
_x000D_
<div class="scroll scroll-width-auto">_x000D_
<p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-width-thin">_x000D_
<p>thin</p><p>thin</p><p>thin</p><p>thin</p><p>thin</p><p>thin</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-width-none">_x000D_
<p>none</p><p>none</p><p>none</p><p>none</p><p>none</p><p>none</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Spring .properties file: get element as an Array

Here is an example of how you can do it in Spring 4.0+

application.properties content:

some.key=yes,no,cancel

Java Code:

@Autowire
private Environment env;

...

String[] springRocks = env.getProperty("some.key", String[].class);

Modifying CSS class property values on the fly with JavaScript / jQuery

The way to dynamically modify a CSS property value in a CSS class is by using a CSS variable in the CSS class property value, and then use JavaScript and the DOM to change the CSS variable. The end result is that the styling on the device screen will immediately change when the code runs that sets the new CSS variable value. So, code changes the CSS variable, and the CSS variable is used in the CSS class setting. Note that a CSS class name and a JavaScript Class are two different things.

  • Use a CSS Variable
  • Put the CSS variable where the static CSS class property value would normally be
  • Use code to set a new CSS variable value
  • The change to the CSS variable changes the CSS class property value and that causes the styling on the device screen to change

CSS - Styling

<style>
  :root { /* Set CSS variable values - These values can be changed with JavaScript 
    and DOM */
  --myCSS_ValueOne: initialValue;

  }

  .classNameHere {
    property_Name_Here: var(--myCSS_ValueOne);/* This CSS property gets its value from
    the CSS variable */

  }

</style>

JavaScript and DOM

<script>
  var r = document.querySelector(':root');//Get global root element

  function setA_NewCSS_VariableValue() {
    r.style.setProperty('--myCSS_ValueOne', 'the_New_Value');// Set a new CSS variable
      //value which immediately changes the CSS class setting because the CSS
      //property setting uses a CSS Variable -
  }
</script>

It is also possible to run a function in response to media queries (changes in the device viewport - like width of the device screen) using the matchMedia() method.

var x = window.matchMedia("(max-width: 300px)")
x.addListener(setA_NewCSS_VariableValue) // create a listener function that runs
//when the viewport is less than, or equal to, 300 pixels wide.

CocoaPods Errors on Project Build

In my case I did put Podfile.lock & Manifest.lock in source control, but I forgot to add Pods-Project.debug(release).xcconfig files to source control (by mistakenly adding *.xcconfig to .gitignore), then I got the same compile errors with exactly the same reason, PODS_ROOT is not being set.

So if the goal is that after cloning the repo, the project can immediately build and run, without having CocoaPods installed on the machine, you either add entire Pods directory in source control or add Podfile.lock, Manifest.lock, project's xcconfig files and Pods xcconfig files to source control.

I didn't put the private .xcconfig that merges the build settings with the default CocoaPods configuration to source control.

How can I solve the error LNK2019: unresolved external symbol - function?

In my case, set the cpp file to "C/C++ compiler" in "property"->"general", resolve the LNK2019 error.

6 digits regular expression

You could try

^[0-9]{1,6}$

it should work.

Changing MongoDB data store directory

Resolved it in 2 minutes downtime :)
Just move your folder, add symlink, then tune permissions.

sudo service mongod stop
sudo mv mongodb /new/disk/mongodb/
sudo ln -s /new/disk/mongodb/ /var/lib/mongodb
sudo chown mongodb:mongodb /new/disk/mongodb/
sudo service mongod start

# test if mongodb user can access new location:
sudo -u mongodb -s cd /new/disk/mongodb/
# resolve other permissions issues if necessary
sudo usermod -a -G <newdisk_grp> mongodb

Multiple HttpPost method in Web API controller

You can use this approach :

public class VTRoutingController : ApiController
{
    [HttpPost("Route")]
    public MyResult Route(MyRequestTemplate routingRequestTemplate)
    {
        return null;
    }

    [HttpPost("TSPRoute")]
    public MyResult TSPRoute(MyRequestTemplate routingRequestTemplate)
    {
        return null;
    }
}

Linq to Entities join vs groupjoin

Behaviour

Suppose you have two lists:

Id  Value
1   A
2   B
3   C

Id  ChildValue
1   a1
1   a2
1   a3
2   b1
2   b2

When you Join the two lists on the Id field the result will be:

Value ChildValue
A     a1
A     a2
A     a3
B     b1
B     b2

When you GroupJoin the two lists on the Id field the result will be:

Value  ChildValues
A      [a1, a2, a3]
B      [b1, b2]
C      []

So Join produces a flat (tabular) result of parent and child values.
GroupJoin produces a list of entries in the first list, each with a group of joined entries in the second list.

That's why Join is the equivalent of INNER JOIN in SQL: there are no entries for C. While GroupJoin is the equivalent of OUTER JOIN: C is in the result set, but with an empty list of related entries (in an SQL result set there would be a row C - null).

Syntax

So let the two lists be IEnumerable<Parent> and IEnumerable<Child> respectively. (In case of Linq to Entities: IQueryable<T>).

Join syntax would be

from p in Parent
join c in Child on p.Id equals c.Id
select new { p.Value, c.ChildValue }

returning an IEnumerable<X> where X is an anonymous type with two properties, Value and ChildValue. This query syntax uses the Join method under the hood.

GroupJoin syntax would be

from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }

returning an IEnumerable<Y> where Y is an anonymous type consisting of one property of type Parent and a property of type IEnumerable<Child>. This query syntax uses the GroupJoin method under the hood.

We could just do select g in the latter query, which would select an IEnumerable<IEnumerable<Child>>, say a list of lists. In many cases the select with the parent included is more useful.

Some use cases

1. Producing a flat outer join.

As said, the statement ...

from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }

... produces a list of parents with child groups. This can be turned into a flat list of parent-child pairs by two small additions:

from p in parents
join c in children on p.Id equals c.Id into g // <= into
from c in g.DefaultIfEmpty()               // <= flattens the groups
select new { Parent = p.Value, Child = c?.ChildValue }

The result is similar to

Value Child
A     a1
A     a2
A     a3
B     b1
B     b2
C     (null)

Note that the range variable c is reused in the above statement. Doing this, any join statement can simply be converted to an outer join by adding the equivalent of into g from c in g.DefaultIfEmpty() to an existing join statement.

This is where query (or comprehensive) syntax shines. Method (or fluent) syntax shows what really happens, but it's hard to write:

parents.GroupJoin(children, p => p.Id, c => c.Id, (p, c) => new { p, c })
       .SelectMany(x => x.c.DefaultIfEmpty(), (x,c) => new { x.p.Value, c?.ChildValue } )

So a flat outer join in LINQ is a GroupJoin, flattened by SelectMany.

2. Preserving order

Suppose the list of parents is a bit longer. Some UI produces a list of selected parents as Id values in a fixed order. Let's use:

var ids = new[] { 3,7,2,4 };

Now the selected parents must be filtered from the parents list in this exact order.

If we do ...

var result = parents.Where(p => ids.Contains(p.Id));

... the order of parents will determine the result. If the parents are ordered by Id, the result will be parents 2, 3, 4, 7. Not good. However, we can also use join to filter the list. And by using ids as first list, the order will be preserved:

from id in ids
join p in parents on id equals p.Id
select p

The result is parents 3, 7, 2, 4.

Token based authentication in Web API without any user interface

I think there is some confusion about the difference between MVC and Web Api. In short, for MVC you can use a login form and create a session using cookies. For Web Api there is no session. That's why you want to use the token.

You do not need a login form. The Token endpoint is all you need. Like Win described you'll send the credentials to the token endpoint where it is handled.

Here's some client side C# code to get a token:

    //using System;
    //using System.Collections.Generic;
    //using System.Net;
    //using System.Net.Http;
    //string token = GetToken("https://localhost:<port>/", userName, password);

    static string GetToken(string url, string userName, string password) {
        var pairs = new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>( "grant_type", "password" ), 
                        new KeyValuePair<string, string>( "username", userName ), 
                        new KeyValuePair<string, string> ( "Password", password )
                    };
        var content = new FormUrlEncodedContent(pairs);
        ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        using (var client = new HttpClient()) {
            var response = client.PostAsync(url + "Token", content).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }

In order to use the token add it to the header of the request:

    //using System;
    //using System.Collections.Generic;
    //using System.Net;
    //using System.Net.Http;
    //var result = CallApi("https://localhost:<port>/something", token);

    static string CallApi(string url, string token) {
        ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
        using (var client = new HttpClient()) {
            if (!string.IsNullOrWhiteSpace(token)) {
                var t = JsonConvert.DeserializeObject<Token>(token);

                client.DefaultRequestHeaders.Clear();
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + t.access_token);
            }
            var response = client.GetAsync(url).Result;
            return response.Content.ReadAsStringAsync().Result;
        }
    }

Where Token is:

//using Newtonsoft.Json;

class Token
{
    public string access_token { get; set; }
    public string token_type { get; set; }
    public int expires_in { get; set; }
    public string userName { get; set; }
    [JsonProperty(".issued")]
    public string issued { get; set; }
    [JsonProperty(".expires")]
    public string expires { get; set; }
}

Now for the server side:

In Startup.Auth.cs

        var oAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider("self"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            // https
            AllowInsecureHttp = false
        };
        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(oAuthOptions);

And in ApplicationOAuthProvider.cs the code that actually grants or denies access:

//using Microsoft.AspNet.Identity.Owin;
//using Microsoft.Owin.Security;
//using Microsoft.Owin.Security.OAuth;
//using System;
//using System.Collections.Generic;
//using System.Security.Claims;
//using System.Threading.Tasks;

public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
    private readonly string _publicClientId;

    public ApplicationOAuthProvider(string publicClientId)
    {
        if (publicClientId == null)
            throw new ArgumentNullException("publicClientId");

        _publicClientId = publicClientId;
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

        var user = await userManager.FindAsync(context.UserName, context.Password);
        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
            return;
        }

        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager);
        var propertyDictionary = new Dictionary<string, string> { { "userName", user.UserName } };
        var properties = new AuthenticationProperties(propertyDictionary);

        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
        // Token is validated.
        context.Validated(ticket);
    }

    public override Task TokenEndpoint(OAuthTokenEndpointContext context)
    {
        foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
        {
            context.AdditionalResponseParameters.Add(property.Key, property.Value);
        }
        return Task.FromResult<object>(null);
    }

    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        // Resource owner password credentials does not provide a client ID.
        if (context.ClientId == null)
            context.Validated();

        return Task.FromResult<object>(null);
    }

    public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
    {
        if (context.ClientId == _publicClientId)
        {
            var expectedRootUri = new Uri(context.Request.Uri, "/");

            if (expectedRootUri.AbsoluteUri == context.RedirectUri)
                context.Validated();
        }
        return Task.FromResult<object>(null);
    }

}

As you can see there is no controller involved in retrieving the token. In fact, you can remove all MVC references if you want a Web Api only. I have simplified the server side code to make it more readable. You can add code to upgrade the security.

Make sure you use SSL only. Implement the RequireHttpsAttribute to force this.

You can use the Authorize / AllowAnonymous attributes to secure your Web Api. Additionally you can add filters (like RequireHttpsAttribute) to make your Web Api more secure. I hope this helps.

Error checking for NULL in VBScript

I see lots of confusion in the comments. Null, IsNull() and vbNull are mainly used for database handling and normally not used in VBScript. If it is not explicitly stated in the documentation of the calling object/data, do not use it.

To test if a variable is uninitialized, use IsEmpty(). To test if a variable is uninitialized or contains "", test on "" or Empty. To test if a variable is an object, use IsObject and to see if this object has no reference test on Is Nothing.

In your case, you first want to test if the variable is an object, and then see if that variable is Nothing, because if it isn't an object, you get the "Object Required" error when you test on Nothing.

snippet to mix and match in your code:

If IsObject(provider) Then
    If Not provider Is Nothing Then
        ' Code to handle a NOT empty object / valid reference
    Else
        ' Code to handle an empty object / null reference
    End If
Else
    If IsEmpty(provider) Then
        ' Code to handle a not initialized variable or a variable explicitly set to empty
    ElseIf provider = "" Then
        ' Code to handle an empty variable (but initialized and set to "")
    Else
        ' Code to handle handle a filled variable
    End If
End If

How to set the color of an icon in Angular Material?

Or simply

add to your element

[ngStyle]="{'color': myVariableColor}"

eg

<mat-icon [ngStyle]="{'color': myVariableColor}">{{ getActivityIcon() }}</mat-icon>

Where color can be defined at another component etc

How do I download a file using VBA (without Internet Explorer)

This solution is based from this website: http://social.msdn.microsoft.com/Forums/en-US/bd0ee306-7bb5-4ce4-8341-edd9475f84ad/excel-2007-use-vba-to-download-save-csv-from-url

It is slightly modified to overwrite existing file and to pass along login credentials.

Sub DownloadFile()

Dim myURL As String
myURL = "https://YourWebSite.com/?your_query_parameters"

Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False, "username", "password"
WinHttpReq.send

If WinHttpReq.Status = 200 Then
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write WinHttpReq.responseBody
    oStream.SaveToFile "C:\file.csv", 2 ' 1 = no overwrite, 2 = overwrite
    oStream.Close
End If

End Sub

AngularJS + JQuery : How to get dynamic content working in angularjs

Addition to @jwize's answer

Because angular.element(document).injector() was giving error injector is not defined So, I have created function that you can run after AJAX call or when DOM is changed using jQuery.

  function compileAngularElement( elSelector) {

        var elSelector = (typeof elSelector == 'string') ? elSelector : null ;  
            // The new element to be added
        if (elSelector != null ) {
            var $div = $( elSelector );

                // The parent of the new element
                var $target = $("[ng-app]");

              angular.element($target).injector().invoke(['$compile', function ($compile) {
                        var $scope = angular.element($target).scope();
                        $compile($div)($scope);
                        // Finally, refresh the watch expressions in the new element
                        $scope.$apply();
                    }]);
            }

        }

use it by passing just new element's selector. like this

compileAngularElement( '.user' ) ; 

Difference between a class and a module

namespace: modules are namespaces...which don't exist in java ;)

I also switched from Java and python to Ruby, I remember had exactly this same question...

So the simplest answer is that module is a namespace, which doesn't exist in Java. In java the closest mindset to namespace is a package.

So a module in ruby is like what in java:
class? No
interface? No
abstract class? No
package? Yes (maybe)

static methods inside classes in java: same as methods inside modules in ruby

In java the minimum unit is a class, you can't have a function outside of a class. However in ruby this is possible (like python).

So what goes into a module?
classes, methods, constants. Module protects them under that namespace.

No instance: modules can't be used to create instances

Mixed ins: sometimes inheritance models are not good for classes, but in terms of functionality want to group a set of classes/ methods/ constants together

Rules about modules in ruby:
- Module names are UpperCamelCase
- constants within modules are ALL CAPS (this rule is the same for all ruby constants, not specific to modules)
- access methods: use . operator
- access constants: use :: symbol

simple example of a module:

module MySampleModule
  CONST1 = "some constant"

  def self.method_one(arg1)
    arg1 + 2
  end
end

how to use methods inside a module:

puts MySampleModule.method_one(1) # prints: 3

how to use constants of a module:

puts MySampleModule::CONST1 # prints: some constant

Some other conventions about modules:
Use one module in a file (like ruby classes, one class per ruby file)

UILabel - Wordwrap text

If you set numberOfLines to 0 (and the label to word wrap), the label will automatically wrap and use as many of lines as needed.

If you're editing a UILabel in IB, you can enter multiple lines of text by pressing option+return to get a line break - return alone will finish editing.

HTTP Status 404 - The requested resource (/) is not available

Sometimes cleaning the server works. It worked for me many times.This is only applicable if the program worked earlier but suddenly it stops working.
Steps:
" Right click on Tomcat Server -> Clean. Then restart the server."

ASP.NET DateTime Picker

Basic Date Picker Lite

This is the free version of their flagship product, but it contains a date and time picker native for asp.net.

How do you remove Subversion control for a folder?

For those using NetBeans with SVN, there is an option 'Subversion > Export'.

Backbone.js fetch with parameters

You can also set processData to true:

collection.fetch({ 
    data: { page: 1 },
    processData: true
});

Jquery will auto process data object into param string,

but in Backbone.sync function, Backbone turn the processData off because Backbone will use other method to process data in POST,UPDATE...

in Backbone source:

if (params.type !== 'GET' && !Backbone.emulateJSON) {
    params.processData = false;
}

Show a div with Fancybox

You could use:

$('#btnForm').click(function(){
    $.fancybox({
            'content' : $("#divForm").html()
        });
};

Use of contains in Java ArrayList<String>

Yes, that should work for Strings, but if you are worried about duplicates use a Set. This collection prevents duplicates without you having to do anything. A HashSet is OK to use, but it is unordered so if you want to preserve insertion order you use a LinkedHashSet.

What are Maven goals and phases and what is their difference?

I believe a good answer is already provided, but I would like to add an easy-to-follow diagram of the different 3 life-cycles (build, clean, and site) and the phases in each.

enter image description here

The phases in bold - are the main phases commonly used.

Java 8 Streams FlatMap method example

Given this:

  public class SalesTerritory
    {
        private String territoryName;
        private Set<String> geographicExtents;

        public SalesTerritory( String territoryName, Set<String> zipCodes )
        {
            this.territoryName = territoryName;
            this.geographicExtents = zipCodes;
        }

        public String getTerritoryName()
        {
            return territoryName;
        }

        public void setTerritoryName( String territoryName )
        {
            this.territoryName = territoryName;
        }

        public Set<String> getGeographicExtents()
        {
            return geographicExtents != null ? Collections.unmodifiableSet( geographicExtents ) : Collections.emptySet();
        }

        public void setGeographicExtents( Set<String> geographicExtents )
        {
            this.geographicExtents = new HashSet<>( geographicExtents );
        }

        @Override
        public int hashCode()
        {
            int hash = 7;
            hash = 53 * hash + Objects.hashCode( this.territoryName );
            return hash;
        }

        @Override
        public boolean equals( Object obj )
        {
            if ( this == obj ) {
                return true;
            }
            if ( obj == null ) {
                return false;
            }
            if ( getClass() != obj.getClass() ) {
                return false;
            }
            final SalesTerritory other = (SalesTerritory) obj;
            if ( !Objects.equals( this.territoryName, other.territoryName ) ) {
                return false;
            }
            return true;
        }

        @Override
        public String toString()
        {
            return "SalesTerritory{" + "territoryName=" + territoryName + ", geographicExtents=" + geographicExtents + '}';
        }

    }

and this:

public class SalesTerritories
{
    private static final Set<SalesTerritory> territories
        = new HashSet<>(
            Arrays.asList(
                new SalesTerritory[]{
                    new SalesTerritory( "North-East, USA",
                                        new HashSet<>( Arrays.asList( new String[]{ "Maine", "New Hampshire", "Vermont",
                                                                                    "Rhode Island", "Massachusetts", "Connecticut",
                                                                                    "New York", "New Jersey", "Delaware", "Maryland",
                                                                                    "Eastern Pennsylvania", "District of Columbia" } ) ) ),
                    new SalesTerritory( "Appalachia, USA",
                                        new HashSet<>( Arrays.asList( new String[]{ "West-Virgina", "Kentucky",
                                                                                    "Western Pennsylvania" } ) ) ),
                    new SalesTerritory( "South-East, USA",
                                        new HashSet<>( Arrays.asList( new String[]{ "Virginia", "North Carolina", "South Carolina",
                                                                                    "Georgia", "Florida", "Alabama", "Tennessee",
                                                                                    "Mississippi", "Arkansas", "Louisiana" } ) ) ),
                    new SalesTerritory( "Mid-West, USA",
                                        new HashSet<>( Arrays.asList( new String[]{ "Ohio", "Michigan", "Wisconsin", "Minnesota",
                                                                                    "Iowa", "Missouri", "Illinois", "Indiana" } ) ) ),
                    new SalesTerritory( "Great Plains, USA",
                                        new HashSet<>( Arrays.asList( new String[]{ "Oklahoma", "Kansas", "Nebraska",
                                                                                    "South Dakota", "North Dakota",
                                                                                    "Eastern Montana",
                                                                                    "Wyoming", "Colorada" } ) ) ),
                    new SalesTerritory( "Rocky Mountain, USA",
                                        new HashSet<>( Arrays.asList( new String[]{ "Western Montana", "Idaho", "Utah", "Nevada" } ) ) ),
                    new SalesTerritory( "South-West, USA",
                                        new HashSet<>( Arrays.asList( new String[]{ "Arizona", "New Mexico", "Texas" } ) ) ),
                    new SalesTerritory( "Pacific North-West, USA",
                                        new HashSet<>( Arrays.asList( new String[]{ "Washington", "Oregon", "Alaska" } ) ) ),
                    new SalesTerritory( "Pacific South-West, USA",
                                        new HashSet<>( Arrays.asList( new String[]{ "California", "Hawaii" } ) ) )
                }
            )
        );

    public static Set<SalesTerritory> getAllTerritories()
    {
        return Collections.unmodifiableSet( territories );
    }

    private SalesTerritories()
    {
    }

}

We can then do this:

System.out.println();
System.out
    .println( "We can use 'flatMap' in combination with the 'AbstractMap.SimpleEntry' class to flatten a hierarchical data-structure to a set of Key/Value pairs..." );
SalesTerritories.getAllTerritories()
    .stream()
    .flatMap( t -> t.getGeographicExtents()
        .stream()
        .map( ge -> new SimpleEntry<>( t.getTerritoryName(), ge ) )
    )
    .map( e -> String.format( "%-30s : %s",
                              e.getKey(),
                              e.getValue() ) )
    .forEach( System.out::println );

Why fragments, and when to use fragments instead of activities?

A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity which enable a more modular activity design. It will not be wrong if we say a fragment is a kind of subactivity.

Following are important points about a fragment:

  1. A fragment has its own layout and its own behavior with its own lifecycle callbacks.

  2. You can add or remove fragments in an activity while the activity is running.

  3. You can combine multiple fragments in a single activity to build a multi-pane UI.

  4. A fragment can be used in multiple activities.

  5. The fragment life cycle is closely related to the lifecycle of its host activity.

  6. When the activity is paused, all the fragments available in the acivity will also be stopped.

  7. A fragment can implement a behavior that has no user interface component.

  8. Fragments were added to the Android API in Android 3 (Honeycomb) with API version 11.

For more details, please visit the official site, Fragments.

Escape double quotes for JSON in Python

Why not do string suppression with triple quotes:

>>> s = """my string with "some" double quotes"""
>>> print s
my string with "some" double quotes

Difference between e.target and e.currentTarget

It's worth noting that event.target can be useful, for example, for using a single listener to trigger different actions. Let's say you have the typical "menu" sprite with 10 buttons inside, so instead of doing:

menu.button1.addEventListener(MouseEvent.CLICK, doAction1);
menu.button2.addEventListener(MouseEvent.CLICK, doAction2);
etc...

You can simply do:

menu.addEventListener(MouseEvent.CLICK, doAction);

And trigger a different action within doAction(event) depending on the event.target (using it's name property, etc...)

Java generating non-repeating random numbers

public class RandomNum {
    public static void main(String[] args) {
        Random rn = new Random();
        HashSet<Integer> hSet = new HashSet<>();
        while(hSet.size() != 1000) {
            hSet.add(rn.nextInt(1000));
        }
        System.out.println(hSet);
    }
}

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

I imported the project as general project from git repository.

  • Deleted .settings, .project and .classpath in project's folder
  • Configure -> Convert to Maven Project. Only this solved the problem in my case.

Remove all the elements that occur in one list from another

use Set Comprehensions {x for x in l2} or set(l2) to get set, then use List Comprehensions to get list

l2set = set(l2)
l3 = [x for x in l1 if x not in l2set]

benchmark test code:

import time

l1 = list(range(1000*10 * 3))
l2 = list(range(1000*10 * 2))

l2set = {x for x in l2}

tic = time.time()
l3 = [x for x in l1 if x not in l2set]
toc = time.time()
diffset = toc-tic
print(diffset)

tic = time.time()
l3 = [x for x in l1 if x not in l2]
toc = time.time()
difflist = toc-tic
print(difflist)

print("speedup %fx"%(difflist/diffset))

benchmark test result:

0.0015058517456054688
3.968189239501953
speedup 2635.179227x    

Elegant way to report missing values in a data.frame

I think the Amelia library does a nice job in handling missing data also includes a map for visualizing the missing rows.

install.packages("Amelia")
library(Amelia)
missmap(airquality)

enter image description here

You can also run the following code will return the logic values of na

row.has.na <- apply(training, 1, function(x){any(is.na(x))})

MongoDB Show all contents from all collections

This way:

db.collection_name.find().toArray().then(...function...)

numpy: most efficient frequency counts for unique values in an array

Take a look at np.bincount:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html

import numpy as np
x = np.array([1,1,1,2,2,2,5,25,1,1])
y = np.bincount(x)
ii = np.nonzero(y)[0]

And then:

zip(ii,y[ii]) 
# [(1, 5), (2, 3), (5, 1), (25, 1)]

or:

np.vstack((ii,y[ii])).T
# array([[ 1,  5],
         [ 2,  3],
         [ 5,  1],
         [25,  1]])

or however you want to combine the counts and the unique values.

Memcache Vs. Memcached

(PartlyStolen from ServerFault)

I think that both are functionally the same, but they simply have different authors, and the one is simply named more appropriately than the other.


Here is a quick backgrounder in naming conventions (for those unfamiliar), which explains the frustration by the question asker: For many *nix applications, the piece that does the backend work is called a "daemon" (think "service" in Windows-land), while the interface or client application is what you use to control or access the daemon. The daemon is most often named the same as the client, with the letter "d" appended to it. For example "imap" would be a client that connects to the "imapd" daemon.

This naming convention is clearly being adhered to by memcache when you read the introduction to the memcache module (notice the distinction between memcache and memcached in this excerpt):

Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.

The Memcache module also provides a session handler (memcache).

More information about memcached can be found at » http://www.danga.com/memcached/.

The frustration here is caused by the author of the PHP extension which was badly named memcached, since it shares the same name as the actual daemon called memcached. Notice also that in the introduction to memcached (the php module), it makes mention of libmemcached, which is the shared library (or API) that is used by the module to access the memcached daemon:

memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.

This extension uses libmemcached library to provide API for communicating with memcached servers. It also provides a session handler (memcached).

Information about libmemcached can be found at » http://tangent.org/552/libmemcached.html.

OS X Terminal UTF-8 issues

Go to Terminal -> Preferences -> Advanced (Tab) go down to International and select Unicode (UTF-8) as Character Encoding.

And tick Set locale environment variables on startup.

How to redirect to another page using PHP

<?php 
include("config.php");
 
 
$id=$_GET['id'];

include("config.php");
if($insert = mysqli_query($con,"update  consumer_closeconnection set close_status='Pending' where id="$id"  "))
            {
?>
<script>
    window.location.href='ConsumerCloseConnection.php';

</script>
<?php
            }
            else
            {
?>
<script>
     window.location.href='ConsumerCloseConnection.php';
</script>
<?php            
    }
?>      

What can I use for good quality code coverage for C#/.NET?

I am not sure what the difference is with the retail NCover, but there is also an NCover project on SourceForge that is of course open source and free.

Labeling file upload button

Take a step back! Firstly, you're assuming the user is using a foreign locale on their device, which is not a sound assumption for justifying taking over the button text of the file picker, and making it say what you want it to.

It is reasonable that you want to control every item of language visible on your page. The content of the File Upload control is not part of the HTML though. There is more content behind this control, for example, in WebKit, it also says "No file chosen" next to the button.

There are very hacky workarounds that attempt this (e.g. like those mentioned in @ChristopheD's answer), but none of them truly succeed:

  • To a screen reader, the file control will still say "Browse..." or "Choose File", and a custom file upload will not be announced as a file upload control, but just a button or a text input.
  • Many of them fail to display the chosen file, or to show that the user has no longer chosen a file
  • Many of them look nothing like the native control, so might look strange on non-standard devices.
  • Keyboard support is typically poor.
  • An author-created UI component can never be as fully functional as its native equivalent (and the closer you get it to behave to suppose IE10 on Windows 7, the more it will deviate from other Browser and Operating System combinations).
  • Modern browsers support drag & drop into the native file upload control.
  • Some techniques may trigger heuristics in security software as a potential ‘click-jacking’ attempt to trick the user into uploading file.

Deviating from the native controls is always a risky thing, there is a whole host of different devices your users could be using, and whatever workaround you choose, you will not have tested it in every one of those devices.

However, there is an even bigger reason why all attempts fail from a User Experience perspective: there is even more non-localized content behind this control, the file selection dialog itself. Once the user is subject to traversing their file system or what not to select a file to upload, they will be subjected to the host Operating System locale.

Are you sure you're doing your user any justice by deviating from the native control, just to localize the text, when as soon as they click it, they're just going to get the Operating System locale anyway?

The best you can do for your users is to ensure you have adequate localised guidance surrounding your file input control. (e.g. Form field label, hint text, tooltip text).

Sorry. :-(

--

This answer is for those looking for any justification not to localise the file upload control.

How to map a composite key with JPA and Hibernate?

Another option is to map is as a Map of composite elements in the ConfPath table.

This mapping would benefit from an index on (ConfPathID,levelStation) though.

public class ConfPath {
    private Map<Long,Time> timeForLevelStation = new HashMap<Long,Time>();

    public Time getTime(long levelStation) {
        return timeForLevelStation.get(levelStation);
    }

    public void putTime(long levelStation, Time newValue) {
        timeForLevelStation.put(levelStation, newValue);
    }
}

public class Time {
    String src;
    String dst;
    long distance;
    long price;

    public long getDistance() {
        return distance;
    }

    public void setDistance(long distance) {
        this.distance = distance;
    }

    public String getDst() {
        return dst;
    }

    public void setDst(String dst) {
        this.dst = dst;
    }

    public long getPrice() {
        return price;
    }

    public void setPrice(long price) {
        this.price = price;
    }

    public String getSrc() {
        return src;
    }

    public void setSrc(String src) {
        this.src = src;
    }
}

Mapping:

<class name="ConfPath" table="ConfPath">
    <id column="ID" name="id">
        <generator class="native"/>
    </id>
    <map cascade="all-delete-orphan" name="values" table="example"
            lazy="extra">
        <key column="ConfPathID"/>
        <map-key type="long" column="levelStation"/>
        <composite-element class="Time">
            <property name="src" column="src" type="string" length="100"/>
            <property name="dst" column="dst" type="string" length="100"/>
            <property name="distance" column="distance"/>
            <property name="price" column="price"/>
        </composite-element>
    </map>
</class>

How to align texts inside of an input?

The accepted answer here is correct but I'd like to add a little info. If you are using a library / framework like bootstrap there may be built in classes for this. For example bootstrap uses the text-right class. Use it like this:

<input type="text" class="text-right"/> 
<input type="number" class="text-right"/>

As a note this works on other input types as well, like numeric as shown above.

If you aren't using a nice framework like bootstrap then you can make your own version of this helper class. Similar to other answers but we are not going to add it directly to the input class so it won't apply to every single input on your site or page, this might not be desired behavior. So this would create a nice easy css class to align things right without needing inline styling or affecting every single input box.

.text-right{
    text-align: right;
}

Now you can use this class exactly the same as the inputs above with class="text-right". I know it isn't saving that many key strokes but it makes your code cleaner.

How can I commit files with git?

in standart Vi editor in this situation you should

  1. press Esc
  2. type ":wq" (without quotes)
  3. Press Enter

How to use support FileProvider for sharing content to other apps?

I want to share something that blocked us for a couple of days: the fileprovider code MUST be inserted between the application tags, not after it. It may be trivial, but it's never specified, and I thought that I could have helped someone! (thanks again to piolo94)

How to get share counts using graph API

You should not use graph api. If you either call:

or

both will return:

{
  "id": "http://www.apple.com",
  "shares": 1146997
}

But the number shown is the sum of:

  • number of likes of this URL
  • number of shares of this URL (this includes copy/pasting a link back to Facebook)
  • number of likes and comments on stories on Facebook about this URL
  • number of inbox messages containing this URL as an attachment.

So you must use FQL.
Look at this answer: How to fetch facebook likes, share, comments count from an article

How do I load an HTML page in a <div> using JavaScript?

Use this simple code

<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>```

C# Pass Lambda Expression as Method Parameter

Lambda expressions have a type of Action<parameters> (in case they don't return a value) or Func<parameters,return> (in case they have a return value). In your case you have two input parameters, and you need to return a value, so you should use:

Func<FullTimeJob, Student, FullTimeJob>

How to make a div 100% height of the browser window

If you’re able to absolutely position your elements,

position: absolute;
top: 0;
bottom: 0;

would do it.

EF Code First "Invalid column name 'Discriminator'" but no inheritance

I had a similar problem, not exactly the same conditions and then i saw this post. Hope it helps someone. Apparently i was using one of my EF entity models a base class for a type that was not specified as a db set in my dbcontext. To fix this issue i had to create a base class that had all the properties common to the two types and inherit from the new base class among the two types.

Example:

//Bad Flow
    //class defined in dbcontext as a dbset
    public class Customer{ 
       public int Id {get; set;}
       public string Name {get; set;}
    }

    //class not defined in dbcontext as a dbset
    public class DuplicateCustomer:Customer{ 
       public object DuplicateId {get; set;}
    }


    //Good/Correct flow*
    //Common base class
    public class CustomerBase{ 
       public int Id {get; set;}
       public string Name {get; set;}
    }

    //entity model referenced in dbcontext as a dbset
    public class Customer: CustomerBase{

    }

    //entity model not referenced in dbcontext as a dbset
    public class DuplicateCustomer:CustomerBase{

       public object DuplicateId {get; set;}

    }

Twig ternary operator, Shorthand if-then-else

You can use shorthand syntax as of Twig 1.12.0

{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}

Gem Command not found

Are you wanting ruby gems? If so, you need to install libgemplugin-ruby and then the ruby 'gem' program will be in your path:

aptitude install libgemplugin-ruby

Can Windows Containers be hosted on linux?

Containers use the OS kernel. Windows Container utilize processes in order to run. So theoretically speaking Windows Containers cannot run on Linux.

However there are workarounds utilizing VMstyle solutions.

I Have found this solution which uses Vagrant and Packer on Mac, so it should work for Linux as well: https://github.com/StefanScherer/windows-docker-machine

This Vagrant environment creates a Docker Machine to work on your MacBook with Windows containers. You can easily switch between Docker for Mac Linux containers and the Windows containers.

Running bash commands enter image description here

building the headless Vagrant box

$ git clone https://github.com/StefanScherer/packer-windows
$ cd packer-windows

$ packer build --only=vmware-iso windows_2019_docker.json
$ vagrant box add windows_2019_docker windows_2019_docker_vmware.box

Create the Docker Machine

$ git clone https://github.com/StefanScherer/windows-docker-machine
$ cd windows-docker-machine
$ vagrant up --provider vmware_fusion 2019

Switch to Windows containers

$ eval $(docker-machine env 2019)

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

In my case, it's related to the Toggle Vrapper Icon in the Eclipse.

If you are getting the bold black cursor, then the icon must be enabled. So, click on the Toggle Vrapper Icon to disable. It's located in the Eclipse's Toolbar. Please see the attached image for the clarity.

enter image description here

Split column at delimiter in data frame

strsplit(c('a|b','b|c'),'|',fixed=TRUE)

Keyboard shortcuts with jQuery

If you want just simple shortcuts (like 1 letter, for example just g) you could easily do it without a extra plugin:

$(document).keypress(function(e) {
  if(e.charCode == 103) {
    // Your Code
  }
});

How to make HTML element resizable using pure Javascript?

There are very good examples here to start trying with, but all of them are based on adding some extra or external element like a "div" as a reference element to drag it, and calculate the new dimensions or position of the original element.

Here's an example that doesn't use any extra elements. We could add borders, padding or margin without affecting its operation. In this example we have not added color, nor any visual reference to the borders nor to the lower right corner as a clue where you can enlarge or reduce dimensions, but using the cursor around the resizable elements the clues appears!

let resizerForCenter = new Resizer('center')  
resizerForCenter.initResizer()

See it in action with CodeSandbox:

In this example we use ES6, and a module that exports a class called Resizer. An example is worth a thousand words:

Edit boring-snow-qz1sd

Or with the code snippet:

_x000D_
_x000D_
const html = document.querySelector('html')_x000D_
_x000D_
class Resizer {_x000D_
 constructor(elemId) {_x000D_
  this._elem = document.getElementById(elemId)_x000D_
  /**_x000D_
   * Stored binded context handlers for method passed to eventListeners!_x000D_
   * _x000D_
   * See: https://stackoverflow.com/questions/9720927/removing-event-listeners-as-class-prototype-functions_x000D_
   */_x000D_
  this._checkBorderHandler = this._checkBorder.bind(this)_x000D_
  this._doResizeHandler  = this._doResize.bind(this)_x000D_
  this._initResizerHandler = this.initResizer.bind(this)_x000D_
  this._onResizeHandler  = this._onResize.bind(this)_x000D_
 }_x000D_
_x000D_
 initResizer() {_x000D_
  this.stopResizer()_x000D_
  this._beginResizer()_x000D_
 }_x000D_
_x000D_
 _beginResizer() {_x000D_
  this._elem.addEventListener('mousemove', this._checkBorderHandler, false)_x000D_
 }_x000D_
_x000D_
 stopResizer() {_x000D_
  html.style.cursor = 'default'_x000D_
  this._elem.style.cursor = 'default'_x000D_
  _x000D_
  window.removeEventListener('mousemove', this._doResizeHandler, false)_x000D_
  window.removeEventListener('mouseup', this._initResizerHandler, false)_x000D_
_x000D_
  this._elem.removeEventListener('mousedown', this._onResizeHandler, false)_x000D_
  this._elem.removeEventListener('mousemove', this._checkBorderHandler, false)_x000D_
 }_x000D_
_x000D_
 _doResize(e) {_x000D_
  let elem = this._elem_x000D_
_x000D_
  let boxSizing = getComputedStyle(elem).boxSizing_x000D_
  let borderRight = 0_x000D_
  let borderLeft = 0_x000D_
  let borderTop = 0_x000D_
  let borderBottom = 0_x000D_
_x000D_
  let paddingRight = 0_x000D_
  let paddingLeft = 0_x000D_
  let paddingTop = 0_x000D_
  let paddingBottom = 0_x000D_
_x000D_
  switch (boxSizing) {_x000D_
   case 'content-box':_x000D_
     paddingRight = parseInt(getComputedStyle(elem).paddingRight)_x000D_
     paddingLeft = parseInt(getComputedStyle(elem).paddingLeft)_x000D_
     paddingTop = parseInt(getComputedStyle(elem).paddingTop)_x000D_
     paddingBottom = parseInt(getComputedStyle(elem).paddingBottom)_x000D_
    break_x000D_
   case 'border-box':_x000D_
     borderRight = parseInt(getComputedStyle(elem).borderRight)_x000D_
     borderLeft = parseInt(getComputedStyle(elem).borderLeft)_x000D_
     borderTop = parseInt(getComputedStyle(elem).borderTop)_x000D_
     borderBottom = parseInt(getComputedStyle(elem).borderBottom)_x000D_
    break_x000D_
   default: break_x000D_
  }_x000D_
_x000D_
  let horizontalAdjustment = (paddingRight + paddingLeft) - (borderRight + borderLeft)_x000D_
  let verticalAdjustment  = (paddingTop + paddingBottom) - (borderTop + borderBottom)_x000D_
_x000D_
  let newWidth = elem.clientWidth  + e.movementX - horizontalAdjustment + 'px'_x000D_
  let newHeight = elem.clientHeight + e.movementY - verticalAdjustment   + 'px'_x000D_
  _x000D_
  let cursorType = getComputedStyle(elem).cursor_x000D_
  switch (cursorType) {_x000D_
   case 'all-scroll':_x000D_
     elem.style.width = newWidth_x000D_
     elem.style.height = newHeight_x000D_
    break_x000D_
   case 'col-resize':_x000D_
     elem.style.width = newWidth_x000D_
    break_x000D_
   case 'row-resize':_x000D_
     elem.style.height = newHeight_x000D_
    break_x000D_
   default: break_x000D_
  }_x000D_
 }_x000D_
_x000D_
 _onResize(e) {_x000D_
  // On resizing state!_x000D_
  let elem = e.target_x000D_
  let newCursorType = undefined_x000D_
  let cursorType = getComputedStyle(elem).cursor_x000D_
  switch (cursorType) {_x000D_
   case 'nwse-resize':_x000D_
    newCursorType = 'all-scroll'_x000D_
    break_x000D_
   case 'ew-resize':_x000D_
    newCursorType = 'col-resize'_x000D_
    break_x000D_
   case 'ns-resize':_x000D_
    newCursorType = 'row-resize'_x000D_
    break_x000D_
   default: break_x000D_
  }_x000D_
  _x000D_
  html.style.cursor = newCursorType // Avoid cursor's flickering _x000D_
  elem.style.cursor = newCursorType_x000D_
  _x000D_
  // Remove what is not necessary, and could have side effects!_x000D_
  elem.removeEventListener('mousemove', this._checkBorderHandler, false);_x000D_
  _x000D_
  // Events on resizing state_x000D_
  /**_x000D_
   * We do not apply the mousemove event on the elem to resize it, but to the window to prevent the mousemove from slippe out of the elem to resize. This work bc we calculate things based on the mouse position_x000D_
   */_x000D_
  window.addEventListener('mousemove', this._doResizeHandler, false);_x000D_
  window.addEventListener('mouseup', this._initResizerHandler, false);_x000D_
 }_x000D_
_x000D_
 _checkBorder(e) {_x000D_
  const elem = e.target_x000D_
  const borderSensitivity = 5_x000D_
  const coor = getCoordenatesCursor(e)_x000D_
  const onRightBorder  = ((coor.x + borderSensitivity) > elem.scrollWidth)_x000D_
  const onBottomBorder = ((coor.y + borderSensitivity) > elem.scrollHeight)_x000D_
  const onBottomRightCorner = (onRightBorder && onBottomBorder)_x000D_
  _x000D_
  if (onBottomRightCorner) {_x000D_
   elem.style.cursor = 'nwse-resize'_x000D_
  } else if (onRightBorder) {_x000D_
   elem.style.cursor = 'ew-resize'_x000D_
  } else if (onBottomBorder) {_x000D_
   elem.style.cursor = 'ns-resize'_x000D_
  } else {_x000D_
   elem.style.cursor = 'auto'_x000D_
  }_x000D_
  _x000D_
  if (onRightBorder || onBottomBorder) {_x000D_
   elem.addEventListener('mousedown', this._onResizeHandler, false)_x000D_
  } else {_x000D_
   elem.removeEventListener('mousedown', this._onResizeHandler, false)_x000D_
  }_x000D_
 }_x000D_
}_x000D_
_x000D_
function getCoordenatesCursor(e) {_x000D_
 let elem = e.target;_x000D_
 _x000D_
 // Get the Viewport-relative coordinates of cursor._x000D_
 let viewportX = e.clientX_x000D_
 let viewportY = e.clientY_x000D_
 _x000D_
 // Viewport-relative position of the target element._x000D_
 let elemRectangle = elem.getBoundingClientRect()_x000D_
 _x000D_
 // The  function returns the largest integer less than or equal to a given number._x000D_
 let x = Math.floor(viewportX - elemRectangle.left) // - elem.scrollWidth_x000D_
 let y = Math.floor(viewportY - elemRectangle.top) // - elem.scrollHeight_x000D_
 _x000D_
 return {x, y}_x000D_
}_x000D_
_x000D_
let resizerForCenter = new Resizer('center')_x000D_
resizerForCenter.initResizer()_x000D_
_x000D_
let resizerForLeft = new Resizer('left')_x000D_
resizerForLeft.initResizer()_x000D_
_x000D_
setTimeout(handler, 10000, true); // 10s_x000D_
_x000D_
function handler() {_x000D_
  resizerForCenter.stopResizer()_x000D_
}
_x000D_
body {_x000D_
 background-color: white;_x000D_
}_x000D_
_x000D_
#wrapper div {_x000D_
 /* box-sizing: border-box; */_x000D_
 position: relative;_x000D_
 float:left;_x000D_
 overflow: hidden;_x000D_
 height: 50px;_x000D_
 width: 50px;_x000D_
 padding: 3px;_x000D_
}_x000D_
_x000D_
#left {_x000D_
 background-color: blueviolet;_x000D_
}_x000D_
#center {_x000D_
 background-color:lawngreen ;_x000D_
}_x000D_
#right {_x000D_
 background: blueviolet;_x000D_
}_x000D_
#wrapper {_x000D_
 border: 5px solid hotpink;_x000D_
 display: inline-block;_x000D_
 _x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
 <meta charset="UTF-8">_x000D_
 <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
 <meta http-equiv="X-UA-Compatible" content="ie=edge">_x000D_
 <title>Resizer v0.0.1</title>_x000D_
</head>_x000D_
  <body>_x000D_
    <div id="wrapper">_x000D_
      <div id="left">Left</div>_x000D_
      <div id="center">Center</div>_x000D_
      <div id="right">Right</div>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Representing Directory & File Structure in Markdown Syntax

You can use tree to generate something very similar to your example. Once you have the output, you can wrap it in a <pre> tag to preserve the plain text formatting.

How to Convert unsigned char* to std::string in C++?

If has access to CryptoPP

Readable Hex String to unsigned char

std::string& hexed = "C23412341324AB";
uint8_t      buffer[64] = {0};
StringSource ssk(hexed, true,
            new HexDecoder(new ArraySink(buffer,sizeof(buffer))));

And back

std::string hexed;
uint8_t val[32]  = {0};
StringSource ss(val, sizeof(val), true,new HexEncoder(new StringSink(hexed));
// val == buffer

OpenCV - Apply mask to a color image

Well, here is a solution if you want the background to be other than a solid black color. We only need to invert the mask and apply it in a background image of the same size and then combine both background and foreground. A pro of this solution is that the background could be anything (even other image).

This example is modified from Hough Circle Transform. First image is the OpenCV logo, second the original mask, third the background + foreground combined.

apply mask and get a customized background

# http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghcircles/py_houghcircles.html
import cv2
import numpy as np

# load the image
img = cv2.imread('E:\\FOTOS\\opencv\\opencv_logo.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# detect circles
gray = cv2.medianBlur(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), 5)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=50, minRadius=0, maxRadius=0)
circles = np.uint16(np.around(circles))

# draw mask
mask = np.full((img.shape[0], img.shape[1]), 0, dtype=np.uint8)  # mask is only 
for i in circles[0, :]:
    cv2.circle(mask, (i[0], i[1]), i[2], (255, 255, 255), -1)

# get first masked value (foreground)
fg = cv2.bitwise_or(img, img, mask=mask)

# get second masked value (background) mask must be inverted
mask = cv2.bitwise_not(mask)
background = np.full(img.shape, 255, dtype=np.uint8)
bk = cv2.bitwise_or(background, background, mask=mask)

# combine foreground+background
final = cv2.bitwise_or(fg, bk)

Note: It is better to use the opencv methods because they are optimized.

What is the difference between pull and clone in git?

git clone <remote-url> <=>

  • create a new directory
  • git init // init new repository
  • git remote add origin <remote-url> // add remote
  • git fetch // fetch all remote branchs
  • git switch <default_branch> // switch to the default branch

git pull <=>

  • fetch ALL remote branches
  • merge CURRENT local branch with tracking remote branch (not another branch) (if local branch existed)

git pull <remote> <branch> <=>

  • fetch the remote branch
  • merge CURRENT local branch with the remote branch (if local branch existed)

What is the difference between README and README.md in GitHub projects?

.md stands for markdown and is generated at the bottom of your github page as html.

Typical syntax includes:

Will become a heading
==============

Will become a sub heading
--------------

*This will be Italic*

**This will be Bold**

- This will be a list item
- This will be a list item

    Add a indent and this will end up as code

For more details: http://daringfireball.net/projects/markdown/

Immutable array in Java

While it's true that Collections.unmodifiableList() works, sometimes you may have a large library having methods already defined to return arrays (e.g. String[]). To prevent breaking them, you can actually define auxiliary arrays that will store the values:

public class Test {
    private final String[] original;
    private final String[] auxiliary;
    /** constructor */
    public Test(String[] _values) {
        original = new String[_values.length];
        // Pre-allocated array.
        auxiliary = new String[_values.length];
        System.arraycopy(_values, 0, original, 0, _values.length);
    }
    /** Get array values. */
    public String[] getValues() {
        // No need to call clone() - we pre-allocated auxiliary.
        System.arraycopy(original, 0, auxiliary, 0, original.length);
        return auxiliary;
    }
}

To test:

    Test test = new Test(new String[]{"a", "b", "C"});
    System.out.println(Arrays.asList(test.getValues()));
    String[] values = test.getValues();
    values[0] = "foobar";
    // At this point, "foobar" exist in "auxiliary" but since we are 
    // copying "original" to "auxiliary" for each call, the next line
    // will print the original values "a", "b", "c".
    System.out.println(Arrays.asList(test.getValues()));

Not perfect, but at least you have "pseudo immutable arrays" (from the class perspective) and this will not break related code.

WAITING at sun.misc.Unsafe.park(Native Method)

I had a similar issue, and following previous answers (thanks!), I was able to search and find how to handle correctly the ThreadPoolExecutor terminaison.

In my case, that just fix my progressive increase of similar blocked threads:

  • I've used ExecutorService::awaitTermination(x, TimeUnit) and ExecutorService::shutdownNow() (if necessary) in my finally clause.
  • For information, I've used the following commands to detect thread count & list locked threads:

    ps -u javaAppuser -L|wc -l

    jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayA.log

    jcmd `ps -C java -o pid=` Thread.print >> threadPrintDayAPlusOne.log

    cat threadPrint*.log |grep "pool-"|wc -l

Entity Framework Provider type could not be loaded?

The problem in my case was that in order to catch another exception I had enabled common language runtime (CLR) exceptions. And I forgot to disable it.

I disabled it in my exception setting. and it overlooked this exception and went on to run and create a db for me (in my case) automatically.

Pandas conditional creation of a series/dataframe column

The following is slower than the approaches timed here, but we can compute the extra column based on the contents of more than one column, and more than two values can be computed for the extra column.

Simple example using just the "Set" column:

def set_color(row):
    if row["Set"] == "Z":
        return "red"
    else:
        return "green"

df = df.assign(color=df.apply(set_color, axis=1))

print(df)
  Set Type  color
0   Z    A    red
1   Z    B    red
2   X    B  green
3   Y    C  green

Example with more colours and more columns taken into account:

def set_color(row):
    if row["Set"] == "Z":
        return "red"
    elif row["Type"] == "C":
        return "blue"
    else:
        return "green"

df = df.assign(color=df.apply(set_color, axis=1))

print(df)
  Set Type  color
0   Z    A    red
1   Z    B    red
2   X    B  green
3   Y    C   blue

Edit (21/06/2019): Using plydata

It is also possible to use plydata to do this kind of things (this seems even slower than using assign and apply, though).

from plydata import define, if_else

Simple if_else:

df = define(df, color=if_else('Set=="Z"', '"red"', '"green"'))

print(df)
  Set Type  color
0   Z    A    red
1   Z    B    red
2   X    B  green
3   Y    C  green

Nested if_else:

df = define(df, color=if_else(
    'Set=="Z"',
    '"red"',
    if_else('Type=="C"', '"green"', '"blue"')))

print(df)                            
  Set Type  color
0   Z    A    red
1   Z    B    red
2   X    B   blue
3   Y    C  green

How to dump a dict to a json file?

This should give you a start

>>> import json
>>> print json.dumps([{'name': k, 'size': v} for k,v in sample.items()], indent=4)
[
    {
        "name": "PointInterpolator",
        "size": 1675
    },
    {
        "name": "ObjectInterpolator",
        "size": 1629
    },
    {
        "name": "RectangleInterpolator",
        "size": 2042
    }
]

Remove #N/A in vlookup result

To avoid errors in any excel function, use the Error Handling functions that start with IS* in Excel. Embed your function with these error handing functions and avoid the undesirable text in your results. More info in OfficeTricks Page

Disable PHP in directory (including all sub-directories) with .htaccess

None of those answers are working for me (either generating a 500 error or doing nothing). That is probably due to the fact that I'm working on a hosted server where I can't have access to Apache configuration.

But this worked for me :

RewriteRule ^.*\.php$ - [F,L]

This line will generate a 403 Forbidden error for any URL that ends with .php and ends up in this subdirectory.

@Oussama lead me to the right direction here, thanks to him.

Connect HTML page with SQL server using javascript

<script>
var name=document.getElementById("name").value;
var address= document.getElementById("address").value;
var age= document.getElementById("age").value;

$.ajax({
      type:"GET",
      url:"http://hostname/projectfolder/webservicename.php?callback=jsondata&web_name="+name+"&web_address="+address+"&web_age="+age,
      crossDomain:true,
      dataType:'jsonp',
      success: function jsondata(data)
           {

            var parsedata=JSON.parse(JSON.stringify(data));
            var logindata=parsedata["Status"];

            if("sucess"==logindata)
            {   
                alert("success");
            }
            else
            {
                alert("failed");
            }
          }  
    }); 
<script>

You need to use web services. In the above code I have php web service to be used which has a callback function which is optional. Assuming you know HTML5 I did not post the html code. In the url you can send the details to the web server.

javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher

A few comments:

import sun.misc.*; Don't do this. It is non-standard and not guaranteed to be the same between implementations. There are other libraries with Base64 conversion available.

byte[] encVal = c.doFinal(Data.getBytes()); You are relying on the default character encoding here. Always specify what character encoding you are using: byte[] encVal = c.doFinal(Data.getBytes("UTF-8")); Defaults might be different in different places.

As @thegrinner pointed out, you need to explicitly check the length of your byte arrays. If there is a discrepancy, then compare them byte by byte to see where the difference is creeping in.

Find rows that have the same value on a column in MySQL

select email from mytable group by email having count(*) >1

bash echo number of lines of file given in a bash variable without the file name

wc can't get the filename if you don't give it one.

wc -l < "$JAVA_TAGS_FILE"

Parsing GET request parameters in a URL that contains another URL

The correct php way is to use parse_url()

http://php.net/manual/en/function.parse-url.php

(from php manual)

This function parses a URL and returns an associative array containing any of the various components of the URL that are present.

This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly.

Is it possible to dynamically compile and execute C# code fragments?

Found this useful - ensures the compiled Assembly references everything you currently have referenced, since there's a good chance you wanted the C# you're compiling to use some classes etc in the code that's emitting this:

(string code is the dynamic C# being compiled)

        var refs = AppDomain.CurrentDomain.GetAssemblies();
        var refFiles = refs.Where(a => !a.IsDynamic).Select(a => a.Location).ToArray();
        var cSharp = (new Microsoft.CSharp.CSharpCodeProvider()).CreateCompiler();
        var compileParams = new System.CodeDom.Compiler.CompilerParameters(refFiles);
        compileParams.GenerateInMemory = true;
        compileParams.GenerateExecutable = false;

        var compilerResult = cSharp.CompileAssemblyFromSource(compileParams, code);
        var asm = compilerResult.CompiledAssembly;

In my case I was emitting a class, whose name was stored in a string, className, which had a single public static method named Get(), that returned with type StoryDataIds. Here's what calling that method looks like:

        var tempType = asm.GetType(className);
        var ids = (StoryDataIds)tempType.GetMethod("Get").Invoke(null, null);

Warning: Compilation can be surprisingly, extremely slow. A small, relatively simple 10-line chunk of code compiles at normal priority in 2-10 seconds on our relatively fast server. You should never tie calls to CompileAssemblyFromSource() to anything with normal performance expectations, like a web request. Instead, proactively compile code you need on a low-priority thread and have a way of dealing with code that requires that code to be ready, until it's had a chance to finish compiling. For example you could use it in a batch job process.

How to detect scroll position of page using jQuery

You are looking for the window.scrollTop() function.

$(window).scroll(function() {
    var height = $(window).scrollTop();

    if(height  > some_number) {
        // do something
    }
});

Check if table exists

If using jruby, here is a code snippet to return an array of all tables in a db.

require "rubygems"
require "jdbc/mysql"
Jdbc::MySQL.load_driver
require "java"

def get_database_tables(connection, db_name)
  md = connection.get_meta_data
  rs = md.get_tables(db_name, nil, '%',["TABLE"])

  tables = []
  count = 0
  while rs.next
    tables << rs.get_string(3)
  end #while
  return tables
end

Grep and Python

  1. use sys.argv to get the command-line parameters
  2. use open(), read() to manipulate file
  3. use the Python re module to match lines

Query Mongodb on month, day, year... of a datetime

You can find record by month, day, year etc of dates by Date Aggregation Operators, like $dayOfYear, $dayOfWeek, $month, $year etc.

As an example if you want all the orders which are created in April 2016 you can use below query.

db.getCollection('orders').aggregate(
   [
     {
       $project:
         {
           doc: "$$ROOT",
           year: { $year: "$created" },
           month: { $month: "$created" },
           day: { $dayOfMonth: "$created" }
         }
     },
     { $match : { "month" : 4, "year": 2016 } }
   ]
)

Here created is a date type field in documents, and $$ROOT we used to pass all other field to project in next stage, and give us all the detail of documents.

You can optimize above query as per your need, it is just to give an example. To know more about Date Aggregation Operators, visit the link.

How to reload .bash_profile from the command line?

Simply type source ~/.bash_profile

Alternatively, if you like saving keystrokes you can type . ~/.bash_profile

How to remove square brackets in string using regex?

here you go

var str = "['abc',['def','ghi'],'jkl']";
//'[\'abc\',[\'def\',\'ghi\'],\'jkl\']'
str.replace(/[\[\]']/g,'' );
//'abc,def,ghi,jkl'

What does "#include <iostream>" do?

In order to read or write to the standard input/output streams you need to include it.

int main( int argc, char * argv[] )
{
    std::cout << "Hello World!" << std::endl;
    return 0;
}

That program will not compile unless you add #include <iostream>

The second line isn't necessary

using namespace std;

What that does is tell the compiler that symbol names defined in the std namespace are to be brought into your program's scope, so you can omit the namespace qualifier, and write for example

#include <iostream>
using namespace std;
int main( int argc, char * argv[] )
{
    cout << "Hello World!" << endl;
    return 0;
}

Notice you no longer need to refer to the output stream with the fully qualified name std::cout and can use the shorter name cout.

I personally don't like bringing in all symbols in the namespace of a header file... I'll individually select the symbols I want to be shorter... so I would do this:

#include <iostream>
using std::cout;
using std::endl;

int main( int argc, char * argv[] )
{
    cout << "Hello World!" << endl;
    return 0;
}

But that is a matter of personal preference.

Is JavaScript a pass-by-reference or pass-by-value language?

In JavaScript, the type of the value solely controls whether that value will be assigned by value-copy or by reference-copy.

Primitive values are always assigned/passed by value-copy:

  • null
  • undefined
  • string
  • number
  • boolean
  • symbol in ES6

Compound values are always assigned/passed by reference-copy

  • objects
  • arrays
  • function

For example

var a = 2;
var b = a; // `b` is always a copy of the value in `a`
b++;
a; // 2
b; // 3

var c = [1,2,3];
var d = c; // `d` is a reference to the shared `[1,2,3]` value
d.push( 4 );
c; // [1,2,3,4]
d; // [1,2,3,4]

In the above snippet, because 2 is a scalar primitive, a holds one initial copy of that value, and b is assigned another copy of the value. When changing b, you are in no way changing the value in a.

But both c and d are separate references to the same shared value [1,2,3], which is a compound value. It's important to note that neither c nor d more "owns" the [1,2,3] value -- both are just equal peer references to the value. So, when using either reference to modify (.push(4)) the actual shared array value itself, it's affecting just the one shared value, and both references will reference the newly modified value [1,2,3,4].

var a = [1,2,3];
var b = a;
a; // [1,2,3]
b; // [1,2,3]

// later
b = [4,5,6];
a; // [1,2,3]
b; // [4,5,6]

When we make the assignment b = [4,5,6], we are doing absolutely nothing to affect where a is still referencing ([1,2,3]). To do that, b would have to be a pointer to a rather than a reference to the array -- but no such capability exists in JS!

function foo(x) {
    x.push( 4 );
    x; // [1,2,3,4]

    // later
    x = [4,5,6];
    x.push( 7 );
    x; // [4,5,6,7]
}

var a = [1,2,3];

foo( a );

a; // [1,2,3,4]  not  [4,5,6,7]

When we pass in the argument a, it assigns a copy of the a reference to x. x and a are separate references pointing at the same [1,2,3] value. Now, inside the function, we can use that reference to mutate the value itself (push(4)). But when we make the assignment x = [4,5,6], this is in no way affecting where the initial reference a is pointing -- still points at the (now modified) [1,2,3,4] value.

To effectively pass a compound value (like an array) by value-copy, you need to manually make a copy of it, so that the reference passed doesn't still point to the original. For example:

foo( a.slice() );

Compound value (object, array, etc) that can be passed by reference-copy

function foo(wrapper) {
    wrapper.a = 42;
}

var obj = {
    a: 2
};

foo( obj );

obj.a; // 42

Here, obj acts as a wrapper for the scalar primitive property a. When passed to foo(..), a copy of the obj reference is passed in and set to the wrapperparameter. We now can use the wrapper reference to access the shared object, and update its property. After the function finishes, obj.a will see the updated value 42.

Source

Change visibility of ASP.NET label with JavaScript

You need to be wary of XSS when doing stuff like this:

document.getElementById('<%= Label1.ClientID %>').style.display

The chances are that no-one will be able to tamper with the ClientID of Label1 in this instance, but just to be on the safe side you might want pass it's value through one of the AntiXss library's methods:

document.getElementById('<%= AntiXss.JavaScriptEncode(Label1.ClientID) %>').style.display

C++ trying to swap values in a vector

I think what you are looking for is iter_swap which you can find also in <algorithm>.
all you need to do is just pass two iterators each pointing at one of the elements you want to exchange.
since you have the position of the two elements, you can do something like this:

// assuming your vector is called v
iter_swap(v.begin() + position, v.begin() + next_position);
// position, next_position are the indices of the elements you want to swap

Add space between HTML elements only using CSS

You can take advantage of the fact that span is an inline element

span{
     word-spacing:10px;
}

However, this solution will break if you have more than one word of text in your span

Set proxy through windows command line including login parameters

IE can set username and password proxies, so maybe setting it there and import does work

reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyEnable /t REG_DWORD /d 1
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyServer /t REG_SZ /d name:port
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyUser /t REG_SZ /d username
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyPass /t REG_SZ /d password
netsh winhttp import proxy source=ie

Set NOW() as Default Value for datetime datatype?

On versions mysql 5.6.5 and newer, you can use precise datetimes and set default values as well. There is a subtle bit though, which is to pass in the precision value to both the datetime and the NOW() function call.

This Example Works:

    ALTER TABLE my_table MODIFY created datetime(6) NOT NULL DEFAULT NOW(6);

This Example Does not Work:

    ALTER TABLE my_table MODIFY created datetime(6) NOT NULL DEFAULT NOW();

Is there an easy way to check the .NET Framework version?

You can get a useful string without having to touch the registry or reference assemblies which may or may not be loaded. mscorlib.dll and other System assemblies have AssemblyFileVersionAttribute defined, and it seems to be unique for each version of .NET, based on the reference assemblies provided with Visual Studio.

string version = (typeof(string).Assembly
    .GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false)
    .FirstOrDefault() as AssemblyFileVersionAttribute)?.Version;

Version 4.5 is a bit off, because it's marked 4.0 in that version, but 4.6 onward appear to have the minor version matching at least. Doing it this way seems like it would be more future proof than depending on some installer registry key and having to compare against a fixed set of values.

I found the reference assemblies here:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework

Where I got the following versions:

4.0 = 4.0.30319.1
4.5 = 4.0.30319.18020
4.5.1 = 4.0.30319.18402
4.5.2 = 4.0.30319.34211
4.6 = 4.6.81.0
4.6.1 = 4.6.1055.0
4.7.2 = 4.7.3062.0
4.8 = 4.8.3761.0

Retina displays, high-res background images

If you are planing to use the same image for retina and non-retina screen then here is the solution. Say that you have a image of 200x200 and have two icons in top row and two icon in bottom row. So, it's four quadrants.

.sprite-of-icons {
  background: url("../images/icons-in-four-quad-of-200by200.png") no-repeat;
  background-size: 100px 100px /* Scale it down to 50% rather using 200x200 */
}

.sp-logo-1 { background-position: 0 0; }

/* Reduce positioning of the icons down to 50% rather using -50px */
.sp-logo-2 { background-position: -25px 0 }
.sp-logo-3 { background-position: 0 -25px }
.sp-logo-3 { background-position: -25px -25px }

Scaling and positioning of the sprite icons to 50% than actual value, you can get the expected result.


Another handy SCSS mixin solution by Ryan Benhase.

/****************************
 HIGH PPI DISPLAY BACKGROUNDS
*****************************/

@mixin background-2x($path, $ext: "png", $w: auto, $h: auto, $pos: left top, $repeat: no-repeat) {

  $at1x_path: "#{$path}.#{$ext}";
  $at2x_path: "#{$path}@2x.#{$ext}";

  background-image: url("#{$at1x_path}");
  background-size: $w $h;
  background-position: $pos;
  background-repeat: $repeat;

  @media all and (-webkit-min-device-pixel-ratio : 1.5),
  all and (-o-min-device-pixel-ratio: 3/2),
  all and (min--moz-device-pixel-ratio: 1.5),
  all and (min-device-pixel-ratio: 1.5) {
    background-image: url("#{$at2x_path}"); 
  }
}

div.background {
  @include background-2x( 'path/to/image', 'jpg', 100px, 100px, center center, repeat-x );
}

For more info about above mixin READ HERE.

How can I modify a saved Microsoft Access 2007 or 2010 Import Specification?

Tim Lentine's answer seems to be true even in the full release. There is just one other thing I would like to mention.

If you complete your import without going into "Advanced..." and saving the spec, but you do save the import for reuse at the end of the wizard (new feature AFAIK), you will not be able to go back and edit that spec. It is built into the "Saved Import". This may be what Knox was referring to.

You can, however, do a partial work around:

  1. Import a new file (or the same one all over again) but,
  2. This time choose to append, instead of making a new
  3. Click OK.
  4. Go into "advanced" All your column heading and data-types will be there.
  5. Now you can make the changes you need and save the spec inside that dialog. Then cancel out of that import (that is not what you wanted anyway, right?)
  6. You can then use that spec for any further imports. It's not a full solution, but saves some of the work.

What exceptions should be thrown for invalid or unexpected parameters in .NET?

I voted for Josh's answer, but would like to add one more to the list:

System.InvalidOperationException should be thrown if the argument is valid, but the object is in a state where the argument shouldn't be used.

Update Taken from MSDN:

InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments.

Let's say that your object has a PerformAction(enmSomeAction action) method, valid enmSomeActions are Open and Close. If you call PerformAction(enmSomeAction.Open) twice in a row then the second call should throw the InvalidOperationException (since the arugment was valid, but not for the current state of the control)

Since you're already doing the right thing by programming defensively I have one other exception to mention is ObjectDisposedException. If your object implements IDisposable then you should always have a class variable tracking the disposed state; if your object has been disposed and a method gets called on it you should raise the ObjectDisposedException:

public void SomeMethod()
{
    If (m_Disposed) {
          throw new ObjectDisposedException("Object has been disposed")
     }
    // ... Normal execution code
}

Update: To answer your follow-up: It is a bit of an ambiguous situation, and is made a little more complicated by a generic (not in the .NET Generics sense) data type being used to represent a specific set of data; an enum or other strongly typed object would be a more ideal fit--but we don't always have that control.

I would personally lean towards the ArgumentOutOfRangeException and provide a message that indicates the valid values are 1-12. My reasoning is that when you talk about months, assuming all integer representations of months are valid, then you are expecting a value in the range of 1-12. If only certain months (like months that had 31 days) were valid then you would not be dealing with a Range per-se and I would throw a generic ArgumentException that indicated the valid values, and I would also document them in the method's comments.

no module named urllib.parse (How should I install it?)

Install six, the Python 2 and 3 Compatibility Library:

$ sudo -H pip install six

Use it:

from six.moves.urllib.parse import urlparse

(edit: I deleted the other answer)

How to break out of while loop in Python?

Walrus operator (assignment expressions added to python 3.8) and while-loop-else-clause can do it more pythonic:

myScore = 0
while ans := input("Roll...").lower() == "r":
    # ... do something
else:
    print("Now I'll see if I can break your score...")

Sending email with PHP from an SMTP server

<?php
ini_set("SMTP", "aspmx.l.google.com");
ini_set("sendmail_from", "[email protected]");

$message = "The mail message was sent with the following mail setting:\r\nSMTP = aspmx.l.google.com\r\nsmtp_port = 25\r\nsendmail_from = [email protected]";

$headers = "From: [email protected]";

mail("[email protected]", "Testing", $message, $headers);
echo "Check your email now....&lt;BR/>";
?>

or, for more details, read on.

How does Django's Meta class work?

Class Meta is the place in your code logic where your model.fields MEET With your form.widgets. So under Class Meta() you create the link between your model' fields and the different widgets you want to have in your form.

How do I apply a style to all children of an element

Instead of the * selector you can use the :not(selector) with the > selector and set something that definitely wont be a child.

Edit: I thought it would be faster but it turns out I was wrong. Disregard.

Example:

.container > :not(marquee){
        color:red;
    }


<div class="container">
    <p></p>
    <span></span>
<div>

How to create a popup windows in javafx

Have you looked into ControlsFx Popover control.


import org.controlsfx.control.PopOver;
import org.controlsfx.control.PopOver.ArrowLocation;

private PopOver item;

final Scene scene = addItemButton.getScene();

final Point2D windowCoord = new Point2D(scene.getWindow()
        .getX(), scene.getWindow().getY());

final Point2D sceneCoord = new Point2D(scene.getX(), scene.
                getY());

final Point2D nodeCoord = addItemButton.localToScene(0.0,
                        0.0);
final double clickX = Math.round(windowCoord.getX()
    + sceneCoord.getY() + nodeCoord.getX());

final double clickY = Math.round(windowCoord.getY()
        + sceneCoord.getY() + nodeCoord.getY());
item.setContentNode(addItemScreen);
item.setArrowLocation(ArrowLocation.BOTTOM_LEFT);
item.setCornerRadius(4);                            
item.setDetachedTitle("Add New Item");
item.show(addItemButton.getParent(), clickX, clickY);

This is only an example but a PopOver sounds like it could accomplish what you want. Check out the documentation for more info.

Important note: ControlsFX will only work on JavaFX 8.0 b118 or later.

How to install Selenium WebDriver on Mac OS

To use the java -jar selenium-server-standalone-2.45.0.jar command-line tool you need to install a JDK. You need to download and install the JDK and the standalone selenium server.

How to get first and last day of the current week in JavaScript

krtek's method has some wrong,I tested this

var startDay = 0; 
var weekStart = new Date(today.getDate() - (7 + today.getDay() - startDay) % 7);
var weekEnd = new Date(today.getDate() + (6 - today.getDay() - startDay) % 7);

it works

How do I filter date range in DataTables?

Here is my solution, there is no way to use momemt.js.Here is DataTable with Two DatePickers for DateRange (To and From) Filter.

$.fn.dataTable.ext.search.push(
  function (settings, data, dataIndex) {
    var min = $('#min').datepicker("getDate");
    var max = $('#max').datepicker("getDate");
    var startDate = new Date(data[4]);
    if (min == null && max == null) { return true; }
    if (min == null && startDate <= max) { return true; }
    if (max == null && startDate >= min) { return true; }
    if (startDate <= max && startDate >= min) { return true; }
    return false;
  }
);
  

    

How to format a java.sql Timestamp for displaying?

Use String.format (or java.util.Formatter):

Timestamp timestamp = ...
String.format("%1$TD %1$TT", timestamp)

EDIT:
please see the documentation of Formatter to know what TD and TT means: click on java.util.Formatter

The first 'T' stands for:

't', 'T'    date/time   Prefix for date and time conversion characters.

and the character following that 'T':

'T'     Time formatted for the 24-hour clock as "%tH:%tM:%tS".
'D'     Date formatted as "%tm/%td/%ty". 

How to get the height of a body element

$(document).height() seems to do the trick and gives the total height including the area which is only visible through scrolling.

Conditionally formatting cells if their value equals any value of another column

Another simpler solution is to use this formula in the conditional formatting (apply to column A):

=COUNTIF(B:B,A1)

Regards!

Flexbox and Internet Explorer 11 (display:flex in <html>?)

According to http://caniuse.com/#feat=flexbox:

"IE10 and IE11 default values for flex are 0 0 auto rather than 0 1 auto, as per the draft spec, as of September 2013"

So in plain words, if somewhere in your CSS you have something like this: flex:1 , that is not translated the same way in all browsers. Try changing it to 1 0 0 and I believe you will immediately see that it -kinda- works.

The problem is that this solution will probably mess up firefox, but then you can use some hacks to target only Mozilla and change it back:

@-moz-document url-prefix() {
 #flexible-content{
      flex: 1;
    }
}

Since flexbox is a W3C Candidate and not official, browsers tend to give different results, but I guess that will change in the immediate future.

If someone has a better answer I would like to know!

Click through div to underlying elements

Nope, you can't click ‘through’ an element. You can get the co-ordinates of the click and try to work out what element was underneath the clicked element, but this is really tedious for browsers that don't have document.elementFromPoint. Then you still have to emulate the default action of clicking, which isn't necessarily trivial depending on what elements you have under there.

Since you've got a fully-transparent window area, you'll probably be better off implementing it as separate border elements around the outside, leaving the centre area free of obstruction so you can really just click straight through.

How to use HTTP GET in PowerShell?

Downloading Wget is not necessary; the .NET Framework has web client classes built in.

$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")

How to clear a chart from a canvas so that hover events cannot be triggered?

I couldn't get .destroy() to work either so this is what I'm doing. The chart_parent div is where I want the canvas to show up. I need the canvas to resize each time, so this answer is an extension of the above one.

HTML:

<div class="main_section" > <div id="chart_parent"></div> <div id="legend"></div> </div>

JQuery:

  $('#chart').remove(); // this is my <canvas> element
  $('#chart_parent').append('<label for = "chart">Total<br /><canvas class="chart" id="chart" width='+$('#chart_parent').width()+'><canvas></label>');

Get size of an Iterable in Java

Strictly speaking, Iterable does not have size. Think data structure like a cycle.

And think about following Iterable instance, No size:

    new Iterable(){

        @Override public Iterator iterator() {
            return new Iterator(){

                @Override
                public boolean hasNext() {
                    return isExternalSystemAvailble();
                }

                @Override
                public Object next() {
                    return fetchDataFromExternalSystem();
                }};
        }};

Simple UDP example to send and receive data from same socket

I'll try to keep this short, I've done this a few months ago for a game I was trying to build, it does a UDP "Client-Server" connection that acts like TCP, you can send (message) (message + object) using this. I've done some testing with it and it works just fine, feel free to modify it if needed.

How to implement class constants?

Constants can be declare outside of classes and use within your class. Otherwise the get property is a nice workaround

const MY_CONSTANT: string = "wazzup";

export class MyClass {

    public myFunction() {

        alert(MY_CONSTANT);
    }
}

Getting file names without extensions

Path.GetFileNameWithoutExtension(file);

This returns the file name only without the extension type. You can also change it so you get both name and the type of file

 Path.GetFileName(FileName);

source:https://msdn.microsoft.com/en-us/library/system.io.path(v=vs.110).aspx

How to clear react-native cache?

You can clean cache in React Native >= 0.50 and npm > 5 :

watchman watch-del-all && 
rm -rf $TMPDIR/react-native-packager-cache-* &&
rm -rf $TMPDIR/metro-bundler-cache-* && 
rm -rf node_modules/ 
&& npm cache clean --force &&
npm install && 
npm start -- --reset-cache

Apart from cleaning npm cache you might need to reset simulator or clean build etc.

After installing with pip, "jupyter: command not found"

On Mac OS you need to export ~/.local/bin inside your $PATH variable.

# Edit the bash profile:
$ vim ~/.bash_profile

# Add this line inside ~/.bash_profile:
export PATH=$PATH:~/.local/bin

# Update the source:
$ source ~/.bash_profile

# Open Jupyter:
$ jupyter notebook

Insert Picture into SQL Server 2005 Image Field using only SQL

I achieved the goal where I have multiple images to insert in the DB as

INSERT INTO [dbo].[User]
           ([Name]
           ,[Image1]
           ,[Age]
           ,[Image2]
           ,[GroupId]
           ,[GroupName])
           VALUES
           ('Umar'
           , (SELECT BulkColumn 
            FROM Openrowset( Bulk 'path-to-file.jpg', Single_Blob) as Image1)
           ,26
           ,(SELECT BulkColumn 
            FROM Openrowset( Bulk 'path-to-file.jpg', Single_Blob) as Image2)
            ,'Group123'
           ,'GroupABC')

Jquery find nearest matching element

closest() only looks for parents, I'm guessing what you really want is .find()

$(this).closest('.row').children('.column').find('.inputQty').val();

What is the purpose of a self executing function in javascript?

Is there a parameter and the "Bunch of code" returns a function?

var a = function(x) { return function() { document.write(x); } }(something);

Closure. The value of something gets used by the function assigned to a. something could have some varying value (for loop) and every time a has a new function.

How to return multiple values?

You can return an object of a Class in Java.

If you are returning more than 1 value that are related, then it makes sense to encapsulate them into a class and then return an object of that class.

If you want to return unrelated values, then you can use Java's built-in container classes like Map, List, Set etc. Check the java.util package's JavaDoc for more details.

ASP.Net MVC - Read File from HttpPostedFileBase without save

byte[] data; using(Stream inputStream=file.InputStream) { MemoryStream memoryStream = inputStream as MemoryStream; if (memoryStream == null) { memoryStream = new MemoryStream(); inputStream.CopyTo(memoryStream); } data = memoryStream.ToArray(); }

JPG vs. JPEG image formats

They are identical. JPG is simply a holdover from the days of DOS when file extensions were required to be 3 characters long. You can find out more information about the JPEG standard here. A question very similar to this one was asked over at SuperUser, where the accepted answer should give you some more detailed information.

Replacement for "rename" in dplyr

It is not listed as a function in dplyr (yet): http://cran.rstudio.org/web/packages/dplyr/dplyr.pdf

The function below works (almost) the same if you don't want to load both plyr and dplyr

rename <- function(dat, oldnames, newnames) {
  datnames <- colnames(dat)
  datnames[which(datnames %in% oldnames)] <- newnames
  colnames(dat) <- datnames
  dat
}

dat <- rename(mtcars,c("mpg","cyl"), c("mympg","mycyl"))
head(dat)

                  mympg mycyl disp  hp drat    wt  qsec vs am gear carb
Mazda RX4          21.0     6  160 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag      21.0     6  160 110 3.90 2.875 17.02  0  1    4    4
Datsun 710         22.8     4  108  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive     21.4     6  258 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout  18.7     8  360 175 3.15 3.440 17.02  0  0    3    2
Valiant            18.1     6  225 105 2.76 3.460 20.22  1  0    3    1

Edit: The comment by Romain produces the following (note that the changes function requires dplyr .1.1)

> dplyr:::changes(mtcars, dat)
Changed variables:
          old         new        
disp      0x108b4b0e0 0x108b4e370
hp        0x108b4b210 0x108b4e4a0
drat      0x108b4b340 0x108b4e5d0
wt        0x108b4b470 0x108b4e700
qsec      0x108b4b5a0 0x108b4e830
vs        0x108b4b6d0 0x108b4e960
am        0x108b4b800 0x108b4ea90
gear      0x108b4b930 0x108b4ebc0
carb      0x108b4ba60 0x108b4ecf0
mpg       0x1033ee7c0            
cyl       0x10331d3d0            
mympg                 0x108b4e110
mycyl                 0x108b4e240

Changed attributes:
          old         new        
names     0x10c100558 0x10c2ea3f0
row.names 0x108b4bb90 0x108b4ee20
class     0x103bd8988 0x103bd8f58

Easiest way to toggle 2 classes in jQuery

Your onClick request:

<span class="A" onclick="var state = this.className.indexOf('A') > -1; $(this).toggleClass('A', !state).toggleClass('B', state);">Click Me</span>

Try it: https://jsfiddle.net/v15q6b5y/


Just the JS à la jQuery:

$('.selector').toggleClass('A', !state).toggleClass('B', state);

How to use _CRT_SECURE_NO_WARNINGS

I was getting the same error in Visual Studio 2017 and to fix it just added #define _CRT_SECURE_NO_WARNINGS after #include "pch.h"

#include "pch.h"
#define _CRT_SECURE_NO_WARNINGS
....

Best way to store chat messages in a database?

If you can avoid the need for concurrent writes to a single file, it sounds like you do not need a database to store the chat messages.

Just append the conversation to a text file (1 file per user\conversation). and have a directory/ file structure

Here's a simplified view of the file structure:

chat-1-bob.txt
        201101011029, hi
        201101011030, fine thanks.

chat-1-jen.txt
        201101011030, how are you?
        201101011035, have you spoken to bill recently?

chat-2-bob.txt
        201101021200, hi
        201101021222, about 12:22
chat-2-bill.txt
        201101021201, Hey Bob,
        201101021203, what time do you call this?

You would then only need to store the userid, conversation id (guid ?) & a reference to the file name.

I think you will find it hard to get a more simple scaleable solution.

You can use LOAD_FILE to get the data too see: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html

If you have a requirement to rebuild a conversation you will need to put a value (date time) alongside your sent chat message (in the file) to allow you to merge & sort the files, but at this point it is probably a good idea to consider using a database.

Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

If android:largeHeap="true" didn't work for you then

1:

Image Compression. I am using this website

2:

Convert images to mdpi,hdpi, xhdpi, xxhdpi, xxxhdpi. I am using this webiste

Don't remove android:largeHeap="true"!

javascript : sending custom parameters with window.open() but its not working

To concatenate strings, use the + operator.

To insert data into a URI, encode it for URIs.

Bad:

var url = "http://localhost:8080/login?cid='username'&pwd='password'"

Good:

var url_safe_username = encodeURIComponent(username);
var url_safe_password = encodeURIComponent(password);
var url = "http://localhost:8080/login?cid=" + url_safe_username + "&pwd=" + url_safe_password;

The server will have to process the query string to make use of the data. You can't assign to arbitrary form fields.

… but don't trigger new windows or pass credentials in the URI (where they are exposed to over the shoulder attacks and may be logged).

What is the point of WORKDIR on Dockerfile?

You can think of WORKDIR like a cd inside the container (it affects commands that come later in the Dockerfile, like the RUN command). If you removed WORKDIR in your example above, RUN npm install wouldn't work because you would not be in the /usr/src/app directory inside your container.

I don't see how this would be related to where you put your Dockerfile (since your Dockerfile location on the host machine has nothing to do with the pwd inside the container). You can put the Dockerfile wherever you'd like in your project. However, the first argument to COPY is a relative path, so if you move your Dockerfile you may need to update those COPY commands.

How can I check if a View exists in a Database?

For people checking the existence to drop View use this

From SQL Server 2016 CTP3 you can use new DIE statements instead of big IF wrappers

syntax

DROP VIEW [ IF EXISTS ] [ schema_name . ] view_name [ ...,n ] [ ; ]

Query :

DROP VIEW IF EXISTS view_name

More info here

Insert HTML with React Variable Statements (JSX)

You can use dangerouslySetInnerHTML, e.g.

render: function() {
    return (
        <div className="content" dangerouslySetInnerHTML={{__html: thisIsMyCopy}}></div>
    );
}

AJAX cross domain call

I faced the same problem during 2 days and I found the solution, and it's elegant after googling a lot. I needed xss Ajax for some widget clients which pull datastream from tiers websites to my Rails app. here's how I did.

How do I add more members to my ENUM-type column in MySQL?

It's possible if you believe. Hehe. try this code.

public function add_new_enum($new_value)
  {
    $table="product";
    $column="category";
         $row = $this->db->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_NAME = ? AND COLUMN_NAME = ?", array($table, $column))->row_array();

    $old_category = array();
    $new_category="";
    foreach (explode(',', str_replace("'", '', substr($row['COLUMN_TYPE'], 5, (strlen($row['COLUMN_TYPE']) - 6)))) as $val)
    {
        //getting the old category first

        $old_category[$val] = $val;
        $new_category.="'".$old_category[$val]."'".",";
    }

     //after the end of foreach, add the $new_value to $new_category

      $new_category.="'".$new_value."'";

    //Then alter the table column with the new enum

    $this->db->query("ALTER TABLE product CHANGE category category ENUM($new_category)");
  }

Before adding new value

After adding new value

Call to undefined function oci_connect()

I installed WAMPServer 2.5 (32-bit) and also encountered an oci_connect error. I also had Oracle 11g client (32-bit) installed. The common fix I read in other posts was to alter the php.ini file in your C:\wamp\bin\php\php5.5.12 directory, however this never worked for me. Maybe I misunderstood, but I found that if you alter the php.ini file in the C:\wamp\bin\apache\apache2.4.9 directory instead, you will get the results you want. The only thing I altered in the apache php.ini file was remove the semicolon to extension=php_oci8_11g.dll in order to enable it. I then restarted all the services and it now works! I hope this works for you.

How do I use this JavaScript variable in HTML?

A good place to start learning how to manipulate pages s the Mozilla Developer Network, they've got a great tutorial about the DOM.

One way you could do it is with document.write, which writes html at the end of the currently loaded part of the document - in this case, after the script tag.

<script>
  var name = prompt("What's your name?");
  document.write("<p>" + name.length + "</p>");
</script>

But it's not a very clean way of doing it. Keep document.write for testing purpose because in most cases you can't predict where it will append the content.

EDIT: Here, the "clever" way would be to do something like this:

<script type="text/javascript">
  window.addEventListener("load", function(e) {
    var name = prompt("What's your name?") || "";
    var text = document.createTextNode(name.length);
    document.getElementById("nameLength").appendChild(text);
  });
</script>
<p id="nameLength"></p>

But people are generally lazy and you'll often see .innerHTML = "something" instead of a text node.

How to use ng-repeat without an html element

As of AngularJS 1.2 there's a directive called ng-repeat-start that does exactly what you ask for. See my answer in this question for a description of how to use it.

How to send HTTP request in java?

You can use java.net.HttpUrlConnection.

Example (from here), with improvements. Included in case of link rot:

public static String executePost(String targetURL, String urlParameters) {
  HttpURLConnection connection = null;

  try {
    //Create connection
    URL url = new URL(targetURL);
    connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", 
        "application/x-www-form-urlencoded");

    connection.setRequestProperty("Content-Length", 
        Integer.toString(urlParameters.getBytes().length));
    connection.setRequestProperty("Content-Language", "en-US");  

    connection.setUseCaches(false);
    connection.setDoOutput(true);

    //Send request
    DataOutputStream wr = new DataOutputStream (
        connection.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.close();

    //Get Response  
    InputStream is = connection.getInputStream();
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
    String line;
    while ((line = rd.readLine()) != null) {
      response.append(line);
      response.append('\r');
    }
    rd.close();
    return response.toString();
  } catch (Exception e) {
    e.printStackTrace();
    return null;
  } finally {
    if (connection != null) {
      connection.disconnect();
    }
  }
}

How to overlay density plots in R?

use lines for the second one:

plot(density(MyData$Column1))
lines(density(MyData$Column2))

make sure the limits of the first plot are suitable, though.

How to concatenate strings of a string field in a PostgreSQL 'group by' query?

According to version PostgreSQL 9.0 and above you can use the aggregate function called string_agg. Your new SQL should look something like this:

SELECT company_id, string_agg(employee, ', ')
    FROM mytable GROUP BY company_id;

Checking if a key exists in a JavaScript object?

We can use - hasOwnProperty.call(obj, key);

The underscore.js way -

if(_.has(this.options, 'login')){
  //key 'login' exists in this.options 
}

_.has = function(obj, key) {
  return hasOwnProperty.call(obj, key);
};

ASP.NET: HTTP Error 500.19 – Internal Server Error 0x8007000d

When trying to set up a .NET Core 1.0 website I got this error, and tried everything else I could find with no luck, including checking the web.config file, IIS_IUSRS permissions, IIS URL rewrite module, etc. In the end, I installed DotNetCore.1.0.0-WindowsHosting.exe from this page: https://www.microsoft.com/net/download and it started working right away.

Specific link to download: https://go.microsoft.com/fwlink/?LinkId=817246

How do I read the file content from the Internal storage - Android App

To read a file from internal storage:

Call openFileInput() and pass it the name of the file to read. This returns a FileInputStream. Read bytes from the file with read(). Then close the stream with close().

code::

StringBuilder sb = new StringBuilder();
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            is.close();
        } catch(OutOfMemoryError om){
            om.printStackTrace();
        } catch(Exception ex){
            ex.printStackTrace();
        }
        String result = sb.toString();

How can I query for null values in entity framework?

I'm not able to comment divega's post, but among the different solutions presented here, divega's solution produces the best SQL. Both performance wise and length wise. I just checked with SQL Server Profiler and by looking at the execution plan (with "SET STATISTICS PROFILE ON").

System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

I had this issue with a WinForms Project using VS 2015. My solution was:

  1. right click the Project
  2. select properties
  3. check "Prefer 32-bit"
  4. Platform target: Any CPU

SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

I might have read all questions about this for two days. None of the answers worked for me.

In my case I was lacking cURL module for PHP.

Be aware that, just because you can use cURL on terminal, it does not mean that you have PHP cURL module and it is active. There was no error showing about it. Not even on /var/log/apache2/error.log

How to install module: (replace version number for the apropiated one)

sudo apt install php7.2-curl
sudo service apache2 reload

How to apply multiple transforms in CSS?

You can also apply multiple transforms using an extra layer of markup e.g.:

<h3 class="rotated-heading">
    <span class="scaled-up">Hey!</span>
</h3>
<style type="text/css">
.rotated-heading
{
    transform: rotate(10deg);
}

.scaled-up
{
    transform: scale(1.5);
}
</style>

This can be really useful when animating elements with transforms using Javascript.

adb command not found in linux environment

I found the solution to my problem. In my ~/.bashrc:

export PATH=${PATH}:/path/to/android-sdk/tools

However adb is not located in the android-sdk/tools/, rather in android-sdk/platform-tools/. So I added the following

export PATH=${PATH}:/path/to/android-sdk/tools:/path/to/android-sdk/platform-tools

And that solved the problem for me.

Get enum values as List of String in Java 8

You could also do something as follow

public enum DAY {MON, TUES, WED, THU, FRI, SAT, SUN};
EnumSet.allOf(DAY.class).stream().map(e -> e.name()).collect(Collectors.toList())

or

EnumSet.allOf(DAY.class).stream().map(DAY::name).collect(Collectors.toList())

The main reason why I stumbled across this question is that I wanted to write a generic validator that validates whether a given string enum name is valid for a given enum type (Sharing in case anyone finds useful).

For the validation, I had to use Apache's EnumUtils library since the type of enum is not known at compile time.

@SuppressWarnings({ "unchecked", "rawtypes" })
public static void isValidEnumsValid(Class clazz, Set<String> enumNames) {
    Set<String> notAllowedNames = enumNames.stream()
            .filter(enumName -> !EnumUtils.isValidEnum(clazz, enumName))
            .collect(Collectors.toSet());

    if (notAllowedNames.size() > 0) {
        String validEnumNames = (String) EnumUtils.getEnumMap(clazz).keySet().stream()
            .collect(Collectors.joining(", "));

        throw new IllegalArgumentException("The requested values '" + notAllowedNames.stream()
                .collect(Collectors.joining(",")) + "' are not valid. Please select one more (case-sensitive) "
                + "of the following : " + validEnumNames);
    }
}

I was too lazy to write an enum annotation validator as shown in here https://stackoverflow.com/a/51109419/1225551

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

I solved this by assigning a ref to the component and then checking if the ref exists before setting the state:

myMethod(){
  if (this.refs.myRef) 
   this.setState({myVar: true});
}

render() {
  return (
    <div ref="myRef">
      {this.state.myVar}
    </div>
  );
}

And lately, since I am using mostly functional components, I am using this pattern:

const Component = () => {
  const ref = React.useRef(null);
  const [count, setCount] = React.useState(0);

  const increment = () => {
    setTimeout(() => { // usually fetching API data here
      if (ref.current !== null) {
        setCount((count) => count + 1);
      }
    }, 100);
  };

  return (
    <button onClick={increment} ref={ref}>
      Async Increment {count}
    </button>
  );
};