Programs & Examples On #To char

ORACLE convert number to string

Using the FM format model modifier to get close, as you won't get the trailing zeros after the decimal separator; but you will still get the separator itself, e.g. 50.. You can use rtrim to get rid of that:

select to_char(a, '99D90'),
    to_char(a, '90D90'),
    to_char(a, 'FM90D99'),
    rtrim(to_char(a, 'FM90D99'), to_char(0, 'D'))
from (
    select 50 a from dual
    union all select 50.57 from dual
    union all select 5.57 from dual
    union all select 0.35 from dual
    union all select 0.4 from dual
)
order by a;

TO_CHA TO_CHA TO_CHA RTRIM(
------ ------ ------ ------
   .35   0.35 0.35   0.35
   .40   0.40 0.4    0.4
  5.57   5.57 5.57   5.57
 50.00  50.00 50.    50
 50.57  50.57 50.57  50.57

Note that I'm using to_char(0, 'D') to generate the character to trim, to match the decimal separator - so it looks for the same character, , or ., as the first to_char adds.

The slight downside is that you lose the alignment. If this is being used elsewhere it might not matter, but it does then you can also wrap it in an lpad, which starts to make it look a bit complicated:

...
lpad(rtrim(to_char(a, 'FM90D99'), to_char(0, 'D')), 6)
...

TO_CHA TO_CHA TO_CHA RTRIM( LPAD(RTRIM(TO_CHAR(A,'FM
------ ------ ------ ------ ------------------------
   .35   0.35 0.35   0.35     0.35
   .40   0.40 0.4    0.4       0.4
  5.57   5.57 5.57   5.57     5.57
 50.00  50.00 50.    50         50
 50.57  50.57 50.57  50.57   50.57

SQL Server - Create a copy of a database table and place it in the same database?

Use SELECT ... INTO:

SELECT *
INTO ABC_1
FROM ABC;

This will create a new table ABC_1 that has the same column structure as ABC and contains the same data. Constraints (e.g. keys, default values), however, are -not- copied.

You can run this query multiple times with a different table name each time.


If you don't need to copy the data, only to create a new empty table with the same column structure, add a WHERE clause with a falsy expression:

SELECT *
INTO ABC_1
FROM ABC
WHERE 1 <> 1;

Javascript equivalent of php's strtotime()?

I jealous the strtotime() in php, but I do mine in javascript using moment. Not as sweet as that from php, but does the trick neatly too.

// first day of the month
var firstDayThisMonth = moment(firstDayThisMonth).startOf('month').toDate();

Go back and forth using the subtract() and add() with the endOf() and startOf():

// last day of previous month
var yesterMonthLastDay = moment(yesterMonthLastDay).subtract(1,'months').endOf('month').toDate();

Determine if Android app is being used for the first time

Hi guys I am doing something like this. And its works for me

create a Boolean field in shared preference.Default value is true {isFirstTime:true} after first time set it to false. Nothing can be simple and relaiable than this in android system.

scrollIntoView Scrolls just too far

For an element in a table row, use JQuery to get the row above the one you want, and simply scroll to that row instead.

Suppose I have multiple rows in a table, some of which should be reviewed by and admin. Each row requiring review has both and up and a down arrow to take you to the previous or next item for review.

Here's a complete example that should just run if you make a new HTML document in notepad and save it. There's extra code to detect the top and bottom of our items for review so we don't throw any errors.

<html>
<head>
    <title>Scrolling Into View</title>
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <style>
        div.scroll { height: 6em; width: 20em; overflow: auto; }
        thead th   { position: sticky; top: -1px; background: #fff; }
        .up, .down { cursor: pointer; }
        .up:hover, .down:hover { color: blue; text-decoration:underline; }
    </style>
</head>
<body>
<div class='scroll'>
<table border='1'>
    <thead>
        <tr>
            <th>Review</th>
            <th>Data</th>
        </tr>
    </thead>
    <tbody>
        <tr id='row_1'>
            <th></th>
            <td>Row 1 (OK)</td>
        </tr>
        <tr id='row_2'>
            <th></th>
            <td>Row 2 (OK)</td>
        </tr>
        <tr id='row_3'>
            <th id='jump_1'><span class='up'>UP</span> <span class='down'>DN</span></th>
            <td>Row 3 (REVIEW)</td>
        </tr>
        <tr id='row_4'>
            <th></th>
            <td>Row 4 (OK)</td>
        </tr>
        <tr id='row_5'>
            <th id='jump_2'><span class='up'>UP</span> <span class='down'>DN</span></th>
            <td>Row 5 (REVIEW)</td>
        </tr>
        <tr id='row_6'>
            <th></th>
            <td>Row 6 (OK)</td>
        </tr>
        <tr id='row_7'>
            <th></th>
            <td>Row 7 (OK)</td>
        </tr>
        <tr id='row_8'>
            <th id='jump_3'><span class='up'>UP</span> <span class='down'>DN</span></th>
            <td>Row 8 (REVIEW)</td>
        </tr>
        <tr id='row_9'>
            <th></th>
            <td>Row 9 (OK)</td>
        </tr>
        <tr id='row_10'>
            <th></th>
            <td>Row 10 (OK)</td>
        </tr>
    </tbody>
</table>
</div>
<script>
$(document).ready( function() {
    $('.up').on('click', function() {
        var id = parseInt($(this).parent().attr('id').split('_')[1]);
        if (id>1) {
            var row_id = $('#jump_' + (id - 1)).parent().attr('id').split('_')[1];
            document.getElementById('row_' + (row_id-1)).scrollIntoView({behavior: 'smooth', block: 'start'});
        } else {
            alert('At first');
        }
    });

    $('.down').on('click', function() {
        var id = parseInt($(this).parent().attr('id').split('_')[1]);
        if ($('#jump_' + (id + 1)).length) {
            var row_id = $('#jump_' + (id + 1)).parent().attr('id').split('_')[1];
            document.getElementById('row_' + (row_id-1)).scrollIntoView({behavior: 'smooth', block: 'start'});
        } else {
            alert('At last');
        }
    });
});
</script>
</body>
</html>

What is the right way to check for a null string in Objective-C?

if(textfield.text.length == 0){
   //do your desired work
}

Best way to handle list.index(might-not-exist) in python?

I have the same issue with the ".index()" method on lists. I have no issue with the fact that it throws an exception but I strongly disagree with the fact that it's a non-descriptive ValueError. I could understand if it would've been an IndexError, though.

I can see why returning "-1" would be an issue too because it's a valid index in Python. But realistically, I never expect a ".index()" method to return a negative number.

Here goes a one liner (ok, it's a rather long line ...), goes through the list exactly once and returns "None" if the item isn't found. It would be trivial to rewrite it to return -1, should you so desire.

indexOf = lambda list, thing: \
            reduce(lambda acc, (idx, elem): \
                   idx if (acc is None) and elem == thing else acc, list, None)

How to use:

>>> indexOf([1,2,3], 4)
>>>
>>> indexOf([1,2,3], 1)
0
>>>

error: expected class-name before ‘{’ token

If you forward-declare Flight and Landing in Event.h, then you should be fixed.

Remember to #include "Flight.h" and #include "Landing.h" in your implementation file for Event.

The general rule of thumb is: if you derive from it, or compose from it, or use it by value, the compiler must know its full definition at the time of declaration. If you compose from a pointer-to-it, the compiler will know how big a pointer is. Similarly, if you pass a reference to it, the compiler will know how big the reference is, too.

Add a Progress Bar in WebView

I have added few lines in your code and now its working fine with progress bar.

        getWindow().requestFeature(Window.FEATURE_PROGRESS);
        setContentView(R.layout.main );
        // Makes Progress bar Visible
        getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);

        webview = (WebView) findViewById(R.id.webview);
        webview.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress)   
            {
                //Make the bar disappear after URL is loaded, and changes string to Loading...
                setTitle("Loading...");
                setProgress(progress * 100); //Make the bar disappear after URL is loaded
     
                // Return the app name after finish loading
                if(progress == 100)
                   setTitle(R.string.app_name);
                }
            });
        webview.setWebViewClient(new HelloWebViewClient());
        webview.getSettings().setJavaScriptEnabled(true);
        webview.loadUrl("http://www.google.com");

How does Task<int> become an int?

No requires converting the Task to int. Simply Use The Task Result.

int taskResult = AccessTheWebAndDouble().Result;

public async Task<int> AccessTheWebAndDouble()
{
    int task = AccessTheWeb();
    return task;
}

It will return the value if available otherwise it return 0.

PyCharm shows unresolved references error for valid code

I finally got this working after none of the proposed solutions worked for me. I was playing with a django rest framework project and was using a virtualenv I had setup with it. I was able to get Pycharm fixed by marking the root folder as the sources root, but then django's server would throw resolve exceptions. So one would work when the other wouldn't and vice versa.

Ultimately I just had to mark the subfolder as the sources root in pycharm. So my structure was like this

-playground
     -env
     -playground

That second playground folder is the one I had to mark as the sources root for everything to work as expected. That didn't present any issues for my scenario so it was a workable solution.

Just thought I'd share in case someone else can use it.

pass post data with window.location.href

Use this file : "jquery.redirect.js"

$("#btn_id").click(function(){
    $.redirect(http://localhost/test/test1.php,
        {
            user_name: "khan",
            city : "Meerut",
            country : "country"
        });
    });
});

see https://github.com/mgalante/jquery.redirect

How to get values from IGrouping

Since IGrouping<TKey, TElement> implements IEnumerable<TElement>, you can use SelectMany to put all the IEnumerables back into one IEnumerable all together:

List<smth> list = new List<smth>();
IEnumerable<IGrouping<int, smth>> groups = list.GroupBy(x => x.id);
IEnumerable<smth> smths = groups.SelectMany(group => group);
List<smth> newList = smths.ToList();

Here's an example that builds/runs: https://dotnetfiddle.net/DyuaaP

Video commentary of this solution: https://youtu.be/6BsU1n1KTdo

Image inside div has extra space below the image

One can also nullify parent's line height:

#wrapper {
  line-height: 0;
}

All fixes: http://jsfiddle.net/FaPFv/

How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?

To complement the version of Leo Dabus, I added support for projects written Swift and Objective-C, also added support for the optional milliseconds, probably isn't the best but you would get the point:

Xcode 8 and Swift 3

extension Date {
    struct Formatter {
        static let iso8601: DateFormatter = {
            let formatter = DateFormatter()
            formatter.calendar = Calendar(identifier: .iso8601)
            formatter.locale = Locale(identifier: "en_US_POSIX")
            formatter.timeZone = TimeZone(secondsFromGMT: 0)
            formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
            return formatter
        }()
    }

    var iso8601: String {
        return Formatter.iso8601.string(from: self)
    }
}


extension String {
    var dateFromISO8601: Date? {
        var data = self
        if self.range(of: ".") == nil {
            // Case where the string doesn't contain the optional milliseconds
            data = data.replacingOccurrences(of: "Z", with: ".000000Z")
        }
        return Date.Formatter.iso8601.date(from: data)
    }
}


extension NSString {
    var dateFromISO8601: Date? {
        return (self as String).dateFromISO8601
    }
}

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I couldn't find an off-the-shelf module that added this function, so I wrote one:

In Access, go to the Database Tools ribbon, in the Macro area click into Visual Basic. In the top left Project area, right click the name of your file and select Insert -> Module. In the module paste this:

Public Function Substring_Index(strWord As String, strDelim As String, intCount As Integer) As String

Substring_Index = delims

start = 0
test = ""

For i = 1 To intCount
    oldstart = start + 1
    start = InStr(oldstart, strWord, strDelim)
    Substring_Index = Mid(strWord, oldstart, start - oldstart)
Next i

End Function

Save the module as module1 (the default). You can now use statements like:

SELECT Substring_Index([fieldname],",",2) FROM table

Visual Studio 2015 installer hangs during install?

Well, I cant find any SecondaryInstaller.exe to stop in task manager and even I dont have any AV rather then Windows Defender so I found something else..
I stopped windows Update from elevated cmd by writing command net stop muauserv and it worked for me...
The update will Retry again for KB2664825 so run the code again in cmd..(because the service starts automatically)

Keep trying and its done for me...!!

How do I get AWS_ACCESS_KEY_ID for Amazon?

Amazon changes the admin console from time to time, hence the previous answers above are irrelevant in 2020.

The way to get the secret access key (Oct.2020) is:

  1. go to IAM console: https://console.aws.amazon.com/iam
  2. click on "Users". (see image) enter image description here
  3. go to the user you need his access key. enter image description here

As i see the answers above, I can assume my answer will become irrelevant in a year max :-)

HTH

Vuex - passing multiple parameters to mutation

In simple terms you need to build your payload into a key array

payload = {'key1': 'value1', 'key2': 'value2'}

Then send the payload directly to the action

this.$store.dispatch('yourAction', payload)

No change in your action

yourAction: ({commit}, payload) => {
  commit('YOUR_MUTATION',  payload )
},

In your mutation call the values with the key

'YOUR_MUTATION' (state,  payload ){
  state.state1 = payload.key1
  state.state2 =  payload.key2
},

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

The accounts property is defined like this:

"accounts":{"github":"sergiotapia"}

Your POCO states this:

public List<Account> Accounts { get; set; }

Try using this Json:

"accounts":[{"github":"sergiotapia"}]

An array of items (which is going to be mapped to the list) is always enclosed in square brackets.

Edit: The Account Poco will be something like this:

class Account {
    public string github { get; set; }
}

and maybe other properties.

Edit 2: To not have an array use the property as follows:

public Account Accounts { get; set; }

with something like the sample class I've posted in the first edit.

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

This one uses the defineProperty with a nice side-effect causing global variable!

_x000D_
_x000D_
var _a = 1_x000D_
_x000D_
Object.defineProperty(this, "a", {_x000D_
  "get": () => {_x000D_
    return _a++;_x000D_
  },_x000D_
  configurable: true_x000D_
});_x000D_
_x000D_
console.log(a)_x000D_
console.log(a)_x000D_
console.log(a)
_x000D_
_x000D_
_x000D_

Converting a Java Keystore into PEM Format

Try Keystore Explorer http://keystore-explorer.org/

KeyStore Explorer is an open source GUI replacement for the Java command-line utilities keytool and jarsigner. It does openssl/pkcs12 as well.

TimeStamp on file name using PowerShell

Here's some PowerShell code that should work. You can combine most of this into fewer lines, but I wanted to keep it clear and readable.

[string]$filePath = "C:\tempFile.zip";

[string]$directory = [System.IO.Path]::GetDirectoryName($filePath);
[string]$strippedFileName = [System.IO.Path]::GetFileNameWithoutExtension($filePath);
[string]$extension = [System.IO.Path]::GetExtension($filePath);
[string]$newFileName = $strippedFileName + [DateTime]::Now.ToString("yyyyMMdd-HHmmss") + $extension;
[string]$newFilePath = [System.IO.Path]::Combine($directory, $newFileName);

Move-Item -LiteralPath $filePath -Destination $newFilePath;

How can I change the version of npm using nvm?

By looking at www.npmjs.com/install.sh I found there is a way to install a specific version by setting an environment-variable

export npm_install="2.14.14"

Then run the download-script as described at npmjs.com:

curl -L https://www.npmjs.com/install.sh | sh

If you omit setting the npm_install variable, then it will install the the version they have marked as latest

Detect change to ngModel on a select tag (Angular 2)

Update:

Separate the event and property bindings:

<select [ngModel]="selectedItem" (ngModelChange)="onChange($event)">
onChange(newValue) {
    console.log(newValue);
    this.selectedItem = newValue;  // don't forget to update the model here
    // ... do other stuff here ...
}

You could also use

<select [(ngModel)]="selectedItem" (ngModelChange)="onChange($event)">

and then you wouldn't have to update the model in the event handler, but I believe this causes two events to fire, so it is probably less efficient.


Old answer, before they fixed a bug in beta.1:

Create a local template variable and attach a (change) event:

<select [(ngModel)]="selectedItem" #item (change)="onChange(item.value)">

plunker

See also How can I get new selection in "select" in Angular 2?

Importing a long list of constants to a Python file

Try to look Create constants using a "settings" module? and Can I prevent modifying an object in Python?

Another one useful link: http://code.activestate.com/recipes/65207-constants-in-python/ tells us about the following option:

from copy import deepcopy

class const(object):

    def __setattr__(self, name, value):
        if self.__dict__.has_key(name):
            print 'NO WAY this is a const' # put here anything you want(throw exc and etc)
            return deepcopy(self.__dict__[name])
        self.__dict__[name] = value

    def __getattr__(self, name, value):
        if self.__dict__.has_key(name):
            return deepcopy(self.__dict__[name])

    def __delattr__(self, item):
        if self.__dict__.has_key(item):
            print 'NOOOOO' # throw exception if needed

CONST = const()
CONST.Constant1 = 111
CONST.Constant1 = 12
print a.Constant1 # 111
CONST.Constant2 = 'tst'
CONST.Constant2 = 'tst1'
print a.Constant2 # 'tst'

So you could create a class like this and then import it from you contants.py module. This will allow you to be sure that value would not be changed, deleted.

How to launch jQuery Fancybox on page load?

In case if you don't have button to click. I mean if you want to open it on ajax response then it would be like this :

$.fancybox({
      href: '#ID',
      padding   : 23,
      maxWidth  : 690,
      maxHeight : 345
});

Remove blank attributes from an Object in Javascript

You can use a combination of JSON.stringify, its replacer parameter, and JSON.parse to turn it back into an object. Using this method also means the replacement is done to all nested keys within nested objects.

Example Object

var exampleObject = {
  string: 'value',
  emptyString: '',
  integer: 0,
  nullValue: null,
  array: [1, 2, 3],
  object: {
    string: 'value',
    emptyString: '',
    integer: 0,
    nullValue: null,
    array: [1, 2, 3]
  },
  arrayOfObjects: [
    {
      string: 'value',
      emptyString: '',
      integer: 0,
      nullValue: null,
      array: [1, 2, 3]
    },
    {
      string: 'value',
      emptyString: '',
      integer: 0,
      nullValue: null,
      array: [1, 2, 3]
    }
  ]
};

Replacer Function

function replaceUndefinedOrNull(key, value) {
  if (value === null || value === undefined) {
    return undefined;
  }

  return value;
}

Clean the Object

exampleObject = JSON.stringify(exampleObject, replaceUndefinedOrNull);
exampleObject = JSON.parse(exampleObject);

CodePen example

How to declare an array of objects in C#

I guess GameObject is a reference type. Default for reference types is null => you have an array of nulls.

You need to initialize each member of the array separatedly.

houses[0] = new GameObject(..);

Only then can you access the object without compilation errors.

So you can explicitly initalize the array:

for (int i = 0; i < houses.Length; i++)
{
    houses[i] = new GameObject();
}

or you can change GameObject to value type.

Trigger event on body load complete js/jquery

The windows.load function is useful if you want to do something when everything is loaded.

$(window).load(function(){
    // full load
});

But you can also use the .load function on any other element. So if you have one particularly large image and you want to do something when that loads but the rest of your page loading code when the dom has loaded you could do:

$(function(){
    // Dom loaded code

    $('#largeImage').load({
        // Image loaded code
    });
});

Also the jquery .load function is pretty much the same as a normal .onload.

Measuring execution time of a function in C++

  • It is a very easy to use method in C++11.
  • We can use std::chrono::high_resolution_clock from header
  • We can write a method to print the method execution time in a much readable form.

For example, to find the all the prime numbers between 1 and 100 million, it takes approximately 1 minute and 40 seconds. So the execution time get printed as:

Execution Time: 1 Minutes, 40 Seconds, 715 MicroSeconds, 715000 NanoSeconds

The code is here:

#include <iostream>
#include <chrono>

using namespace std;
using namespace std::chrono;

typedef high_resolution_clock Clock;
typedef Clock::time_point ClockTime;

void findPrime(long n, string file);
void printExecutionTime(ClockTime start_time, ClockTime end_time);

int main()
{
    long n = long(1E+8);  // N = 100 million

    ClockTime start_time = Clock::now();

    // Write all the prime numbers from 1 to N to the file "prime.txt"
    findPrime(n, "C:\\prime.txt"); 

    ClockTime end_time = Clock::now();

    printExecutionTime(start_time, end_time);
}

void printExecutionTime(ClockTime start_time, ClockTime end_time)
{
    auto execution_time_ns = duration_cast<nanoseconds>(end_time - start_time).count();
    auto execution_time_ms = duration_cast<microseconds>(end_time - start_time).count();
    auto execution_time_sec = duration_cast<seconds>(end_time - start_time).count();
    auto execution_time_min = duration_cast<minutes>(end_time - start_time).count();
    auto execution_time_hour = duration_cast<hours>(end_time - start_time).count();

    cout << "\nExecution Time: ";
    if(execution_time_hour > 0)
    cout << "" << execution_time_hour << " Hours, ";
    if(execution_time_min > 0)
    cout << "" << execution_time_min % 60 << " Minutes, ";
    if(execution_time_sec > 0)
    cout << "" << execution_time_sec % 60 << " Seconds, ";
    if(execution_time_ms > 0)
    cout << "" << execution_time_ms % long(1E+3) << " MicroSeconds, ";
    if(execution_time_ns > 0)
    cout << "" << execution_time_ns % long(1E+6) << " NanoSeconds, ";
}

Provisioning Profiles menu item missing from Xcode 5

For me, the refresh in xcode 5 prefs->accounts was doing nothing. At one point it showed me three profiles so I thought I was one refresh away, but after the next refresh it went back to just one profile, so I abandoned this method.

If anyone gets this far and is still struggling, here's what I did:

  1. Close xcode 5
  2. Open xcode 4.6.2
  3. Go to Window->Organizer->Provisioning Profiles
  4. Press Refresh arrow on bottom right

When I did this, everything synced up perfectly. It even told me what it was downloading each step of the way like good software does. After the sync completed, I closed xcode 4.6.2, re-opened xcode 5 and went to preferences->accounts and voila, all of my profiles are now available in xocde 5.

Custom style to jquery ui dialogs

You can specify a custom class to the top element of the dialog via the option dialogClass

$("#success").dialog({
    ...
    dialogClass:"myClass",
    ...
});

Then you can target this class in CSS via .myClass.ui-dialog.

What is an idempotent operation?

retry-safe.

Is usually the easiest way to understand its meaning in computer science.

How to delete all files older than 3 days when "Argument list too long"?

To delete all files and directories within the current directory:

find . -mtime +3 | xargs rm -Rf

Or alternatively, more in line with the OP's original command:

find . -mtime +3 -exec rm -Rf -- {} \;

Get week of year in JavaScript like in PHP

With Luxon (https://github.com/moment/luxon) :

import { DateTime } from 'luxon';
const week: number = DateTime.fromJSDate(new Date()).weekNumber;

Is it possible to convert char[] to char* in C?

You don't need to declare them as arrays if you want to use use them as pointers. You can simply reference pointers as if they were multi-dimensional arrays. Just create it as a pointer to a pointer and use malloc:

int i;
int M=30, N=25;
int ** buf;
buf = (int**) malloc(M * sizeof(int*));
for(i=0;i<M;i++)
    buf[i] = (int*) malloc(N * sizeof(int));

and then you can reference buf[3][5] or whatever.

Dynamically access object property using variable

Finding Object by reference without, strings, Note make sure the object you pass in is cloned , i use cloneDeep from lodash for that

if object looks like

const obj = {data: ['an Object',{person: {name: {first:'nick', last:'gray'} }]

path looks like

const objectPath = ['data',1,'person',name','last']

then call below method and it will return the sub object by path given

const child = findObjectByPath(obj, objectPath)
alert( child) // alerts "last"


const findObjectByPath = (objectIn: any, path: any[]) => {
    let obj = objectIn
    for (let i = 0; i <= path.length - 1; i++) {
        const item = path[i]
        // keep going up to the next parent
        obj = obj[item] // this is by reference
    }
    return obj
}

git: fatal: I don't handle protocol '??http'

I simply added 5 "SPACE"s between clone and the url:

  git clone     ?https://<PATH>/<TO>/<GIT_REPO>.git

and it works!

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

I was upgrading gradle from 4.1 to 4.10 and my internet connection timed out.

So I fixed this issue by deleting "gradle-4.10-all" folder in .gradle/wrapper/dists

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

To me it happened in DogController that autowired DogService that autowired DogRepository. Dog class used to have field name but I changed it to coolName, but didn't change methods in DogRepository: Dog findDogByName(String name). I change that method to Dog findDogByCoolName(String name) and now it works.

Understanding __getitem__ method

Cong Ma does a good job of explaining what __getitem__ is used for - but I want to give you an example which might be useful. Imagine a class which models a building. Within the data for the building it includes a number of attributes, including descriptions of the companies that occupy each floor :

Without using __getitem__ we would have a class like this :

class Building(object):
     def __init__(self, floors):
         self._floors = [None]*floors
     def occupy(self, floor_number, data):
          self._floors[floor_number] = data
     def get_floor_data(self, floor_number):
          return self._floors[floor_number]

building1 = Building(4) # Construct a building with 4 floors
building1.occupy(0, 'Reception')
building1.occupy(1, 'ABC Corp')
building1.occupy(2, 'DEF Inc')
print( building1.get_floor_data(2) )

We could however use __getitem__ (and its counterpart __setitem__) to make the usage of the Building class 'nicer'.

class Building(object):
     def __init__(self, floors):
         self._floors = [None]*floors
     def __setitem__(self, floor_number, data):
          self._floors[floor_number] = data
     def __getitem__(self, floor_number):
          return self._floors[floor_number]

building1 = Building(4) # Construct a building with 4 floors
building1[0] = 'Reception'
building1[1] = 'ABC Corp'
building1[2] = 'DEF Inc'
print( building1[2] )

Whether you use __setitem__ like this really depends on how you plan to abstract your data - in this case we have decided to treat a building as a container of floors (and you could also implement an iterator for the Building, and maybe even the ability to slice - i.e. get more than one floor's data at a time - it depends on what you need.

Interface vs Abstract Class (general OO)

By implementing interfaces you are achieving composition ("has-a" relationships) instead of inheritance ("is-a" relationships). That is an important principle to remember when it comes to things like design patterns where you need to use interfaces to achieve a composition of behaviors instead of an inheritance.

How do CSS triangles work?

The borders use an angled edge where they intersect (45° angle with equal width borders, but changing the border widths can skew the angle).

Border example

_x000D_
_x000D_
div {_x000D_
  width: 60px;_x000D_
  border-width: 30px;_x000D_
  border-color: red blue green yellow;_x000D_
  border-style: solid;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Have a look to the jsFiddle.

By hiding certain borders, you can get the triangle effect (as you can see above by making the different portions different colours). transparent is often used as an edge colour to achieve the triangle shape.

How to destroy Fragment?

Use this if you're in the fragment.

@Override
        public void onDestroy() {
            super.onDestroy();

            getFragmentManager().beginTransaction().remove((Fragment) youfragmentname).commitAllowingStateLoss();

        }

Use cell's color as condition in if statement (function)

I don't believe there's any way to get a cell's color from a formula. The closest you can get is the CELL formula, but (at least as of Excel 2003), it doesn't return the cell's color.

It would be pretty easy to implement with VBA:

Public Function myColor(r As Range) As Integer
    myColor = r.Interior.ColorIndex
End Function

Then in the worksheet:

=mycolor(A1)

Entity Framework - Generating Classes

EDMX model won't work with EF7 but I've found a Community/Professional product which seems to be very powerfull : http://www.devart.com/entitydeveloper/editions.html

MySql server startup error 'The server quit without updating PID file '

I had the same issue on my Mac machine (correctly followed all the installation steps suggested by brew install).

Deleting the error file fixed it for me:

sudo rm -rf /usr/local/var/mysql/dev.work.err (dev.work is my hostname)

This worked because dev.work.err was owned by _mysql:wheel instead of my own username. CHOWN-ing the error file would have probably fixed it as well.

Gradle proxy configuration

For me, works adding this configuration in the gradle.properties file of the project, where the build.gradle file is:

systemProp.http.proxyHost=proxyURL
systemProp.http.proxyPort=proxyPort
systemProp.http.proxyUser=USER
systemProp.http.proxyPassword=PASSWORD
systemProp.https.proxyHost=proxyUrl 
systemProp.https.proxyPort=proxyPort
systemProp.https.proxyUser=USER
systemProp.https.proxyPassword=PASSWORD

Where : proxyUrl is the url of the proxy server (http://.....)

proxyPort is the port (usually 8080)

USER is my domain user

PASSWORD, my password

In this case, the proxy for http and https is the same

How to convert file to base64 in JavaScript?

Modern ES6 way (async/await)

const toBase64 = file => new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
});

async function Main() {
   const file = document.querySelector('#myfile').files[0];
   console.log(await toBase64(file));
}

Main();

UPD:

If you want to catch errors

async function Main() {
   const file = document.querySelector('#myfile').files[0];
   const result = await toBase64(file).catch(e => Error(e));
   if(result instanceof Error) {
      console.log('Error: ', result.message);
      return;
   }
   //...
}

MySQL Daemon Failed to Start - centos 6

Yet another tip that worked for me. Run the command:

$ mysql_install_db

Event binding on dynamically created elements?

You could simply wrap your event binding call up into a function and then invoke it twice: once on document ready and once after your event that adds the new DOM elements. If you do that you'll want to avoid binding the same event twice on the existing elements so you'll need either unbind the existing events or (better) only bind to the DOM elements that are newly created. The code would look something like this:

function addCallbacks(eles){
    eles.hover(function(){alert("gotcha!")});
}

$(document).ready(function(){
    addCallbacks($(".myEles"))
});

// ... add elements ...
addCallbacks($(".myNewElements"))

Awaiting multiple Tasks with different results

Just await the three tasks separately, after starting them all.

var catTask = FeedCat();
var houseTask = SellHouse();
var carTask = BuyCar();

var cat = await catTask;
var house = await houseTask;
var car = await carTask;

Can't use modulus on doubles?

The % operator is for integers. You're looking for the fmod() function.

#include <cmath>

int main()
{
    double x = 6.3;
    double y = 2.0;
    double z = std::fmod(x,y);

}

CSS file not refreshing in browser

If you're using ASP.NET web forms, make sure that you are using the right theme:

enter image description here

I just spent about an hour trying to solve this!

What's the difference between "end" and "exit sub" in VBA?

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don't perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

enter image description here

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.

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

This issue arises due to the ways in which the command line IPython interpreter uses your current path vs. the way a separate process does (be it an IPython notebook, external process, etc). IPython will look for modules to import that are not only found in your sys.path, but also on your current working directory. When starting an interpreter from the command line, the current directory you're operating in is the same one you started ipython in. If you run

import os
os.getcwd() 

you'll see this is true.

However, let's say you're using an ipython notebook, run os.getcwd() and your current working directory is instead the folder in which you told the notebook to operate from in your ipython_notebook_config.py file (typically using the c.NotebookManager.notebook_dir setting).

The solution is to provide the python interpreter with the path-to-your-module. The simplest solution is to append that path to your sys.path list. In your notebook, first try:

import sys
sys.path.append('my/path/to/module/folder')

import module-of-interest

If that doesn't work, you've got a different problem on your hands unrelated to path-to-import and you should provide more info about your problem.

The better (and more permanent) way to solve this is to set your PYTHONPATH, which provides the interpreter with additional directories look in for python packages/modules. Editing or setting the PYTHONPATH as a global var is os dependent, and is discussed in detail here for Unix or Windows.

Bootstrap combining rows (rowspan)

_x000D_
_x000D_
div {_x000D_
  height:50px;_x000D_
}_x000D_
.short-div {_x000D_
  height:25px;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<div class="container">_x000D_
  <h1>Responsive Bootstrap</h1>_x000D_
  <div class="row">_x000D_
    <div class="col-lg-5 col-md-5 col-sm-5 col-xs-5" style="background-color:red;">Span 5</div>_x000D_
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3" style="background-color:blue">Span 3</div>_x000D_
    <div class="col-lg-2 col-md-2 col-sm-3 col-xs-2" style="padding:0px">_x000D_
      <div class="short-div" style="background-color:green">Span 2</div>_x000D_
      <div class="short-div" style="background-color:purple">Span 2</div>_x000D_
    </div>_x000D_
    <div class="col-lg-2 col-md-2 col-sm-3 col-xs-2" style="background-color:yellow">Span 2</div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="container-fluid">_x000D_
  <div class="row-fluid">_x000D_
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">_x000D_
      <div class="short-div" style="background-color:#999">Span 6</div>_x000D_
      <div class="short-div">Span 6</div>_x000D_
    </div>_x000D_
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6" style="background-color:#ccc">Span 6</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I pass a parameter to a Java Thread?

Parameter passing via the start() and run() methods:

// Tester
public static void main(String... args) throws Exception {
    ThreadType2 t = new ThreadType2(new RunnableType2(){
        public void run(Object object) {
            System.out.println("Parameter="+object);
        }});
    t.start("the parameter");
}

// New class 1 of 2
public class ThreadType2 {
    final private Thread thread;
    private Object objectIn = null;
    ThreadType2(final RunnableType2 runnableType2) {
        thread = new Thread(new Runnable() {
            public void run() {
                runnableType2.run(objectIn);
            }});
    }
    public void start(final Object object) {
        this.objectIn = object;
        thread.start();
    }
    // If you want to do things like setDaemon(true); 
    public Thread getThread() {
        return thread;
    }
}

// New class 2 of 2
public interface RunnableType2 {
    public void run(Object object);
}

Git log out user from command line

I am in a corporate setting and was attempting a simple git pull after a recent change in password.

I got: remote: Invalid username or password.

Interestingly, the following did not work: git config --global --unset credential.helper

I use Windows-7, so, I went to control panel -> Credential Manager -> Generic Credentials.

From the credential manager list, delete the line items corresponding to git.

After the deletion, come back to gitbash and git pull should prompt the dialog for you to enter your credentials.

BASH Syntax error near unexpected token 'done'

Open new file named foobar

nano -w foobar

Input script

 #!/bin/bash
 while [ 0 = 0 ]; do
   echo "Press [CTRL+C] to stop.."
   sleep 1
 done;

Exit and save

CTRL+X then Y and Enter

Set script executable and run

chmod +x foobar
./foobar

Rails create or update magic?

Old question but throwing my solution into the ring for completeness. I needed this when I needed a specific find but a different create if it doesn't exist.

def self.find_by_or_create_with(args, attributes) # READ CAREFULLY! args for finding, attributes for creating!
        obj = self.find_or_initialize_by(args)
        return obj if obj.persisted?
        return obj if obj.update_attributes(attributes) 
end

using href links inside <option> tag

Use a real dropdown menu instead: a list (ul, li) and links. Never misuse form elements as links.

Readers with screen readers usually scan through a automagically generated list of links – the’ll miss these important information. Many keyboard navigation systems (e.g. JAWS, Opera) offer different keyboard shortcuts for links and form elements.

If you still cannot drop the idea of a select don’t use the onchange handler at least. This is a real pain for keyboard users, it makes your third item nearly inaccessible.

Can someone give an example of cosine similarity, in a very simple, graphical way?

Simple JAVA code to calculate cosine similarity

/**
   * Method to calculate cosine similarity of vectors
   * 1 - exactly similar (angle between them is 0)
   * 0 - orthogonal vectors (angle between them is 90)
   * @param vector1 - vector in the form [a1, a2, a3, ..... an]
   * @param vector2 - vector in the form [b1, b2, b3, ..... bn]
   * @return - the cosine similarity of vectors (ranges from 0 to 1)
   */
  private double cosineSimilarity(List<Double> vector1, List<Double> vector2) {

    double dotProduct = 0.0;
    double normA = 0.0;
    double normB = 0.0;
    for (int i = 0; i < vector1.size(); i++) {
      dotProduct += vector1.get(i) * vector2.get(i);
      normA += Math.pow(vector1.get(i), 2);
      normB += Math.pow(vector2.get(i), 2);
    }
    return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
  }

HTML embedded PDF iframe

Iframe

<iframe id="fred" style="border:1px solid #666CCC" title="PDF in an i-Frame" src="PDFData.pdf" frameborder="1" scrolling="auto" height="1100" width="850" ></iframe>

Object

<object data="your_url_to_pdf" type="application/pdf">
  <embed src="your_url_to_pdf" type="application/pdf" />
</object>

Received an invalid column length from the bcp client for colid 6

Great piece of code, thanks for sharing!

I ended up using reflection to get the actual DataMemberName to throw back to a client on an error (I'm using bulk save in a WCF service). Hopefully someone else will find how I did it useful.

_x000D_
_x000D_
static string GetDataMemberName(string colName, object t) {_x000D_
  foreach(PropertyInfo propertyInfo in t.GetType().GetProperties()) {_x000D_
    if (propertyInfo.CanRead) {_x000D_
      if (propertyInfo.Name == colName) {_x000D_
        var attributes = propertyInfo.GetCustomAttributes(typeof(DataMemberAttribute), false).FirstOrDefault() as DataMemberAttribute;_x000D_
        if (attributes != null && !string.IsNullOrEmpty(attributes.Name))_x000D_
          return attributes.Name;_x000D_
        return colName;_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  return colName;_x000D_
}
_x000D_
_x000D_
_x000D_

How to get first record in each group using Linq

Use it to achieve what you want. Then decide which properties you want to return.

yourList.OrderBy(l => l.Id).GroupBy(l => new { GroupName = l.F1}).Select(r => r.Key.GroupName)

Escape string for use in Javascript regex

Short 'n Sweet

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Example

escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "

(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)

Install

Available on npm as escape-string-regexp

npm install --save escape-string-regexp

Note

See MDN: Javascript Guide: Regular Expressions

Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.

.

.

.

.

Test Case: A typical url

escapeRegExp("/path/to/resource.html?search=query");

>>> "\/path\/to\/resource\.html\?search=query"

The Long Answer

If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.

var escapeRegExp;

(function () {
  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , = 
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
          "-"
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"
      ]

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
    , regex = RegExp('[' + specials.join('\\') + ']', 'g')
    ;

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");
  };

  // test escapeRegExp("/path/to/res?search=this.that")
}());

Why can templates only be implemented in the header file?

You can actually define your template class inside a .template file rather than a .cpp file. Whoever is saying you can only define it inside a header file is wrong. This is something that works all the way back to c++ 98.

Don't forget to have your compiler treat your .template file as a c++ file to keep the intelli sense.

Here is an example of this for a dynamic array class.

#ifndef dynarray_h
#define dynarray_h

#include <iostream>

template <class T>
class DynArray{
    int capacity_;
    int size_;
    T* data;
public:
    explicit DynArray(int size = 0, int capacity=2);
    DynArray(const DynArray& d1);
    ~DynArray();
    T& operator[]( const int index);
    void operator=(const DynArray<T>& d1);
    int size();

    int capacity();
    void clear();

    void push_back(int n);

    void pop_back();
    T& at(const int n);
    T& back();
    T& front();
};

#include "dynarray.template" // this is how you get the header file

#endif

Now inside you .template file you define your functions just how you normally would.

template <class T>
DynArray<T>::DynArray(int size, int capacity){
    if (capacity >= size){
        this->size_ = size;
        this->capacity_ = capacity;
        data = new T[capacity];
    }
    //    for (int i = 0; i < size; ++i) {
    //        data[i] = 0;
    //    }
}

template <class T>
DynArray<T>::DynArray(const DynArray& d1){
    //clear();
    //delete [] data;
    std::cout << "copy" << std::endl;
    this->size_ = d1.size_;
    this->capacity_ = d1.capacity_;
    data = new T[capacity()];
    for(int i = 0; i < size(); ++i){
        data[i] = d1.data[i];
    }
}

template <class T>
DynArray<T>::~DynArray(){
    delete [] data;
}

template <class T>
T& DynArray<T>::operator[]( const int index){
    return at(index);
}

template <class T>
void DynArray<T>::operator=(const DynArray<T>& d1){
    if (this->size() > 0) {
        clear();
    }
    std::cout << "assign" << std::endl;
    this->size_ = d1.size_;
    this->capacity_ = d1.capacity_;
    data = new T[capacity()];
    for(int i = 0; i < size(); ++i){
        data[i] = d1.data[i];
    }

    //delete [] d1.data;
}

template <class T>
int DynArray<T>::size(){
    return size_;
}

template <class T>
int DynArray<T>::capacity(){
    return capacity_;
}

template <class T>
void DynArray<T>::clear(){
    for( int i = 0; i < size(); ++i){
        data[i] = 0;
    }
    size_ = 0;
    capacity_ = 2;
}

template <class T>
void DynArray<T>::push_back(int n){
    if (size() >= capacity()) {
        std::cout << "grow" << std::endl;
        //redo the array
        T* copy = new T[capacity_ + 40];
        for (int i = 0; i < size(); ++i) {
            copy[i] = data[i];
        }

        delete [] data;
        data = new T[ capacity_ * 2];
        for (int i = 0; i < capacity() * 2; ++i) {
            data[i] = copy[i];
        }
        delete [] copy;
        capacity_ *= 2;
    }
    data[size()] = n;
    ++size_;
}

template <class T>
void DynArray<T>::pop_back(){
    data[size()-1] = 0;
    --size_;
}

template <class T>
T& DynArray<T>::at(const int n){
    if (n >= size()) {
        throw std::runtime_error("invalid index");
    }
    return data[n];
}

template <class T>
T& DynArray<T>::back(){
    if (size() == 0) {
        throw std::runtime_error("vector is empty");
    }
    return data[size()-1];
}

template <class T>
T& DynArray<T>::front(){
    if (size() == 0) {
        throw std::runtime_error("vector is empty");
    }
    return data[0];
    }

select2 - hiding the search box

If you want to hide on initial opening and you are populating the dropdown via ajax call, add the following to the ajax block in your select2 declaration:

beforeSend: function () 
  {
    $('.select2-search--dropdown').addClass('hidden');
  }

To then show it again (and focus) after your ajax request is successful:

  success: function() {
      $('.select2-search--dropdown').removeClass('select2-search--hide'); // show search bar then focus
      $('.select2-search__field')[0].focus();
  }

Get last record of a table in Postgres

The last inserted record can be queried using this assuming you have the "id" as the primary key:

SELECT timestamp,value,card FROM my_table WHERE id=(select max(id) from my_table)

Assuming every new row inserted will use the highest integer value for the table's id.

How to set input type date's default value to today?

$(document).ready(function(){
  var date = new Date();

  var day = ("0" + date.getDate()).slice(-2); var month = ("0" + (date.getMonth() + 1)).slice(-2);

  var today = date.getFullYear()+"-"+(month)+"-"+(day) ;
});

$('#dateid').val(today);

Delete with "Join" in Oracle sql Query

Recently I learned of the following syntax:

DELETE (SELECT *
        FROM productfilters pf
        INNER JOIN product pr
            ON pf.productid = pr.id
        WHERE pf.id >= 200
            AND pr.NAME = 'MARK')

I think it looks much cleaner then other proposed code.

Java file path in Linux

The Official Documentation is clear about Path.

Linux Syntax: /home/joe/foo

Windows Syntax: C:\home\joe\foo


Note: joe is your username for these examples.

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

Use your browser's network inspector (F12) to see when the browser is requesting the bgbody.png image and what absolute path it's using and why the server is returning a 404 response.

...assuming that bgbody.png actually exists :)

Is your CSS in a stylesheet file or in a <style> block in a page? If it's in a stylesheet then the relative path must be relative to the CSS stylesheet (not the document that references it). If it's in a page then it must be relative to the current resource path. If you're using non-filesystem-based resource paths (i.e. using URL rewriting or URL routing) then this will cause problems and it's best to always use absolute paths.

Going by your relative path it looks like you store your images separately from your stylesheets. I don't think this is a good idea - I support storing images and other resources, like fonts, in the same directory as the stylesheet itself, as it simplifies paths and is also a more logical filesystem arrangement.

Batch script loop

The answer really depends on how familiar you are with batch, if you are not so experienced, I would recommend incrementing a loop variable:

@echo off
set /a loop=1
:repeat
echo Hello World!
set /a loop=%loop%+1
if %loop%==<no. of times to repeat> (
goto escapedfromrepeat
)
goto repeat
:escapedfromrepeat
echo You have come out of the loop
pause

But if you are more experienced with batch, I would recommend the more practical for /l %loop in (1, 1, 10) do echo %loop is the better choice.

             (start at 1, go up in 1's, end at 10)
for /l %[your choice] (start, step, end) do [command of your choice]

SQL query, store result of SELECT in local variable

I came here with a similar question/problem, but I only needed a single value to be stored from the query, not an array/table of results as in the orig post. I was able to use the table method above for a single value, however I have stumbled upon an easier way to store a single value.

declare @myVal int; set @myVal = isnull((select a from table1), 0);

Make sure to default the value in the isnull statement to a valid type for your variable, in my example the value in table1 that we're storing is an int.

How to find the highest value of a column in a data frame in R?

Try this solution:

Oz<-subset(data, data$Month==5,select=Ozone) # select ozone  value in the month of                 
                                             #May (i.e. Month = 5)
summary(T)                                   #gives caracteristics of table( contains 1 column of Ozone) including max, min ...

Get Root Directory Path of a PHP project

you can try: $_SERVER['PATH_TRANSLATED']

quote:

Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping. Note: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly under the Apache 2 SAPI in contrast to the situation in Apache 1, where it's set to the same value as the SCRIPT_FILENAME server variable when it's not populated by Apache.
This change was made to comply with the CGI specification that PATH_TRANSLATED should only exist if PATH_INFO is defined. Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO

source: php.net/manual

Turning a string into a Uri in Android

Uri.parse(STRING);

See doc:

String: an RFC 2396-compliant, encoded URI

Url must be canonicalized before using, like this:

Uri.parse(Uri.decode(STRING));

Obtaining only the filename when using OpenFileDialog property "FileName"

Use OpenFileDialog.SafeFileName

OpenFileDialog.SafeFileName Gets the file name and extension for the file selected in the dialog box. The file name does not include the path.

How can I use Bash syntax in Makefile targets?

You can call bash directly within your Makefile instead of using the default shell:

bash -c "ls -al"

instead of:

ls -al

How do I specify "close existing connections" in sql script

You can disconnect everyone and roll back their transactions with:

alter database [MyDatbase] set single_user with rollback immediate

After that, you can safely drop the database :)

How to add to an NSDictionary

You want to ask is "what is the difference between a mutable and a non-mutable array or dictionary." Many times there different terms are used to describe things that you already know about. In this case, you can replace the term "mutable" with "dynamic." So, a mutuable dictionary or array is one that is "dynamic" and can change at runtime, whereas a non-mutable dictionary or array is one that is "static" and defined in your code and does not change at runtime (in other words, you will not be adding, deleting or possibly sorting the elements.)

As to how it is done, you are asking us to repeat the documentation here. All you need to do is to search in sample code and the Xcode documentation to see exactly how it is done. But the mutable thing threw me too when I was first learning, so I'll give you that one!

How to launch an application from a browser?

I achieved the same thing using a local web server and PHP. I used a script containing shell_exec to launch an application locally.

Alternatively, you could do something like this:

<a href="file://C:/Windows/notepad.exe">Notepad</a>

Presto SQL - Converting a date string to date format

I figured it out. The below works in converting it to a 24 hr date format.

select date_parse('7/22/2016 6:05:04 PM','%m/%d/%Y %h:%i:%s %p')

See date_parse documentation in Presto.

How do I extract text that lies between parentheses (round brackets)?

A regex maybe? I think this would work...

\(([a-z]+?)\)

ComboBox: Adding Text and Value to an Item (no Binding Source)

I liked fab's answer but didn't want to use a dictionary for my situation so I substituted a list of tuples.

// set up your data
public static List<Tuple<string, string>> List = new List<Tuple<string, string>>
{
  new Tuple<string, string>("Item1", "Item2")
}

// bind to the combo box
comboBox.DataSource = new BindingSource(List, null);
comboBox.ValueMember = "Item1";
comboBox.DisplayMember = "Item2";

//Get selected value
string value = ((Tuple<string, string>)queryList.SelectedItem).Item1;

Create a jTDS connection string

A shot in the dark, but From the looks of your error message, it seems that either the sqlserver instance is not running on port 1433 or something is blocking the requests to that port

?: operator (the 'Elvis operator') in PHP

Yes, this is new in PHP 5.3. It returns either the value of the test expression if it is evaluated as TRUE, or the alternative value if it is evaluated as FALSE.

Detecting superfluous #includes in C/C++?

I've tried using Flexelint (the unix version of PC-Lint) and had somewhat mixed results. This is likely because I'm working on a very large and knotty code base. I recommend carefully examining each file that is reported as unused.

The main worry is false positives. Multiple includes of the same header are reported as an unneeded header. This is bad since Flexelint does not tell you what line the header is included on or where it was included before.

One of the ways automated tools can get this wrong:

In A.hpp:

class A { 
  // ...
};

In B.hpp:

#include "A.hpp

class B {
    public:
        A foo;
};

In C.cpp:

#include "C.hpp"  

#include "B.hpp"  // <-- Unneeded, but lint reports it as needed
#include "A.hpp"  // <-- Needed, but lint reports it as unneeded

If you blindly follow the messages from Flexelint you'll muck up your #include dependencies. There are more pathological cases, but basically you're going to need to inspect the headers yourself for best results.

I highly recommend this article on Physical Structure and C++ from the blog Games from within. They recommend a comprehensive approach to cleaning up the #include mess:

Guidelines

Here’s a distilled set of guidelines from Lakos’ book that minimize the number of physical dependencies between files. I’ve been using them for years and I’ve always been really happy with the results.

  1. Every cpp file includes its own header file first. [snip]
  2. A header file must include all the header files necessary to parse it. [snip]
  3. A header file should have the bare minimum number of header files necessary to parse it. [snip]

How to obtain the last path segment of a URI

In Android

Android has a built in class for managing URIs.

Uri uri = Uri.parse("http://base_path/some_segment/id");
String lastPathSegment = uri.getLastPathSegment()

Can you do a For Each Row loop using MySQL?

Not a for each exactly, but you can do nested SQL

SELECT 
    distinct a.ID, 
    a.col2, 
    (SELECT 
        SUM(b.size) 
    FROM 
        tableb b 
    WHERE 
        b.id = a.col3)
FROM
    tablea a

How to build a JSON array from mysql database

Use this

$array = array();
$subArray=array();
$sql_results = mysql_query('SELECT * FROM `location`');

while($row = mysql_fetch_array($sql_results))
{
    $subArray[location_id]=$row['location'];  //location_id is key and $row['location'] is value which come fron database.
    $subArray[x]=$row['x'];
    $subArray[y]=$row['y'];


 $array[] =  $subArray ;
}
echo'{"ProductsData":'.json_encode($array).'}';

How can I see the current value of my $PATH variable on OS X?

for MacOS, make sure you know where the GO install

export GOPATH=/usr/local/go
PATH=$PATH:$GOPATH/bin

How can I add C++11 support to Code::Blocks compiler?

Use g++ -std=c++11 -o <output_file_name> <file_to_be_compiled>

How to print a two dimensional array?

more simpler approach , use java 5 style for loop

Integer[][] twoDimArray = {{8, 9},{8, 10}};
        for (Integer[] array: twoDimArray){
            System.out.print(array[0] + " ,");
            System.out.println(array[1]);
        }

how to change background image of button when clicked/focused?

Sorry this is wrong.

For changing background color/image based on the particular event(focus, press, normal), you need to define a button selector file and implement it as background for button.

For example: button_selector.xml (define this file inside the drawable folder)

<?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">
     <item android:state_pressed="true"
           android:color="#000000" /> <!-- pressed -->
     <item android:state_focused="true"
           android:color="#000000" /> <!-- focused -->
     <item android:color="#FFFFFF" /> <!-- default -->
 </selector>

    <!-- IF you want image instead of color then write 
android:drawable="@drawable/your_image" inside the <item> tag -->

And apply it as:

 <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:drawable="@drawable/button_selector.xml" />

What is the difference between a static and a non-static initialization code block

The static code block can be used to instantiate or initialize class variables (as opposed to object variables). So declaring "a" static means that is only one shared by all Test objects, and the static code block initializes "a" only once, when the Test class is first loaded, no matter how many Test objects are created.

how do I use an enum value on a switch statement in C++

i had a similar issue using enum with switch cases later i resolved it on my own....below is the corrected code, perhaps this might help.

     //Menu Chooser Programe using enum
     #include<iostream>
     using namespace std;
     int main()
     {
        enum level{Novice=1, Easy, Medium, Hard};
        level diffLevel=Novice;
        int i;
        cout<<"\nenter a level: ";
        cin>>i;
        switch(i)
        {
        case Novice: cout<<"\nyou picked Novice\n"; break;
        case Easy: cout<<"\nyou picked Easy\n"; break;
        case Medium: cout<<"\nyou picked Medium\n"; break;
        case Hard: cout<<"\nyou picked Hard\n"; break;
        default: cout<<"\nwrong input!!!\n"; break;
        }
        return 0;
     }

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

This is the code that works for me, what I want is to list the images directly on my page so that you just have to put the directory where you can find the images for example -> dir = "images /" I do a substring var pathName = filename.substring (filename.lastIndexOf ('/') + 1); with which I make sure to just bring the name of the files listed and at the end I link my URL to publish it in the body

$ ("body"). append ($ ("<img src =" + dir + pathName + "> </ img>"));
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="jquery-1.6.3.min.js"></script>
        <script>


        var dir = "imagenes/";
        var fileextension = ".jpg";
        $.ajax({
            //This will retrieve the contents of the folder if the folder is configured as 'browsable'
            url: dir,
            success: function (data) {
                //Lsit all png file names in the page
                $(data).find("a:contains(" + fileextension + ")").each(function () {
                    var filename = this.href.replace(window.location.pathname, "").replace("http://", "");
            var pathName = filename.substring(filename.lastIndexOf('/') + 1);               
                    $("body").append($("<img src=" + dir + pathName + "></img>"));
            console.log(dir+pathName);
                });
            }
        });



        </script>

  </head>
  <body>
<img src="1_1.jpg">
  </body>
</html>

How to remove an unpushed outgoing commit in Visual Studio?

TL;DR:

Use git reset --soft HEAD~ in the cmd from the .sln folder


I was facing it today and was overwhelmed that VSCode suggests such thing, whereas it's big brother Visual Studio doesn't.

Most of the answers were helpful; if I have more commits that were made before, losing them all would be frustrating. Moreover, if VSCode does it in half a second, it shouldn't be complex.

Only jessehouwing's answer was the closest to a simple solution.


Assuming the undesired commit(s) was the last one to happen, Here is how I solved it:

Go to Team Explorer -> Sync. There you'd see the all the commits. Press the Actions dropdown and Open Command Prompt

undesired-commit-solved example

You'll have the cmd window prompted, there write git reset --soft HEAD~. If there are multiple undesired commits, add the amount after the ~ (i.e git reset --soft HEAD~5)


(If you're not using git, check colloquial usage).

I hope it will help, and hopefully in the next version VS team will add it builtin

Checking if a file is a directory or just a file

You can call the stat() function and use the S_ISREG() macro on the st_mode field of the stat structure in order to determine if your path points to a regular file:

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int is_regular_file(const char *path)
{
    struct stat path_stat;
    stat(path, &path_stat);
    return S_ISREG(path_stat.st_mode);
}

Note that there are other file types besides regular and directory, like devices, pipes, symbolic links, sockets, etc. You might want to take those into account.

How do you monitor network traffic on the iPhone?

Com'on, no mention of Fiddler? Where's the love :)

Fiddler is a very popular HTTP debugger aimed at developers and not network admins (i.e. Wireshark).

Setting it up for iOS is fairly simple process. It can decrypt HTTPS traffic too!

Our mobile team is finally reliefed after QA department started using Fiddler to troubleshoot issues. Before fiddler, people fiddled around to know who to blame, mobile team or APIs team, but not anymore.

Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

One other way not mentioned here is to subclass ListBox

Ie.

public class ListBoxNoEventValidation : ListBox 
{
}

ClientEventValidation keys off the attribute System.Web.UI.SupportsEventValidation if you subclass it, unless you explicitly add it back in, it will never call the validation routine. That works with any control, and is the only way I've found to "disable" it on a control by control basis (Ie, not page level).

How can I align YouTube embedded video in the center in bootstrap

<center><div class="video">
<iframe width="560" height="315" src="https://www.youtube.com/embed/ig3qHRVZRvM" frameborder="0" allowfullscreen=""></iframe>
</div></center>

It seems to work, is this all you were asking for? I guess you could go about taking longer more involved routes, but this seemed simple enough.

ReactJS - Does render get called any time "setState" is called?

Does React re-render all components and sub-components every time setState is called?

By default - yes.

There is a method boolean shouldComponentUpdate(object nextProps, object nextState), each component has this method and it's responsible to determine "should component update (run render function)?" every time you change state or pass new props from parent component.

You can write your own implementation of shouldComponentUpdate method for your component, but default implementation always returns true - meaning always re-run render function.

Quote from official docs http://facebook.github.io/react/docs/component-specs.html#updating-shouldcomponentupdate

By default, shouldComponentUpdate always returns true to prevent subtle bugs when the state is mutated in place, but if you are careful to always treat the state as immutable and to read-only from props and state in render() then you can override shouldComponentUpdate with an implementation that compares the old props and state to their replacements.

Next part of your question:

If so, why? I thought the idea was that React only rendered as little as needed - when the state changed.

There are two steps of what we may call "render":

  1. Virtual DOM renders: when render method is called it returns a new virtual dom structure of the component. As I mentioned before, this render method is called always when you call setState(), because shouldComponentUpdate always returns true by default. So, by default, there is no optimization here in React.

  2. Native DOM renders: React changes real DOM nodes in your browser only if they were changed in the Virtual DOM and as little as needed - this is that great React's feature which optimizes real DOM mutation and makes React fast.

Why is Android Studio reporting "URI is not registered"?

The new build system in Android Studio creates a build folder. The code inspection barfs on this folder as well as the gradle folder. These folders should proably be ignored when running code inspection.

I have raised an issue with the Android Studio team at:

https://code.google.com/p/android/issues/detail?id=56415

Converting bool to text in C++

C++ has proper strings so you might as well use them. They're in the standard header string. #include <string> to use them. No more strcat/strcpy buffer overruns; no more missing null terminators; no more messy manual memory management; proper counted strings with proper value semantics.

C++ has the ability to convert bools into human-readable representations too. We saw hints at it earlier with the iostream examples, but they're a bit limited because they can only blast the text to the console (or with fstreams, a file). Fortunately, the designers of C++ weren't complete idiots; we also have iostreams that are backed not by the console or a file, but by an automatically managed string buffer. They're called stringstreams. #include <sstream> to get them. Then we can say:

std::string bool_as_text(bool b)
{
    std::stringstream converter;
    converter << std::boolalpha << b;   // flag boolalpha calls converter.setf(std::ios_base::boolalpha)
    return converter.str();
}

Of course, we don't really want to type all that. Fortunately, C++ also has a convenient third-party library named Boost that can help us out here. Boost has a nice function called lexical_cast. We can use it thus:

boost::lexical_cast<std::string>(my_bool)

Now, it's true to say that this is higher overhead than some macro; stringstreams deal with locales which you might not care about, and create a dynamic string (with memory allocation) whereas the macro can yield a literal string, which avoids that. But on the flip side, the stringstream method can be used for a great many conversions between printable and internal representations. You can run 'em backwards; boost::lexical_cast<bool>("true") does the right thing, for example. You can use them with numbers and in fact any type with the right formatted I/O operators. So they're quite versatile and useful.

And if after all this your profiling and benchmarking reveals that the lexical_casts are an unacceptable bottleneck, that's when you should consider doing some macro horror.

Most efficient way to see if an ArrayList contains an object in Java

Given your constraints, you're stuck with brute force search (or creating an index if the search will be repeated). Can you elaborate any on how the ArrayList is generated--perhaps there is some wiggle room there.

If all you're looking for is prettier code, consider using the Apache Commons Collections classes, in particular CollectionUtils.find(), for ready-made syntactic sugar:

ArrayList haystack = // ...
final Object needleField1 = // ...
final Object needleField2 = // ...

Object found = CollectionUtils.find(haystack, new Predicate() {
   public boolean evaluate(Object input) {
      return needleField1.equals(input.field1) && 
             needleField2.equals(input.field2);
   }
});

How do I convert a javascript object array to a string array of the object attribute I want?

If your array of objects is items, you can do:

_x000D_
_x000D_
var items = [{_x000D_
  id: 1,_x000D_
  name: 'john'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'jane'_x000D_
}, {_x000D_
  id: 2000,_x000D_
  name: 'zack'_x000D_
}];_x000D_
_x000D_
var names = items.map(function(item) {_x000D_
  return item['name'];_x000D_
});_x000D_
_x000D_
console.log(names);_x000D_
console.log(items);
_x000D_
_x000D_
_x000D_

Documentation: map()

Replace special characters in a string with _ (underscore)

string = string.replace(/[\W_]/g, "_");

jQuery ajax call to REST service

From the use of 8080 I'm assuming you are using a tomcat servlet container to serve your rest api. If this is the case you can also consider to have your webserver proxy the requests to the servlet container.

With apache you would typically use mod_jk (although there are other alternatives) to serve the api trough the web server behind port 80 instead of 8080 which would solve the cross domain issue.

This is common practice, have the 'static' content in the webserver and dynamic content in the container, but both served from behind the same domain.

The url for the rest api would be http://localhost/restws/json/product/get

Here a description on how to use mod_jk to connect apache to tomcat: http://tomcat.apache.org/connectors-doc/webserver_howto/apache.html

How do you programmatically update query params in react-router?

I prefer you to use below function that is ES6 style:

getQueryStringParams = query => {
    return query
        ? (/^[?#]/.test(query) ? query.slice(1) : query)
            .split('&')
            .reduce((params, param) => {
                    let [key, value] = param.split('=');
                    params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
                    return params;
                }, {}
            )
        : {}
};

jQuery - Follow the cursor with a DIV

This works for me. Has a nice delayed action going on.

var $mouseX = 0, $mouseY = 0;
var $xp = 0, $yp =0;

$(document).mousemove(function(e){
    $mouseX = e.pageX;
    $mouseY = e.pageY;    
});

var $loop = setInterval(function(){
// change 12 to alter damping higher is slower
$xp += (($mouseX - $xp)/12);
$yp += (($mouseY - $yp)/12);
$("#moving_div").css({left:$xp +'px', top:$yp +'px'});  
}, 30);

Nice and simples

Pointer to 2D arrays in C

Both your examples are equivalent. However, the first one is less obvious and more "hacky", while the second one clearly states your intention.

int (*pointer)[280];
pointer = tab1;

pointer points to an 1D array of 280 integers. In your assignment, you actually assign the first row of tab1. This works since you can implicitly cast arrays to pointers (to the first element).

When you are using pointer[5][12], C treats pointer as an array of arrays (pointer[5] is of type int[280]), so there is another implicit cast here (at least semantically).

In your second example, you explicitly create a pointer to a 2D array:

int (*pointer)[100][280];
pointer = &tab1;

The semantics are clearer here: *pointer is a 2D array, so you need to access it using (*pointer)[i][j].

Both solutions use the same amount of memory (1 pointer) and will most likely run equally fast. Under the hood, both pointers will even point to the same memory location (the first element of the tab1 array), and it is possible that your compiler will even generate the same code.

The first solution is "more advanced" since one needs quite a deep understanding on how arrays and pointers work in C to understand what is going on. The second one is more explicit.

Loop through an array of strings in Bash?

You can use the syntax of ${arrayName[@]}

#!/bin/bash
# declare an array called files, that contains 3 values
files=( "/etc/passwd" "/etc/group" "/etc/hosts" )
for i in "${files[@]}"
do
    echo "$i"
done

Can we have multiple <tbody> in same <table>?

Martin Joiner's problem is caused by a misunderstanding of the <caption> tag.

The <caption> tag defines a table caption.

The <caption> tag must be the first child of the <table> tag.

You can specify only one caption per table.

Also, note that the scope attribute should be placed on a <th> element and not on a <tr> element.

The proper way to write a multi-header multi-tbody table would be something like this :

_x000D_
_x000D_
<table id="dinner_table">_x000D_
    <caption>This is the only correct place to put a caption.</caption>_x000D_
    <tbody>_x000D_
        <tr class="header">_x000D_
            <th colspan="2" scope="col">First Half of Table (British Dinner)</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">1</th>_x000D_
            <td>Fish</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">2</th>_x000D_
            <td>Chips</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">3</th>_x000D_
            <td>Peas</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">4</th>_x000D_
            <td>Gravy</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
    <tbody>_x000D_
        <tr class="header">_x000D_
            <th colspan="2" scope="col">Second Half of Table (Italian Dinner)</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">5</th>_x000D_
            <td>Pizza</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">6</th>_x000D_
            <td>Salad</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">7</th>_x000D_
            <td>Oil</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <th scope="row">8</th>_x000D_
            <td>Bread</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How do I capture all of my compiler's output to a file?

In a bourne shell:

make > my.log 2>&1

I.e. > redirects stdout, 2>&1 redirects stderr to the same place as stdout

Detect whether there is an Internet connection available on Android

The getActiveNetworkInfo() method of ConnectivityManager returns a NetworkInfo instance representing the first connected network interface it can find or null if none of the interfaces are connected. Checking if this method returns null should be enough to tell if an internet connection is available or not.

private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

You will also need:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

in your android manifest.

Edit:

Note that having an active network interface doesn't guarantee that a particular networked service is available. Network issues, server downtime, low signal, captive portals, content filters and the like can all prevent your app from reaching a server. For instance you can't tell for sure if your app can reach Twitter until you receive a valid response from the Twitter service.

continuous page numbering through section breaks

You can check out this post on SuperUser.

Word starts page numbering over for each new section by default.

I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.

My method:

  • open up the footer (or header if that's where your page number is)
  • drag-select the page number
  • right-click on it
  • hit Format Page Numbers
  • click on the Continue from Previous Section radio button under Page numbering

I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.

Validate select box

For starters, you can "disable" the option from being selected accidentally by users:

<option value="" disabled="disabled">Choose an option</option>

Then, inside your JavaScript event (doesn't matter whether it is jQuery or JavaScript), for your form to validate whether it is set, do:

select = document.getElementById('select'); // or in jQuery use: select = this;
if (select.value) {
  // value is set to a valid option, so submit form
  return true;
}
return false;

Or something to that effect.

API vs. Webservice

API(Application Programming Interface), the full form itself suggests that its an Interface which allows you to program for your application with the help or support of some other Application's Interface which exposes some sort of functionality which is useful to your application.

E.g showing updated currency exchange rates on your website would need some third party Interface to program against unless you plan to have your own database with currency rates and regular updates to the same. This set of functionality is when already available with some one else and when they want to share it with others they have to have an endpoint to communicate with the others who are interested in such interactions so they deploy it on web by the means of web-services. This end point is nothing but interface of their application which you can program against hence API.

Resize svg when window is resized in d3.js

UPDATE just use the new way from @cminatti


old answer for historic purposes

IMO it's better to use select() and on() since that way you can have multiple resize event handlers... just don't get too crazy

d3.select(window).on('resize', resize); 

function resize() {
    // update width
    width = parseInt(d3.select('#chart').style('width'), 10);
    width = width - margin.left - margin.right;

    // resize the chart
    x.range([0, width]);
    d3.select(chart.node().parentNode)
        .style('height', (y.rangeExtent()[1] + margin.top + margin.bottom) + 'px')
        .style('width', (width + margin.left + margin.right) + 'px');

    chart.selectAll('rect.background')
        .attr('width', width);

    chart.selectAll('rect.percent')
        .attr('width', function(d) { return x(d.percent); });

    // update median ticks
    var median = d3.median(chart.selectAll('.bar').data(), 
        function(d) { return d.percent; });

    chart.selectAll('line.median')
        .attr('x1', x(median))
        .attr('x2', x(median));


    // update axes
    chart.select('.x.axis.top').call(xAxis.orient('top'));
    chart.select('.x.axis.bottom').call(xAxis.orient('bottom'));

}

http://eyeseast.github.io/visible-data/2013/08/28/responsive-charts-with-d3/

Stopping an Android app from console

adb shell killall -9 com.your.package.name

according to MAC "mandatory access control" you probably have the permission to kill process which is not started by root

have fun!

Add rows to CSV File in powershell

Create a new custom object and add it to the object array that Import-Csv creates.

$fileContent = Import-csv $file -header "Date", "Description"
$newRow = New-Object PsObject -Property @{ Date = 'Text4' ; Description = 'Text5' }
$fileContent += $newRow

Moving from JDK 1.7 to JDK 1.8 on Ubuntu

Just use these command lines:

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer

If needed, you can also follow this Ubuntu tutorial.

Proxy with urllib2

proxy = urllib2.ProxyHandler({'http': '127.0.0.1'})
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
urllib2.urlopen('http://www.google.com')

How to convert a string or integer to binary in Ruby?

You have Integer#to_s(base) and String#to_i(base) available to you.

Integer#to_s(base) converts a decimal number to a string representing the number in the base specified:

9.to_s(2) #=> "1001"

while the reverse is obtained with String#to_i(base):

"1001".to_i(2) #=> 9

difference between new String[]{} and new String[] in java

You have a choice, when you create an object array (as opposed to an array of primitives).

One option is to specify a size for the array, in which case it will just contain lots of nulls.

String[] array = new String[10]; // Array of size 10, filled with nulls.

The other option is to specify what will be in the array.

String[] array = new String[] {"Larry", "Curly", "Moe"};  // Array of size 3, filled with stooges.

But you can't mix the two syntaxes. Pick one or the other.

How to display a jpg file in Python?

from PIL import Image

image = Image.open('File.jpg')
image.show()

Selecting fields from JSON output

Assuming you are dealing with a JSON-string in the input, you can parse it using the json package, see the documentation.

In the specific example you posted you would need

x = json.loads("""{
 "accountWide": true,
 "criteria": [
     {
         "description": "some description",
         "id": 7553,
         "max": 1,
         "orderIndex": 0
     }
  ]
 }""")
description = x['criteria'][0]['description']
id = x['criteria'][0]['id']
max = x['criteria'][0]['max']

Android WebView not loading URL

Just as an alternative solution:

For me webView.getSettings().setUserAgentString("Android WebView") did the trick.

I already had implemented INTERNET permission and WebViewClient as well as WebChromeClient

Comparing two .jar files

Extract each jar to it's own directory using the jar command with parameters xvf. i.e. jar xvf myjar.jar for each jar.

Then, use the UNIX command diff to compare the two directories. This will show the differences in the directories. You can use diff -r dir1 dir2 two recurse and show the differences in text files in each directory(.xml, .properties, etc).

This will also show if binary class files differ. To actually compare the class files you will have to decompile them as noted by others.

Basic HTTP and Bearer Token Authentication

There is another solution for testing APIs on development server.

  • Set HTTP Basic Authentication only for web routes
  • Leave all API routes free from authentication

Web server configuration for nginx and Laravel would be like this:

    location /api {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location / {
        try_files $uri $uri/ /index.php?$query_string;

        auth_basic "Enter password";
        auth_basic_user_file /path/to/.htpasswd;
    }

Authorization: Bearer will do the job of defending the development server against web crawlers and other unwanted visitors.

jquery clear input default value

Unless you're really worried about older browsers, you could just use the new html5 placeholder attribute like so:

<input type="text" name="email" placeholder="Email address" class="input" />

Convert txt to csv python script

This is how I do it:

 with open(txtfile, 'r') as infile, open(csvfile, 'w') as outfile:
        stripped = (line.strip() for line in infile)
        lines = (line.split(",") for line in stripped if line)
        writer = csv.writer(outfile)
        writer.writerows(lines)

Hope it helps!

Stored procedure or function expects parameter which is not supplied

in my case, I was passing all the parameters but one of the parameter my code was passing a null value for string.

Eg: cmd.Parameters.AddWithValue("@userName", userName);

in the above case, if the data type of userName is string, I was passing userName as null.

How to correctly assign a new string value?

The first example doesn't work because you can't assign values to arrays - arrays work (sort of) like const pointers in this respect. What you can do though is copy a new value into the array:

strcpy(p.name, "Jane");

Char arrays are fine to use if you know the maximum size of the string in advance, e.g. in the first example you are 100% sure that the name will fit into 19 characters (not 20 because one character is always needed to store the terminating zero value).

Conversely, pointers are better if you don't know the possible maximum size of your string, and/or you want to optimize your memory usage, e.g. avoid reserving 512 characters for the name "John". However, with pointers you need to dynamically allocate the buffer they point to, and free it when not needed anymore, to avoid memory leaks.

Update: example of dynamically allocated buffers (using the struct definition in your 2nd example):

char* firstName = "Johnnie";
char* surname = "B. Goode";
person p;

p.name = malloc(strlen(firstName) + 1);
p.surname = malloc(strlen(surname) + 1);

p.age = 25;
strcpy(p.name, firstName);
strcpy(p.surname, surname);

printf("Name: %s; Age: %d\n",p.name,p.age);

free(p.surname);
free(p.name);

Find all table names with column name?

Please try the below query. Use sys.columns to get the details :-

SELECT c.name AS ColName, t.name AS TableName
FROM sys.columns c
    JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%MyCol%';

transform object to array with lodash

For me, this worked:

_.map(_.toPairs(data), d => _.fromPairs([d]));

It turns

{"a":"b", "c":"d", "e":"f"} 

into

[{"a":"b"}, {"c":"d"}, {"e":"f"}]

button image as form input submit button?

Late to the conversation...

But, why not use css? That way you can keep the button as a submit type.

html:

<input type="submit" value="go" />

css:

button, input[type="submit"] {
    background:url(/images/submit.png) no-repeat;"
}

Works like a charm.

EDIT: If you want to remove the default button styles, you can use the following css:

button, input[type="submit"]{
    color: inherit;
    border: none;
    padding: 0;
    font: inherit;
    cursor: pointer;
    outline: inherit;
}

from this SO question

align textbox and text/labels in html?

I have found better option,

<style type="text/css">
    .form {
        margin: 0 auto;
        width: 210px;
    }
    .form label{
        display: inline-block;
        text-align: right;
        float: left;
    }
    .form input{
        display: inline-block;
        text-align: left;
        float: right;
    }
</style>

Demo here: https://jsfiddle.net/durtpwvx/

Jquery Setting Value of Input Field

This should work.

$(".formData").val("valuesgoeshere")

For empty

$(".formData").val("")

If this does not work, you should post a jsFiddle.

Demo:

_x000D_
_x000D_
$(function() {_x000D_
  $(".resetInput").on("click", function() {_x000D_
    $(".formData").val("");_x000D_
  });_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="text" class="formData" value="yoyoyo">_x000D_
_x000D_
_x000D_
<button class="resetInput">Click Here to reset</button>
_x000D_
_x000D_
_x000D_

How to Add a Dotted Underline Beneath HTML Text

You can try this method:

<h2 style="text-decoration: underline; text-underline-position: under; text-decoration-style: dotted">Hello World!</h2>

Please note that without text-underline-position: under; you still will have a dotted underline but this property will give it more breathing space.

This is assuming you want to embed everything inside an HTML file using inline styling and not to use a separate CSS file or tag.

Using import fs from 'fs'

Building on RobertoNovelo's answer:

import * as fs from 'fs';

is currently the simplest way to do it.

It was tested with a Node.js project (Node.js v10.15.3), with esm, allowing to use import.

Getting an Embedded YouTube Video to Auto Play and Loop

All of the answers didn't work for me, I checked the playlist URL and seen that playlist parameter changed to list! So it should be:

&loop=1&list=PLvNxGp1V1dOwpDBl7L3AJIlkKYdNDKUEs

So here is the full code I use make a clean, looping, autoplay video:

<iframe width="100%" height="425" src="https://www.youtube.com/embed/MavEpJETfgI?autoplay=1&showinfo=0&loop=1&list=PLvNxGp1V1dOwpDBl7L3AJIlkKYdNDKUEs&rel=0" frameborder="0" allowfullscreen></iframe>

Oracle SQL convert date format from DD-Mon-YY to YYYYMM

As offer_date is an number, and is of lower accuracy than your real dates, this may work...
- Convert your real date to a string of format YYYYMM
- Conver that value to an INT
- Compare the result you your offer_date

SELECT
  *
FROM
  offers
WHERE
    offer_date = (SELECT CAST(to_char(create_date, 'YYYYMM') AS INT) FROM customers where id = '12345678')
AND offer_rate > 0 

Also, by doing all the manipulation on the create_date you only do the processing on one value.

Additionally, had you manipulated the offer_date you would not be able to utilise any index on that field, and so force SCANs instead of SEEKs.

What's the difference between a web site and a web application?

I say a website can be a web application, but more often a website has multiple web applications. the relationship between the two is one of composition: website composed of applications.

a dating site might have a photo upload web application, a calendar one so you can mark when you're dating who.

These applications are embedded throughout the website.

Sending email in .NET through Gmail

use this way

MailMessage sendmsg = new MailMessage(SendersAddress, ReceiversAddress, subject, body); 
SmtpClient client = new SmtpClient("smtp.gmail.com");

client.Port = Convert.ToInt32("587");
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("[email protected]","MyPassWord");
client.Send(sendmsg);

Don't forget this :

using System.Net;
using System.Net.Mail;

GitHub "fatal: remote origin already exists"

In the special case that you are creating a new repository starting from an old repository that you used as template (Don't do this if this is not your case). Completely erase the git files of the old repository so you can start a new one:

rm -rf .git

And then restart a new git repository as usual:

git init
git add whatever.wvr ("git add --all" if you want to add all files)
git commit -m "first commit"
git remote add origin [email protected]:ppreyer/first_app.git
git push -u origin master

Javascript checkbox onChange

function calc()
{
  if (document.getElementById('xxx').checked) 
  {
      document.getElementById('totalCost').value = 10;
  } else {
      calculate();
  }
}

HTML

<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>

Creating an empty file in C#

You can chain methods off the returned object, so you can immediately close the file you just opened in a single statement.

File.Open("filename", FileMode.Create).Close();

Get table column names in MySQL?

The easy way, if loading results using assoc is to do this:

$sql = "SELECT p.* FROM (SELECT 1) as dummy LEFT JOIN `product_table` p on null";
$q = $this->db->query($sql);
$column_names = array_keys($q->row);

This you load a single result using this query, you get an array with the table column names as keys and null as value. E.g.

Array(
'product_id' => null,
'sku' => null,
'price' => null,
...
)

after which you can easily get the table column names using the php function array_keys($result)

How to get the week day name from a date?

SQL> SELECT TO_CHAR(date '1982-03-09', 'DAY') day FROM dual;

DAY
---------
TUESDAY

SQL> SELECT TO_CHAR(date '1982-03-09', 'DY') day FROM dual;

DAY
---
TUE

SQL> SELECT TO_CHAR(date '1982-03-09', 'Dy') day FROM dual;

DAY
---
Tue

(Note that the queries use ANSI date literals, which follow the ISO-8601 date standard and avoid date format ambiguity.)

How to read embedded resource text file

By all your powers combined I use this helper class for reading resources from any assembly and any namespace in a generic way.

public class ResourceReader
{
    public static IEnumerable<string> FindEmbededResources<TAssembly>(Func<string, bool> predicate)
    {
        if (predicate == null) throw new ArgumentNullException(nameof(predicate));

        return
            GetEmbededResourceNames<TAssembly>()
                .Where(predicate)
                .Select(name => ReadEmbededResource(typeof(TAssembly), name))
                .Where(x => !string.IsNullOrEmpty(x));
    }

    public static IEnumerable<string> GetEmbededResourceNames<TAssembly>()
    {
        var assembly = Assembly.GetAssembly(typeof(TAssembly));
        return assembly.GetManifestResourceNames();
    }

    public static string ReadEmbededResource<TAssembly, TNamespace>(string name)
    {
        if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));
        return ReadEmbededResource(typeof(TAssembly), typeof(TNamespace), name);
    }

    public static string ReadEmbededResource(Type assemblyType, Type namespaceType, string name)
    {
        if (assemblyType == null) throw new ArgumentNullException(nameof(assemblyType));
        if (namespaceType == null) throw new ArgumentNullException(nameof(namespaceType));
        if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));

        return ReadEmbededResource(assemblyType, $"{namespaceType.Namespace}.{name}");
    }

    public static string ReadEmbededResource(Type assemblyType, string name)
    {
        if (assemblyType == null) throw new ArgumentNullException(nameof(assemblyType));
        if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));

        var assembly = Assembly.GetAssembly(assemblyType);
        using (var resourceStream = assembly.GetManifestResourceStream(name))
        {
            if (resourceStream == null) return null;
            using (var streamReader = new StreamReader(resourceStream))
            {
                return streamReader.ReadToEnd();
            }
        }
    }
}

How to convert a Java object (bean) to key-value pairs (and vice versa)?

Probably late to the party. You can use Jackson and convert it into a Properties object. This is suited for Nested classes and if you want the key in the for a.b.c=value.

JavaPropsMapper mapper = new JavaPropsMapper();
Properties properties = mapper.writeValueAsProperties(sct);
Map<Object, Object> map = properties;

if you want some suffix, then just do

SerializationConfig config = mapper.getSerializationConfig()
                .withRootName("suffix");
mapper.setConfig(config);

need to add this dependency

<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-properties</artifactId>
</dependency>

Matrix Multiplication in pure Python?

Here's some short and simple code for matrix/vector routines in pure Python that I wrote many years ago:

'''Basic Table, Matrix and Vector functions for Python 2.2
   Author:   Raymond Hettinger    
'''

Version = 'File MATFUNC.PY, Ver 183, Date 12-Dec-2002,14:33:42'

import operator, math, random
NPRE, NPOST = 0, 0                    # Disables pre and post condition checks

def iszero(z):  return abs(z) < .000001
def getreal(z):
    try:
        return z.real
    except AttributeError:
        return z
def getimag(z):
    try:
        return z.imag
    except AttributeError:
        return 0
def getconj(z):
    try:
        return z.conjugate()
    except AttributeError:
        return z


separator = [ '', '\t', '\n', '\n----------\n', '\n===========\n' ]

class Table(list):
    dim = 1
    concat = list.__add__      # A substitute for the overridden __add__ method
    def __getslice__( self, i, j ):
        return self.__class__( list.__getslice__(self,i,j) )
    def __init__( self, elems ):
        list.__init__( self, elems )
        if len(elems) and hasattr(elems[0], 'dim'): self.dim = elems[0].dim + 1
    def __str__( self ):
        return separator[self.dim].join( map(str, self) )
    def map( self, op, rhs=None ):
        '''Apply a unary operator to every element in the matrix or a binary operator to corresponding
        elements in two arrays.  If the dimensions are different, broadcast the smaller dimension over
        the larger (i.e. match a scalar to every element in a vector or a vector to a matrix).'''
        if rhs is None:                                                 # Unary case
            return self.dim==1 and self.__class__( map(op, self) ) or self.__class__( [elem.map(op) for elem in self] )
        elif not hasattr(rhs,'dim'):                                    # List / Scalar op
            return self.__class__( [op(e,rhs) for e in self] )
        elif self.dim == rhs.dim:                                       # Same level Vec / Vec or Matrix / Matrix
            assert NPRE or len(self) == len(rhs), 'Table operation requires len sizes to agree'
            return self.__class__( map(op, self, rhs) )
        elif self.dim < rhs.dim:                                        # Vec / Matrix
            return self.__class__( [op(self,e) for e in rhs]  )
        return self.__class__( [op(e,rhs) for e in self] )         # Matrix / Vec
    def __mul__( self, rhs ):  return self.map( operator.mul, rhs )
    def __div__( self, rhs ):  return self.map( operator.div, rhs )
    def __sub__( self, rhs ):  return self.map( operator.sub, rhs )
    def __add__( self, rhs ):  return self.map( operator.add, rhs )
    def __rmul__( self, lhs ):  return self*lhs
    def __rdiv__( self, lhs ):  return self*(1.0/lhs)
    def __rsub__( self, lhs ):  return -(self-lhs)
    def __radd__( self, lhs ):  return self+lhs
    def __abs__( self ): return self.map( abs )
    def __neg__( self ): return self.map( operator.neg )
    def conjugate( self ): return self.map( getconj )
    def real( self ): return self.map( getreal  )
    def imag( self ): return self.map( getimag )
    def flatten( self ):
        if self.dim == 1: return self
        return reduce( lambda cum, e: e.flatten().concat(cum), self, [] )
    def prod( self ):  return reduce(operator.mul, self.flatten(), 1.0)
    def sum( self ):  return reduce(operator.add, self.flatten(), 0.0)
    def exists( self, predicate ):
        for elem in self.flatten():
            if predicate(elem):
                return 1
        return 0
    def forall( self, predicate ):
        for elem in self.flatten():
            if not predicate(elem):
                return 0
        return 1
    def __eq__( self, rhs ):  return (self - rhs).forall( iszero )

class Vec(Table):
    def dot( self, otherVec ):  return reduce(operator.add, map(operator.mul, self, otherVec), 0.0)
    def norm( self ):  return math.sqrt(abs( self.dot(self.conjugate()) ))
    def normalize( self ):  return self / self.norm()
    def outer( self, otherVec ):  return Mat([otherVec*x for x in self])
    def cross( self, otherVec ):
        'Compute a Vector or Cross Product with another vector'
        assert len(self) == len(otherVec) == 3, 'Cross product only defined for 3-D vectors'
        u, v = self, otherVec
        return Vec([ u[1]*v[2]-u[2]*v[1], u[2]*v[0]-u[0]*v[2], u[0]*v[1]-u[1]*v[0] ])
    def house( self, index ):
        'Compute a Householder vector which zeroes all but the index element after a reflection'
        v = Vec( Table([0]*index).concat(self[index:]) ).normalize()
        t = v[index]
        sigma = 1.0 - t**2
        if sigma != 0.0:
            t = v[index] = t<=0 and t-1.0 or -sigma / (t + 1.0)
            v /= t
        return v, 2.0 * t**2 / (sigma + t**2)
    def polyval( self, x ):
        'Vec([6,3,4]).polyval(5) evaluates to 6*x**2 + 3*x + 4 at x=5'
        return reduce( lambda cum,c: cum*x+c, self, 0.0 )
    def ratval( self, x ):
        'Vec([10,20,30,40,50]).ratfit(5) evaluates to (10*x**2 + 20*x + 30) / (40*x**2 + 50*x + 1) at x=5.'
        degree = len(self) / 2
        num, den = self[:degree+1], self[degree+1:] + [1]
        return num.polyval(x) / den.polyval(x)

class Matrix(Table):
    __slots__ = ['size', 'rows', 'cols']
    def __init__( self, elems ):
        'Form a matrix from a list of lists or a list of Vecs'
        Table.__init__( self, hasattr(elems[0], 'dot') and elems or map(Vec,map(tuple,elems)) )
        self.size = self.rows, self.cols = len(elems), len(elems[0])
    def tr( self ):
        'Tranpose elements so that Transposed[i][j] = Original[j][i]'
        return Mat(zip(*self))
    def star( self ):
        'Return the Hermetian adjoint so that Star[i][j] = Original[j][i].conjugate()'
        return self.tr().conjugate()
    def diag( self ):
        'Return a vector composed of elements on the matrix diagonal'
        return Vec( [self[i][i] for i in range(min(self.size))] )
    def trace( self ): return self.diag().sum()
    def mmul( self, other ):
        'Matrix multiply by another matrix or a column vector '
        if other.dim==2: return Mat( map(self.mmul, other.tr()) ).tr()
        assert NPRE or self.cols == len(other)
        return Vec( map(other.dot, self) )
    def augment( self, otherMat ):
        'Make a new matrix with the two original matrices laid side by side'
        assert self.rows == otherMat.rows, 'Size mismatch: %s * %s' % (`self.size`, `otherMat.size`)
        return Mat( map(Table.concat, self, otherMat) )
    def qr( self, ROnly=0 ):
        'QR decomposition using Householder reflections: Q*R==self, Q.tr()*Q==I(n), R upper triangular'
        R = self
        m, n = R.size
        for i in range(min(m,n)):
            v, beta = R.tr()[i].house(i)
            R -= v.outer( R.tr().mmul(v)*beta )
        for i in range(1,min(n,m)): R[i][:i] = [0] * i
        R = Mat(R[:n])
        if ROnly: return R
        Q = R.tr().solve(self.tr()).tr()       # Rt Qt = At    nn  nm  = nm
        self.qr = lambda r=0, c=`self`: not r and c==`self` and (Q,R) or Matrix.qr(self,r) #Cache result
        assert NPOST or m>=n and Q.size==(m,n) and isinstance(R,UpperTri) or m<n and Q.size==(m,m) and R.size==(m,n)
        assert NPOST or Q.mmul(R)==self and Q.tr().mmul(Q)==eye(min(m,n))
        return Q, R
    def _solve( self, b ):
        '''General matrices (incuding) are solved using the QR composition.
        For inconsistent cases, returns the least squares solution'''
        Q, R = self.qr()
        return R.solve( Q.tr().mmul(b) )
    def solve( self, b ):
        'Divide matrix into a column vector or matrix and iterate to improve the solution'
        if b.dim==2: return Mat( map(self.solve, b.tr()) ).tr()
        assert NPRE or self.rows == len(b), 'Matrix row count %d must match vector length %d' % (self.rows, len(b))
        x = self._solve( b )
        diff = b - self.mmul(x)
        maxdiff = diff.dot(diff)
        for i in range(10):
            xnew = x + self._solve( diff )
            diffnew = b - self.mmul(xnew)
            maxdiffnew = diffnew.dot(diffnew)
            if maxdiffnew >= maxdiff:  break
            x, diff, maxdiff = xnew, diffnew, maxdiffnew
            #print >> sys.stderr, i+1, maxdiff
        assert NPOST or self.rows!=self.cols or self.mmul(x) == b
        return x
    def rank( self ):  return Vec([ not row.forall(iszero) for row in self.qr(ROnly=1) ]).sum()

class Square(Matrix):
    def lu( self ):
        'Factor a square matrix into lower and upper triangular form such that L.mmul(U)==A'
        n = self.rows
        L, U = eye(n), Mat(self[:])
        for i in range(n):
            for j in range(i+1,U.rows):
                assert U[i][i] != 0.0, 'LU requires non-zero elements on the diagonal'
                L[j][i] = m = 1.0 * U[j][i] / U[i][i]
                U[j] -= U[i] * m
        assert NPOST or isinstance(L,LowerTri) and isinstance(U,UpperTri) and L*U==self
        return L, U
    def __pow__( self, exp ):
        'Raise a square matrix to an integer power (i.e. A**3 is the same as A.mmul(A.mmul(A))'
        assert NPRE or exp==int(exp) and exp>0, 'Matrix powers only defined for positive integers not %s' % exp
        if exp == 1: return self
        if exp&1: return self.mmul(self ** (exp-1))
        sqrme = self ** (exp/2)
        return sqrme.mmul(sqrme)
    def det( self ):  return self.qr( ROnly=1 ).det()
    def inverse( self ):  return self.solve( eye(self.rows) )
    def hessenberg( self ):
        '''Householder reduction to Hessenberg Form (zeroes below the diagonal)
        while keeping the same eigenvalues as self.'''
        for i in range(self.cols-2):
            v, beta = self.tr()[i].house(i+1)
            self -= v.outer( self.tr().mmul(v)*beta )
            self -= self.mmul(v).outer(v*beta)
        return self
    def eigs( self ):
        'Estimate principal eigenvalues using the QR with shifts method'
        origTrace, origDet = self.trace(), self.det()
        self = self.hessenberg()
        eigvals = Vec([])
        for i in range(self.rows-1,0,-1):
            while not self[i][:i].forall(iszero):
                shift = eye(i+1) * self[i][i]
                q, r = (self - shift).qr()
                self = r.mmul(q) + shift
            eigvals.append( self[i][i] )
            self = Mat( [self[r][:i] for r in range(i)] )
        eigvals.append( self[0][0] )
        assert NPOST or iszero( (abs(origDet) - abs(eigvals.prod())) / 1000.0 )
        assert NPOST or iszero( origTrace - eigvals.sum() )
        return Vec(eigvals)

class Triangular(Square):
    def eigs( self ):  return self.diag()
    def det( self ):  return self.diag().prod()

class UpperTri(Triangular):
    def _solve( self, b ):
        'Solve an upper triangular matrix using backward substitution'
        x = Vec([])
        for i in range(self.rows-1, -1, -1):
            assert NPRE or self[i][i], 'Backsub requires non-zero elements on the diagonal'
            x.insert(0, (b[i] - x.dot(self[i][i+1:])) / self[i][i] )
        return x

class LowerTri(Triangular):
    def _solve( self, b ):
        'Solve a lower triangular matrix using forward substitution'
        x = Vec([])
        for i in range(self.rows):
            assert NPRE or self[i][i], 'Forward sub requires non-zero elements on the diagonal'
            x.append( (b[i] - x.dot(self[i][:i])) / self[i][i] )
        return x

def Mat( elems ):
    'Factory function to create a new matrix.'
    m, n = len(elems), len(elems[0])
    if m != n: return Matrix(elems)
    if n <= 1: return Square(elems)
    for i in range(1, len(elems)):
        if not iszero( max(map(abs, elems[i][:i])) ):
            break
    else: return UpperTri(elems)
    for i in range(0, len(elems)-1):
        if not iszero( max(map(abs, elems[i][i+1:])) ):
            return Square(elems)
    return LowerTri(elems)


def funToVec( tgtfun, low=-1, high=1, steps=40, EqualSpacing=0 ):
    '''Compute x,y points from evaluating a target function over an interval (low to high)
    at evenly spaces points or with Chebyshev abscissa spacing (default) '''
    if EqualSpacing:
        h = (0.0+high-low)/steps
        xvec = [low+h/2.0+h*i for i in range(steps)]
    else:
        scale, base = (0.0+high-low)/2.0, (0.0+high+low)/2.0
        xvec = [base+scale*math.cos(((2*steps-1-2*i)*math.pi)/(2*steps)) for i in range(steps)]
    yvec = map(tgtfun, xvec)
    return Mat( [xvec, yvec] )

def funfit( (xvec, yvec), basisfuns ):
    'Solves design matrix for approximating to basis functions'
    return Mat([ map(form,xvec) for form in basisfuns ]).tr().solve(Vec(yvec))

def polyfit( (xvec, yvec), degree=2 ):
    'Solves Vandermonde design matrix for approximating polynomial coefficients'
    return Mat([ [x**n for n in range(degree,-1,-1)] for x in xvec ]).solve(Vec(yvec))

def ratfit( (xvec, yvec), degree=2 ):
    'Solves design matrix for approximating rational polynomial coefficients (a*x**2 + b*x + c)/(d*x**2 + e*x + 1)'
    return Mat([[x**n for n in range(degree,-1,-1)]+[-y*x**n for n in range(degree,0,-1)] for x,y in zip(xvec,yvec)]).solve(Vec(yvec))

def genmat(m, n, func):
    if not n: n=m
    return Mat([ [func(i,j) for i in range(n)] for j in range(m) ])

def zeroes(m=1, n=None):
    'Zero matrix with side length m-by-m or m-by-n.'
    return genmat(m,n, lambda i,j: 0)

def eye(m=1, n=None):
    'Identity matrix with side length m-by-m or m-by-n'
    return genmat(m,n, lambda i,j: i==j)

def hilb(m=1, n=None):
    'Hilbert matrix with side length m-by-m or m-by-n.  Elem[i][j]=1/(i+j+1)'
    return genmat(m,n, lambda i,j: 1.0/(i+j+1.0))

def rand(m=1, n=None):
    'Random matrix with side length m-by-m or m-by-n'
    return genmat(m,n, lambda i,j: random.random())

if __name__ == '__main__':
    import cmath
    a = Table([1+2j,2,3,4])
    b = Table([5,6,7,8])
    C = Table([a,b])
    print 'a+b', a+b
    print '2+a', 2+a
    print 'a/5.0', a/5.0
    print '2*a+3*b', 2*a+3*b
    print 'a+C', a+C
    print '3+C', 3+C
    print 'C+b', C+b
    print 'C.sum()', C.sum()
    print 'C.map(math.cos)', C.map(cmath.cos)
    print 'C.conjugate()', C.conjugate()
    print 'C.real()', C.real()

    print zeroes(3)
    print eye(4)
    print hilb(3,5)

    C = Mat( [[1,2,3], [4,5,1,], [7,8,9]] )
    print C.mmul( C.tr()), '\n'
    print C ** 5, '\n'
    print C + C.tr(), '\n'

    A = C.tr().augment( Mat([[10,11,13]]).tr() ).tr()
    q, r = A.qr()
    assert q.mmul(r) == A
    assert q.tr().mmul(q)==eye(3)
    print 'q:\n', q, '\nr:\n', r, '\nQ.tr()&Q:\n', q.tr().mmul(q), '\nQ*R\n', q.mmul(r), '\n'
    b = Vec([50, 100, 220, 321])
    x = A.solve(b)
    print 'x:  ', x
    print 'b:  ', b
    print 'Ax: ', A.mmul(x)

    inv = C.inverse()
    print '\ninverse C:\n', inv, '\nC * inv(C):\n', C.mmul(inv)
    assert C.mmul(inv) == eye(3)

    points = (xvec,yvec) = funToVec(lambda x: math.sin(x)+2*math.cos(.7*x+.1), low=0, high=3, EqualSpacing=1)
    basis = [lambda x: math.sin(x), lambda x: math.exp(x), lambda x: x**2]
    print 'Func coeffs:', funfit( points, basis )
    print 'Poly coeffs:', polyfit( points, degree=5 )
    points = (xvec,yvec) = funToVec(lambda x: math.sin(x)+2*math.cos(.7*x+.1), low=0, high=3)
    print 'Rational coeffs:', ratfit( points )

    print polyfit(([1,2,3,4], [1,4,9,16]), 2)

    mtable = Vec([1,2,3]).outer(Vec([1,2]))
    print mtable, mtable.size

    A = Mat([ [2,0,3], [1,5,1], [18,0,6] ])
    print 'A:'
    print A
    print 'eigs:'
    print A.eigs()
    print 'Should be:', Vec([11.6158, 5.0000, -3.6158])
    print 'det(A)'
    print A.det()

    c = Mat( [[1,2,30],[4,5,10],[10,80,9]] )     # Failed example from Konrad Hinsen
    print 'C:\n', c
    print c.eigs()
    print 'Should be:', Vec([-8.9554, 43.2497, -19.2943])

    A = Mat([ [1,2,3,4], [4,5,6,7], [2,1,5,0], [4,2,1,0] ] )    # Kincaid and Cheney p.326
    print 'A:\n', A
    print A.eigs()
    print 'Should be:', Vec([3.5736, 0.1765, 11.1055, -3.8556])

    A = rand(3)
    q,r = A.qr()
    s,t = A.qr()
    print q is s                # Test caching
    print r is t
    A[1][1] = 1.1               # Invalidate the cache
    u,v = A.qr()
    print q is u                # Verify old result not used
    print r is v
    print u.mmul(v) == A        # Verify new result

    print 'Test qr on 3x5 matrix'
    a = rand(3,5)
    q,r = a.qr()
    print q.mmul(r) == a
    print q.tr().mmul(q) == eye(3)

Maven: The packaging for this project did not assign a file to the build artifact

TL;DR To fix this issue, invoke packaging plugin before, e.g. for jar packaging use maven-jar-plugin , as following:

mvn jar:jar install:install

Or

mvn jar:jar deploy:deploy 

If you actually needed to deploy.

Gotcha This approach won't work if you have multi-module project with different packagings (ear/war/jar/zip) – even worse, wrong artifacts will be installed/deployed! In such case use reactor options to only build the deployable module (e.g. the war).


Explanation

In some cases you actually want to run directly a install:install or deploy:deploy goal (that is, from the maven-deploy-plugin, the deploy goal, not the Maven deploy phase) and you would end up in the annoying The packaging for this project did not assign a file to the build artifact.

A classic example is a CI job (a Jenkins or Bamboo job, e.g.) where in different steps you want to execute/care about different aspects:

  • A first step would be a mvn clean install, performing tests and test coverage
  • A second step would be a Sonarqube analysis based on a quality profile, e.g. mvn sonar:sonar plus further options
  • Then, and only after successful tests execution and quality gate passed, you want to deploy to your Maven enterprise repository the final project artifacts, yet you don't want to re-run mvn deploy, because it would again execute previous phases (and compile, test, etc.) and you want your build to be effective but yet fast.

Yes, you could speed up this last step at least skipping tests (compilation and execution, via -Dmaven.test.skip=true) or play with a particular profile (to skip as many plugins as possible), but it is much easier and clear to simply run mvn deploy:deploy then.

But it would fail with the error above, because as also specified by the plugin FAQ:

During the packaging-phase all gathered and placed in context. With this mechanism Maven can ensure that the maven-install-plugin and maven-deploy-plugin are copying/uploading the same set of files. So when you only execute deploy:deploy, then there are no files put in the context and there is nothing to deploy.

Indeed, the deploy:deploy needs some runtime information placed in the build context by previous phases (or previous plugins/goals executions).

It has also reported as a potential bug: MDEPLOY-158: deploy:deploy does not work for only Deploying artifact to Maven Remote repo

But then rejected as not a problem.

The deployAtEnd configuration option of the maven-deploy-plugin won't help neither in certain scenarios because we have intermediate job steps to execute:

Whether every project should be deployed during its own deploy-phase or at the end of the multimodule build. If set to true and the build fails, none of the reactor projects is deployed. (experimental)

So, how to fix it?
Simply run the following in such a similar third/last step:

mvn jar:jar deploy:deploy

The maven-jar-plugin will not re-create any jar as part of your build, thanks to its forceCreation option set to false by default:

Require the jar plugin to build a new JAR even if none of the contents appear to have changed. By default, this plugin looks to see if the output jar exists and inputs have not changed. If these conditions are true, the plugin skips creation of the jar.

But it will nicely populate the build context for us and make deploy:deploy happy. No tests to skip, no profiles to add. Just what you need: speed.


Additional note: if you are using the build-helper-maven-plugin, buildnumber-maven-plugin or any other similar plugin to generate meta-data later on used by the maven-jar-plugin (e.g. entries for the Manifest file), you most probably have executions linked to the validate phase and you still want to have them during the jar:jar build step (and yet keep a fast execution). In this case the almost harmless overhead is to invoke the validate phase as following:

mvn validate jar:jar deploy:deploy

Yet another additional note: if you have not jar but, say, war packaging, use war:war before install/deploy instead.

Gotcha as pointed out above, check behavior in multi module projects.

(Mac) -bash: __git_ps1: command not found

I had same problem when upgrading to Yosemite.

I just had to modify ~/.bashrc to source /usr/local/etc/bash_completion.d/git-prompt.sh instead of the old path.

then re-source your . ~/.bashrc to get the effect.

Passing multiple values for a single parameter in Reporting Services

This works great for me:

WHERE CHARINDEX(CONVERT(nvarchar, CustNum), @CustNum) > 0

expand/collapse table rows with JQuery

using jQuery it's easy...

 $('YOUR CLASS SELECTOR').click(function(){

            $(this).toggle();
});

Putting HTML inside Html.ActionLink(), plus No Link Text?

Here is an uber expansion of @tvanfosson's answer. I was inspired by it and decide to make it more generic.

    public static MvcHtmlString NestedActionLink(this HtmlHelper htmlHelper, string linkText, string actionName,
        string controllerName, object routeValues = null, object htmlAttributes = null,
        RouteValueDictionary childElements = null)
    {
        var htmlAttributesDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

        if (childElements != null)
        {
            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);

            var anchorTag = new TagBuilder("a");
            anchorTag.MergeAttribute("href",
                routeValues == null
                    ? urlHelper.Action(actionName, controllerName)
                    : urlHelper.Action(actionName, controllerName, routeValues));
            anchorTag.MergeAttributes(htmlAttributesDictionary);
            TagBuilder childTag = null;

            if (childElements != null)
            {
                foreach (var childElement in childElements)
                {
                    childTag = new TagBuilder(childElement.Key.Split('|')[0]);
                    object elementAttributes;
                    childElements.TryGetValue(childElement.Key, out elementAttributes);

                    var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(elementAttributes);

                    foreach (var attribute in attributes)
                    {
                        switch (attribute.Key)
                        {
                            case "@class":
                                childTag.AddCssClass(attribute.Value.ToString());
                                break;
                            case "InnerText":
                                childTag.SetInnerText(attribute.Value.ToString());
                                break;
                            default:
                                childTag.MergeAttribute(attribute.Key, attribute.Value.ToString());
                                break;
                        }
                    }
                    childTag.ToString(TagRenderMode.SelfClosing);
                    if (childTag != null) anchorTag.InnerHtml += childTag.ToString();
                }                    
            }
            return MvcHtmlString.Create(anchorTag.ToString(TagRenderMode.Normal));
        }
        else
        {
            return htmlHelper.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributesDictionary);
        }
    }

Android Text over image

You may want to take if from a diffrent side: It seems easier to have a TextView with a drawable on the background:

 <TextView
            android:id="@+id/text"
            android:background="@drawable/rounded_rectangle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
        </TextView>

RegEx for valid international mobile phone number

Even though it is about international numbers I would want the code to be like :

/^(\+|\d)[0-9]{7,16}$/;

As you can have international numbers starting with '00' as well.

Why I prefer 15 digits : http://en.wikipedia.org/wiki/E.164

Replacing Pandas or Numpy Nan with a None to use with MysqlDB

You can replace nan with None in your numpy array:

>>> x = np.array([1, np.nan, 3])
>>> y = np.where(np.isnan(x), None, x)
>>> print y
[1.0 None 3.0]
>>> print type(y[1])
<type 'NoneType'>

jQuery or Javascript - how to disable window scroll without overflow:hidden;

Plenty of good ideas on this thread. I have a lot of popups in my page for handling user input. What I use, is a combination of disabling the mousewheel and hiding the scrollbar:

this.disableScrollFn= function(e) { 
    e.preventDefault(); e.stopPropagation() 
};
document.body.style.overflow = 'hidden';
$('body').on('mousewheel', this.disableScrollFn);

Advantage of this is we stop the user from scrolling in any possible way, and without having to change css position and top properties. I'm not concerened about touch events, since touch outside would close the popup.

To disable this, upon closing the popup I do the following.

document.body.style.overflow = 'auto';
$('body').off('mousewheel', this.disableScrollFn);

Note, I store a reference to my disableScrollFn on the existing object (in my case a PopupViewModel), for that gets triggered upon closing the popup to have access to disableScrollFn.

pandas dataframe create new columns and fill with calculated values from same df

In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])

In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]: 
          A         B         C         D
1  0.319124  0.296653  0.138206  0.246017
2  0.376994  0.326481  0.230464  0.066062
3  0.036134  0.192954  0.430341  0.340571

How to make a <div> or <a href="#"> to align center

You can use the code below:

a {
display: block;
width: 113px;
margin: auto; 
}

By setting, in my case, the link to display:block, it is easier to position the link.
This works the same when you use a <div> tag/class.
You can pick any width you want.

Twitter bootstrap hide element on small devices

<div class="small hidden-xs">
    Some Content Here
</div>

This also works for elements not necessarily used in a grid /small column. When it is rendered on larger screens the font-size will be smaller than your default text font-size.

This answer satisfies the question in the OP title (which is how I found this Q/A).

How to get the Enum Index value in C#

You can directly cast it:

enum MyMonthEnum { January = 1, February, March, April, May, June, July, August, September, October, November, December };

public static string GetMyMonthName(int MonthIndex)
{
  MyMonthEnum MonthName = (MyMonthEnum)MonthIndex;
  return MonthName.ToString();
}

For Example:

string MySelectedMonthName=GetMyMonthName(8);
 //then MySelectedMonthName value will be August.

Add quotation at the start and end of each line in Notepad++

  • Place your cursor at the end of the text.
  • Press SHIFT and ->. The cursor will move to the next line.
  • Press CTRL-F and type , in "Replace with:" and press ENTER.

You will need to put a quote at the beginning of your first text and the end of your last.

How to set the height of table header in UITableView?

In Xcode 10 you can set header and footer of section hight from "Size Inspector" tab

Size Inspector header

How do I assign a null value to a variable in PowerShell?

These are automatic variables, like $null, $true, $false etc.

about_Automatic_Variables, see https://technet.microsoft.com/en-us/library/hh847768.aspx?f=255&MSPPError=-2147217396

$NULL
$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.

Windows PowerShell treats $null as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.

For example, when $null is included in a collection, it is counted as one of the objects.

C:\PS> $a = ".dir", $null, ".pdf"
C:\PS> $a.count
3

If you pipe the $null variable to the ForEach-Object cmdlet, it generates a value for $null, just as it does for the other objects.

PS C:\ps-test> ".dir", $null, ".pdf" | Foreach {"Hello"}
Hello
Hello
Hello

As a result, you cannot use $null to mean "no parameter value." A parameter value of $null overrides the default parameter value.

However, because Windows PowerShell treats the $null variable as a placeholder, you can use it scripts like the following one, which would not work if $null were ignored.

$calendar = @($null, $null, “Meeting”, $null, $null, “Team Lunch”, $null)
$days = Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"
$currentDay = 0

foreach($day in $calendar)
{
    if($day –ne $null)
    {
        "Appointment on $($days[$currentDay]): $day"
    }

    $currentDay++
}

output:

Appointment on Tuesday: Meeting
Appointment on Friday: Team lunch

onchange equivalent in angular2

We can use Angular event bindings to respond to any DOM event. The syntax is simple. We surround the DOM event name in parentheses and assign a quoted template statement to it. -- reference

Since change is on the list of standard DOM events, we can use it:

(change)="saverange()"

In your particular case, since you're using NgModel, you could break up the two-way binding like this instead:

[ngModel]="range" (ngModelChange)="saverange($event)"

Then

saverange(newValue) {
  this.range = newValue;
  this.Platform.ready().then(() => {
     this.rootRef.child("users").child(this.UserID).child('range').set(this.range)
  })
} 

However, with this approach saverange() is called with every keystroke, so you're probably better off using (change).

Regular expression to match exact number of characters?

Your solution is correct, but there is some redundancy in your regex.
The similar result can also be obtained from the following regex:

^([A-Z]{3})$

The {3} indicates that the [A-Z] must appear exactly 3 times.

How do I paste multi-line bash codes into terminal and run it all at once?

I'm really surprised this answer isn't offered here, I was in search of a solution to this question and I think this is the easiest approach, and more flexible/forgiving...

If you'd like to paste multiple lines from a website/text editor/etc., into bash, regardless of whether it's commands per line or a function or entire script... simply start with a ( and end with a ) and Enter, like in the following example:

If I had the following blob

function hello {
    echo Hello!
}
hello

You can paste and verify in a terminal using bash by:

  1. Starting with (

  2. Pasting your text, and pressing Enter (to make it pretty)... or not

  3. Ending with a ) and pressing Enter

Example:

imac:~ home$ ( function hello {
>     echo Hello!
> }
> hello
> )
Hello!
imac:~ home$ 

The pasted text automatically gets continued with a prepending > for each line. I've tested with multiple lines with commands per line, functions and entire scripts. Hope this helps others save some time!

Getting index value on razor foreach

All of the above answers require logic in the view. Views should be dumb and contain as little logic as possible. Why not create properties in your view model that correspond to position in the list eg:

public int Position {get; set}

In your view model builder you set the position 1 through 4.

BUT .. there is even a cleaner way. Why not make the CSS class a property of your view model? So instead of the switch statement in your partial, you would just do this:

<div class="@Model.GridCSS">

Move the switch statement to your view model builder and populate the CSS class there.

How to get Printer Info in .NET?

Please notice that the article that dowski and Panos was reffering to (MSDN Win32_Printer) can be a little misleading.

I'm referring the first value of most of the arrays. some begins with 1 and some begins with 0. for example, "ExtendedPrinterStatus" first value in table is 1, therefore, your array should be something like this:

string[] arrExtendedPrinterStatus = { 
    "","Other", "Unknown", "Idle", "Printing", "Warming Up",
    "Stopped Printing", "Offline", "Paused", "Error", "Busy",
    "Not Available", "Waiting", "Processing", "Initialization",
    "Power Save", "Pending Deletion", "I/O Active", "Manual Feed"
};

and on the other hand, "ErrorState" first value in table is 0, therefore, your array should be something like this:

string[] arrErrorState = {
    "Unknown", "Other", "No Error", "Low Paper", "No Paper", "Low Toner",
    "No Toner", "Door Open", "Jammed", "Offline", "Service Requested",
    "Output Bin Full"
};

BTW, "PrinterState" is obsolete, but you can use "PrinterStatus".

React native ERROR Packager can't listen on port 8081

That picture indeed shows that your 8081 is not in use. If suggestions above haven't helped, and your mobile device is connected to your computer via usb (and you have Android 5.0 (Lollipop) or above) you could try:

$ adb reconnect

This is not necessary in most cases, but just in case, let's reset your connection with your mobile and restart adb server. Finally:

$ adb reverse tcp:8081 tcp:8081

So, whenever your mobile device tries to access any port 8081 on itself it will be routed to the 8081 port on your PC.

Or, one could try

$ killall node

Oracle PL/SQL - Raise User-Defined Exception With Custom SQLERRM

declare
   z exception;

begin
   if to_char(sysdate,'day')='sunday' then
     raise z;
   end if;

   exception 
     when z then
        dbms_output.put_line('to day is sunday');
end;

Is there a JSON equivalent of XQuery/XPath?

JMESPath seems to be very popular these days (as of 2020) and addresses a number of issues with JSONPath. It's available for many languages.

How do I write a SQL query for a specific date range and date time using SQL Server 2008?

Infact this worked for me

 SELECT * 
 FROM myTable
 WHERE CAST(ReadDate AS DATETIME) + ReadTime BETWEEN '2010-09-16 5:00PM' AND '2010-09-21 9:00AM'

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

The bug referred to in another answer is addressed by URIUtils in Apache HttpComponents

public static URI resolve(URI baseURI,
                          String reference)

Resolves a URI reference against a base URI. Work-around for bug in java.net.URI ()

Are vectors passed to functions by value or by reference in C++

when we pass vector by value in a function as an argument,it simply creates the copy of vector and no any effect happens on the vector which is defined in main function when we call that particular function. while when we pass vector by reference whatever is written in that particular function, every action will going to perform on the vector which is defined in main or other function when we call that particular function.

Padding zeros to the left in postgreSQL

The to_char() function is there to format numbers:

select to_char(column_1, 'fm000') as column_2
from some_table;

The fm prefix ("fill mode") avoids leading spaces in the resulting varchar. The 000 simply defines the number of digits you want to have.

psql (9.3.5)
Type "help" for help.

postgres=> with sample_numbers (nr) as (
postgres(>     values (1),(11),(100)
postgres(> )
postgres-> select to_char(nr, 'fm000')
postgres-> from sample_numbers;
 to_char
---------
 001
 011
 100
(3 rows)

postgres=>

For more details on the format picture, please see the manual:
http://www.postgresql.org/docs/current/static/functions-formatting.html

Returning value that was passed into a method

The generic Returns<T> method can handle this situation nicely.

_mock.Setup(x => x.DoSomething(It.IsAny<string>())).Returns<string>(x => x);

Or if the method requires multiple inputs, specify them like so:

_mock.Setup(x => x.DoSomething(It.IsAny<string>(), It.IsAny<int>())).Returns((string x, int y) => x);

JavaScript click event listener on class

Yow can use querySelectorAll to select all the classes and loop through them to assign the eventListener. The if condition checks if it contains the class name.

const arrClass = document.querySelectorAll(".className");
for (let i of arrClass) {
  i.addEventListener("click", (e) => {
    if (e.target.classList.contains("className")) {
        console.log("Perfrom Action")
    }
  })
}

Entity Framework and SQL Server View

Due to the above mentioned problems, I prefer table value functions.

If you have this:

CREATE VIEW [dbo].[MyView] AS SELECT A, B FROM dbo.Something

create this:

CREATE FUNCTION MyFunction() RETURNS TABLE AS RETURN (SELECT * FROM [dbo].[MyView])

Then you simply import the function rather than the view.

Get top most UIViewController

Use this code to find top most UIViewController

func getTopViewController() -> UIViewController? {
    var topController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController
    while topController?.presentedViewController != nil {
        topController = topController?.presentedViewController
    }
    return topController
}

Last non-empty cell in a column

for textual data:

EQUIV("";A1:A10;-1)

for numerical data:

EQUIV(0;A1:A10;-1)

This give you the relative index of the last non empty cell in the range selected (here A1:A10).

If you want to get the value, access it via INDIRECT after building -textually- the absolute cell reference, eg:

INDIRECT("A" & (nb_line_where_your_data_start + EQUIV(...) - 1))

How to trap on UIViewAlertForUnsatisfiableConstraints?

Whenever I attempt to remove the constraints that the system had to break, my constraints are no longer enough to satisfy the IB (ie "missing constraints" shows in the IB, which means they're incomplete and won't be used). I actually got around this by setting the constraint it wants to break to low priority, which (and this is an assumption) allows the system to break the constraint gracefully. It's probably not the best solution, but it solved my problem and the resulting constraints worked perfectly.

PL/SQL, how to escape single quote in a string?

Here's a blog post that should help with escaping ticks in strings.

Here's the simplest method from said post:

The most simple and most used way is to use a single quotation mark with two single >quotation marks in both sides.

SELECT 'test single quote''' from dual;

The output of the above statement would be:

test single quote'

Simply stating you require an additional single quote character to print a single quote >character. That is if you put two single quote characters Oracle will print one. The first >one acts like an escape character.

This is the simplest way to print single quotation marks in Oracle. But it will get >complex when you have to print a set of quotation marks instead of just one. In this >situation the following method works fine. But it requires some more typing labour.

Using setTimeout to delay timing of jQuery actions

Try this:

function explode(){
  alert("Boom!");
}
setTimeout(explode, 2000);

Resizable table columns with jQuery

:-) Once I found myself in the same situation, there was no jQuery plugin matching my requeriments, so I spend some time developing my own one: colResizable
 

About colResizable

colResizable is a free jQuery plugin to resize table columns dragging them manually. It is compatible with both mouse and touch devices and has some nice features such as layout persistence after page refresh or postback. It works with both percentage and pixel-based table layouts.

It is tiny in size (colResizable 1.0 is only 2kb) and it is fully compatible with all major browsers (IE7+, Firefox, Chrome and Opera).

enter image description here

Features

colResizable was developed since no other similar plugin with the below listed features was found:

  • Compatible with mouse and touch devices (PC, tablets, and mobile phones)
  • Compatibility with both percentage and pixel-based table layouts
  • Column resizing not altering total table width (optional)
  • No external resources needed (such as images or stylesheets)
  • Optional layout persistence after page refresh or postback
  • Customization of column anchors
  • Small footprint
  • Cross-browser compatibility (IE7+, Chrome, Safari, Firefox)
  • Events

Comparison with other plugins

colResizable is the most polished plugin to resize table columns out there. It has plenty of customization possibilities and it is also compatible with touch devices. But probably the most interesting feature which is making colResizable the greatest choice is that it is compatible with both pixel-based and fluid percentage table layouts. But, what does it mean?

If the width of a table is set to, lets say 90%, and the column widths are modified using colResizable, when the browser is resized columns widths are resized proportionally. While other plugins does behave odd, colResizable does its job just as expected.

colResizable is also compatible with table max-width attribute: if the sum of all columns exceed the table's max-width, they are automatically fixed and updated.

Another great advantage compared with other plugins is that it is compatible with page refresh, postbacks and even partial postbacks if the table is located inside of an updatePanel. It is compatible with all major browsers (IE7+, Firefox, Chrome and Opera), while other plugins fail with old IE versions.

See samples and JSFiddle.

Code sample

$("#sample").colResizable({
        liveDrag:true
});

C# - Winforms - Global Variables

yes you can by using static class. like this:

static class Global
{
    private static string _globalVar = "";

    public static string GlobalVar
    {
        get { return _globalVar; }
        set { _globalVar = value; }
    }
}

and for using any where you can write:

GlobalClass.GlobalVar = "any string value"

Convert String To date in PHP

If you're up for it, use the DateTime class

Maven in Eclipse: step by step installation

I have just include Maven integration plug-in at Eclipse:

Just follow the bellow steps:

  • In eclipse, from upper menu item select- "Help" ->click on "Install New Software.."-> then click on "Add" button.

  • set the "MavenAPI" at name text box and "http://download.eclipse.org/technology/m2e/releases" at location text box.

  • press Ok and select the Maven project and install by clicking next next.

@HostBinding and @HostListener: what do they do and what are they for?

Theory with less Jargons

@Hostlistnening deals basically with the host element say (a button) listening to an action by a user and performing a certain function say alert("Ahoy!") while @Hostbinding is the other way round. Here we listen to the changes that occurred on that button internally (Say when it was clicked what happened to the class) and we use that change to do something else, say emit a particular color.

Example

Think of the scenario that you would like to make a favorite icon on a component, now you know that you would have to know whether the item has been Favorited with its class changed, we need a way to determine this. That is exactly where @Hostbinding comes in.

And where there is the need to know what action actually was performed by the user that is where @Hostlistening comes in