Programs & Examples On #Unit conversion

Unit conversion is the process of applying an arithmetic transformation (usually multiplying/dividing or adding/subtracting) using a conversion factor to convert one textual representation of a quantity, based on one unit, to another.

SQL query to select dates between two dates

SELECT Date, TotalAllowance  
FROM Calculation  
WHERE EmployeeId = 1 
  AND Date BETWEEN to_date('2011/02/25','yyyy-mm-dd') 
               AND to_date ('2011/02/27','yyyy-mm-dd');

How can I change the default credentials used to connect to Visual Studio Online (TFSPreview) when loading Visual Studio up?

You need to remove TFS credentials from Windows Vault to clear and force to ask new TFS credentials in Visual Studio

  1. Go to Control Panel (Start -> Control Panel).

  2. Click User Accounts ( or User Accounts and Family Safety->User Accounts in Windows 7 Machine)

  3. Click Credential Manager (or Manage your credentials)

  4. In Credential Manager page, you can see the two type of credentials

       i. Windows Credentials
       ii. Generic Credentials
    

5.Click on two credentials modify link, click the link Remove from vault to remove stored TFS credentials.

Now, When you login into Visual Studio you will be asked to give credentials to connect TFS.

Note: Don't forgot to uncheck the option Remember my credentials to force to ask credentials for every TFS connections.

Explicit Return Type of Lambda

The return type of a lambda (in C++11) can be deduced, but only when there is exactly one statement, and that statement is a return statement that returns an expression (an initializer list is not an expression, for example). If you have a multi-statement lambda, then the return type is assumed to be void.

Therefore, you should do this:

  remove_if(rawLines.begin(), rawLines.end(), [&expression, &start, &end, &what, &flags](const string& line) -> bool
  {
    start = line.begin();
    end = line.end();
    bool temp = boost::regex_search(start, end, what, expression, flags);
    return temp;
  })

But really, your second expression is a lot more readable.

Node.js/Express.js App Only Works on Port 3000

In bin/www, there is a line:

var port = normalizePort(process.env.PORT || '3000');

Try to modify it.

Which Python memory profiler is recommended?

I found meliae to be much more functional than Heapy or PySizer. If you happen to be running a wsgi webapp, then Dozer is a nice middleware wrapper of Dowser

How do I set the timeout for a JAX-WS webservice client?

The properties in the accepted answer did not work for me, possibly because I'm using the JBoss implementation of JAX-WS?

Using a different set of properties (found in the JBoss JAX-WS User Guide) made it work:

//Set timeout until a connection is established
((BindingProvider)port).getRequestContext().put("javax.xml.ws.client.connectionTimeout", "6000");

//Set timeout until the response is received
((BindingProvider) port).getRequestContext().put("javax.xml.ws.client.receiveTimeout", "1000");

How to Export-CSV of Active Directory Objects?

csvde -f test.csv

This command will perform a CSV dump of every entry in your Active Directory server. You should be able to see the full DN's of users and groups.

You will have to go through that output file and get rid off the unnecessary content.

How do I pass along variables with XMLHTTPRequest

Manually formatting the query string is fine for simple situations. But it can become tedious when there are many parameters.

You could write a simple utility function that handles building the query formatting for you.

function formatParams( params ){
  return "?" + Object
        .keys(params)
        .map(function(key){
          return key+"="+encodeURIComponent(params[key])
        })
        .join("&")
}

And you would use it this way to build a request.

var endpoint = "https://api.example.com/endpoint"
var params = {
  a: 1, 
  b: 2,
  c: 3
}

var url = endpoint + formatParams(params)
//=> "https://api.example.com/endpoint?a=1&b=2&c=3"

There are many utility functions available for manipulating URL's. If you have JQuery in your project you could give http://api.jquery.com/jquery.param/ a try.

It is similar to the above example function, but handles recursively serializing nested objects and arrays.

"Series objects are mutable and cannot be hashed" error

Shortly: gene_name[x] is a mutable object so it cannot be hashed. To use an object as a key in a dictionary, python needs to use its hash value, and that's why you get an error.

Further explanation:

Mutable objects are objects which value can be changed. For example, list is a mutable object, since you can append to it. int is an immutable object, because you can't change it. When you do:

a = 5;
a = 3;

You don't change the value of a, you create a new object and make a point to its value.

Mutable objects cannot be hashed. See this answer.

To solve your problem, you should use immutable objects as keys in your dictionary. For example: tuple, string, int.

Comment out HTML and PHP together

The <!-- --> is only for HTML commenting and the PHP will still run anyway...

Therefore the best thing I would do is also to comment out the PHP...

what is Promotional and Feature graphic in Android Market/Play Store?

Promo graphic

The promo graphic is used for promotions on older versions of the Android OS (earlier than 4.0). This image is not required to submit an update for your Store Listing.

Requirements

  • JPG or 24-bit PNG (no alpha)
  • Dimensions: 180px by 120px

https://support.google.com/googleplay/android-developer/answer/1078870

Node.js: how to consume SOAP XML web service

Adding to Kim .J's solution: you can add preserveWhitespace=true in order to avoid a Whitespace error. Like this:

soap.CreateClient(url,preserveWhitespace=true,function(...){

Executing multiple commands from a Windows cmd script

When you call another .bat file, I think you need "call" in front of the call:

call otherCommand.bat

Can I multiply strings in Java to repeat sequences?

With Guava:

Joiner.on("").join(Collections.nCopies(i, someNum));

Make content horizontally scroll inside a div

if you remove the float: left from the a and add white-space: nowrap to the outer div

#myWorkContent{
    width:530px;
    height:210px;
    border: 13px solid #bed5cd;
    overflow-x: scroll;
    overflow-y: hidden;
    white-space: nowrap;
}
#myWorkContent a {
    display: inline;
}

this should work for any size or amount of images..

or even:

#myWorkContent a {
    display: inline-block;
    vertical-align: middle;
}

which would also vertically align images of different heights if required

test code

How do I write to a Python subprocess' stdin?

You can provide a file-like object to the stdin argument of subprocess.call().

The documentation for the Popen object applies here.

To capture the output, you should instead use subprocess.check_output(), which takes similar arguments. From the documentation:

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'

How to source virtualenv activate in a Bash script

What does sourcing the bash script for?

  1. If you intend to switch between multiple virtualenvs or enter one virtualenv quickly, have you tried virtualenvwrapper? It provides a lot of utils like workon venv, mkvirtualenv venv and so on.

  2. If you just run a python script in certain virtualenv, use /path/to/venv/bin/python script.py to run it.

Incrementing a date in JavaScript

I feel that nothing is safer than .getTime() and .setTime(), so this should be the best, and performant as well.

const d = new Date()
console.log(d.setTime(d.getTime() + 1000 * 60 * 60 * 24)) // MILLISECONDS

.setDate() for invalid Date (like 31 + 1) is too dangerous, and it depends on the browser implementation.

how to determine size of tablespace oracle 11g

The following query can be used to detemine tablespace and other params:

select df.tablespace_name "Tablespace",
       totalusedspace "Used MB",
       (df.totalspace - tu.totalusedspace) "Free MB",
       df.totalspace "Total MB",
       round(100 * ( (df.totalspace - tu.totalusedspace)/ df.totalspace)) "Pct. Free"
  from (select tablespace_name,
               round(sum(bytes) / 1048576) TotalSpace
          from dba_data_files 
         group by tablespace_name) df,
       (select round(sum(bytes)/(1024*1024)) totalusedspace,
               tablespace_name
          from dba_segments 
         group by tablespace_name) tu
 where df.tablespace_name = tu.tablespace_name 
   and df.totalspace <> 0;

Source: https://community.oracle.com/message/1832920

For your case if you want to know the partition name and it's size just run this query:

select owner,
       segment_name,
       partition_name,
       segment_type,
       bytes / 1024/1024 "MB" 
  from dba_segments 
 where owner = <owner_name>;

How to determine whether a substring is in a different string

Can also use this method

if substring in string:
    print(string + '\n Yes located at:'.format(string.find(substring)))

How to show row number in Access query like ROW_NUMBER in SQL

You can try this query:

Select A.*, (select count(*) from Table1 where A.ID>=ID) as RowNo
from Table1 as A
order by A.ID

Convert a string to a double - is this possible?

Use doubleval(). But be very careful about using decimals in financial transactions, and validate that user input very carefully.

How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

You have to add empty option to solve it,

I also can give you one more solution but its up to you that is fine for you or not Because User select default option after selecting other options than jsFunction will be called twice.

<select onChange="jsFunction()" id="selectOpt">
    <option value="1" onclick="jsFunction()">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

function jsFunction(){
  var myselect = document.getElementById("selectOpt");
  alert(myselect.options[myselect.selectedIndex].value);
}

Can dplyr package be used for conditional mutating?

The derivedFactor function from mosaic package seems to be designed to handle this. Using this example, it would look like:

library(dplyr)
library(mosaic)
df <- mutate(df, g = derivedFactor(
     "2" = (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)),
     "3" = (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
     .method = "first",
     .default = NA
     ))

(If you want the result to be numeric instead of a factor, you can wrap derivedFactor in an as.numeric call.)

derivedFactor can be used for an arbitrary number of conditionals, too.

Finding square root without using sqrt function?

This a very simple recursive approach.

double mySqrt(double v, double test) {
    if (abs(test * test - v) < 0.0001) {
        return test;
    }

    double highOrLow = v / test;
    return mySqrt(v, (test + highOrLow) / 2.0);
}
double mySqrt(double v) {
    return mySqrt(v, v/2.0);
}

Regex select all text between tags

You can use Pattern pattern = Pattern.compile( "[^<'tagname'/>]" );

Bootstrap dropdown not working

I had the same problem when I included the bootstrap.min.js twice. Removed one of them and it began working.

Properly escape a double quote in CSV

Use 2 quotes:

"Samsung U600 24"""

OnClick in Excel VBA

I had a similar issue, and I fixed by running the macro "onTime", and by using some global variables to only run once the user has stopped clicking.

Public macroIsOnQueue As Boolean
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    macroIsOnQueue = False
    Application.OnTime (Now() + TimeValue("00:00:02")), "addBordersOnRow"
    macroIsOnQueue = True
End sub
Sub addBordersOnRow()
    If macroIsOnQueue Then        
       macroIsOnQueue = False
       ' add code here
    End if
End sub

This way, whenever the user changes selection within 2 seconds, the macroIsOnQueue variable is set to false, but the last time selection is changed, macroIsOnQueue is set to true, and the macro will run.

Hope this helps, Have fun with VBA !!

How do you use youtube-dl to download live streams (that are live)?

I'll be using this Live Event from NASA TV as an example:

https://www.youtube.com/watch?v=21X5lGlDOfg

First, list the formats for the video:

$  ~ youtube-dl --list-formats https://www.youtube.com/watch\?v\=21X5lGlDOfg
[youtube] 21X5lGlDOfg: Downloading webpage
[youtube] 21X5lGlDOfg: Downloading m3u8 information
[youtube] 21X5lGlDOfg: Downloading MPD manifest
[info] Available formats for 21X5lGlDOfg:
format code  extension  resolution note
91           mp4        256x144    HLS  197k , avc1.42c00b, 30.0fps, mp4a.40.5@ 48k
92           mp4        426x240    HLS  338k , avc1.4d4015, 30.0fps, mp4a.40.5@ 48k
93           mp4        640x360    HLS  829k , avc1.4d401e, 30.0fps, mp4a.40.2@128k
94           mp4        854x480    HLS 1380k , avc1.4d401f, 30.0fps, mp4a.40.2@128k
300          mp4        1280x720   3806k , avc1.4d4020, 60.0fps, mp4a.40.2 (best)

Pick the format you wish to download, and fetch the HLS m3u8 URL of the video from the manifest. I'll be using 94 mp4 854x480 HLS 1380k , avc1.4d401f, 30.0fps, mp4a.40.2@128k for this example:

?  ~ youtube-dl -f 94 -g https://www.youtube.com/watch\?v\=21X5lGlDOfg
https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1592099895/ei/1y_lXuLOEsnXyQWYs4GABw/ip/81.190.155.248/id/21X5lGlDOfg.3/itag/94/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/goi/160/sgoap/gir%3Dyes%3Bitag%3D140/sgovp/gir%3Dyes%3Bitag%3D135/hls_chunk_host/r5---sn-h0auphxqp5-f5fs.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/8270/mh/N8/mm/44/mn/sn-h0auphxqp5-f5fs/ms/lva/mv/m/mvi/4/pl/16/dover/11/keepalive/yes/beids/9466586/mt/1592078245/disable_polymer/true/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,goi,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAM2dGSece2shUTgS73Qa3KseLqnf85ca_9u7Laz7IDfSAiEAj8KHw_9xXVS_PV3ODLlwDD-xfN6rSOcLVNBpxKgkRLI%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRQIhAJCO6kSwn7PivqMW7sZaiYFvrultXl6Qmu9wppjCvImzAiA7vkub9JaanJPGjmB4qhLVpHJOb9fZyhMEeh1EUCd-3Q%3D%3D/playlist/index.m3u8

Note that link could be different and it contains expiration timestamp, in this case 1592099895 (about 6 hours).

Now that you have the HLS playlist, you can open this URL in VLC and save it using "Record", or write a small ffmpeg command:

ffmpeg -i \
https://manifest.googlevideo.com/api/manifest/hls_playlist/expire/1592099895/ei/1y_lXuLOEsnXyQWYs4GABw/ip/81.190.155.248/id/21X5lGlDOfg.3/itag/94/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/goi/160/sgoap/gir%3Dyes%3Bitag%3D140/sgovp/gir%3Dyes%3Bitag%3D135/hls_chunk_host/r5---sn-h0auphxqp5-f5fs.googlevideo.com/playlist_duration/30/manifest_duration/30/vprv/1/playlist_type/DVR/initcwndbps/8270/mh/N8/mm/44/mn/sn-h0auphxqp5-f5fs/ms/lva/mv/m/mvi/4/pl/16/dover/11/keepalive/yes/beids/9466586/mt/1592078245/disable_polymer/true/sparams/expire,ei,ip,id,itag,source,requiressl,ratebypass,live,goi,sgoap,sgovp,playlist_duration,manifest_duration,vprv,playlist_type/sig/AOq0QJ8wRgIhAM2dGSece2shUTgS73Qa3KseLqnf85ca_9u7Laz7IDfSAiEAj8KHw_9xXVS_PV3ODLlwDD-xfN6rSOcLVNBpxKgkRLI%3D/lsparams/hls_chunk_host,initcwndbps,mh,mm,mn,ms,mv,mvi,pl/lsig/AG3C_xAwRQIhAJCO6kSwn7PivqMW7sZaiYFvrultXl6Qmu9wppjCvImzAiA7vkub9JaanJPGjmB4qhLVpHJOb9fZyhMEeh1EUCd-3Q%3D%3D/playlist/index.m3u8 \
-c copy output.ts

How can I increment a char?

Check this: USING FOR LOOP

for a in range(5):
    x='A'
    val=chr(ord(x) + a)
    print(val)

LOOP OUTPUT: A B C D E

Angular2 equivalent of $document.ready()

Copying the answer from Chris:

Got it working:

import {AfterViewInit} from 'angular2/core';    

export class HomeCmp implements AfterViewInit {    

    ngAfterViewInit() {
       //Copy in all the js code from the script.js. Typescript will complain but it works just fine
    }

Execute a SQL Stored Procedure and process the results

My Stored Procedure Requires 2 Parameters and I needed my function to return a datatable here is 100% working code

Please make sure that your procedure return some rows

Public Shared Function Get_BillDetails(AccountNumber As String) As DataTable
    Try
        Connection.Connect()
        debug.print("Look up account number " & AccountNumber)
        Dim DP As New SqlDataAdapter("EXEC SP_GET_ACCOUNT_PAYABLES_GROUP  '" & AccountNumber & "' , '" & 08/28/2013 &"'", connection.Con)
        Dim DST As New DataSet
        DP.Fill(DST)
        Return DST.Tables(0)      
    Catch ex As Exception
        Return Nothing
    End Try
End Function

Array.push() if does not exist?

Not sure about speed, but stringification + indexOf is a simple approach. Start with turning your array into a string:

let strMyArray = JSON.stringify(myArray);

Then for a series of attribute-value pairs you can use:

if (strMyArray.indexOf('"name":"tom"') === -1 && strMyArray.indexOf('"text":"tasty"') === -1) {
   myArray.push({ name: "tom", text: "tasty" });
}

Finding a whole object is simpler:

if (strMyArray.indexOf(JSON.stringify(objAddMe) === -1) { 
   myArray.push(objAddMe);
}

Install .ipa to iPad with or without iTunes

If you built the IPA using PhoneGap Build online you can download and install the IPA directly on your Ipad/Iphone by opening build.phonegap.com in Safari on the device, logging in and then clicking the iOS tab (the download ipa button). You will then be asked to install the app you built.

Direct link to this after logging in is: https://build.phonegap.com/apps/YOUR-BUILD-NUMBER/download/ios

Angular 2: How to access an HTTP response body?

.subscribe(data => {   
            console.log(data);
            let body:string = JSON.parse(data['_body']);`

Using local makefile for CLion instead of CMake

I am not very familiar with CMake and could not use Mondkin's solution directly.

Here is what I came up with in my CMakeLists.txt using the latest version of CLion (1.2.4) and MinGW on Windows (I guess you will just need to replace all: g++ mytest.cpp -o bin/mytest by make if you are not using the same setup):

cmake_minimum_required(VERSION 3.3)
project(mytest)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

add_custom_target(mytest ALL COMMAND mingw32-make WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})

And the custom Makefile is like this (it is located at the root of my project and generates the executable in a bin directory):

all:
    g++ mytest.cpp -o bin/mytest

I am able to build the executable and errors in the log window are clickable.

Hints in the IDE are quite limited through, which is a big limitation compared to pure CMake projects...

How to download a file over HTTP?

If speed matters to you, I made a small performance test for the modules urllib and wget, and regarding wget I tried once with status bar and once without. I took three different 500MB files to test with (different files- to eliminate the chance that there is some caching going on under the hood). Tested on debian machine, with python2.

First, these are the results (they are similar in different runs):

$ python wget_test.py 
urlretrive_test : starting
urlretrive_test : 6.56
==============
wget_no_bar_test : starting
wget_no_bar_test : 7.20
==============
wget_with_bar_test : starting
100% [......................................................................] 541335552 / 541335552
wget_with_bar_test : 50.49
==============

The way I performed the test is using "profile" decorator. This is the full code:

import wget
import urllib
import time
from functools import wraps

def profile(func):
    @wraps(func)
    def inner(*args):
        print func.__name__, ": starting"
        start = time.time()
        ret = func(*args)
        end = time.time()
        print func.__name__, ": {:.2f}".format(end - start)
        return ret
    return inner

url1 = 'http://host.com/500a.iso'
url2 = 'http://host.com/500b.iso'
url3 = 'http://host.com/500c.iso'

def do_nothing(*args):
    pass

@profile
def urlretrive_test(url):
    return urllib.urlretrieve(url)

@profile
def wget_no_bar_test(url):
    return wget.download(url, out='/tmp/', bar=do_nothing)

@profile
def wget_with_bar_test(url):
    return wget.download(url, out='/tmp/')

urlretrive_test(url1)
print '=============='
time.sleep(1)

wget_no_bar_test(url2)
print '=============='
time.sleep(1)

wget_with_bar_test(url3)
print '=============='
time.sleep(1)

urllib seems to be the fastest

How to export dataGridView data Instantly to Excel on button click?

If your DataGridView's RightToLeft set to Yes then your data copy reversely. So you should use the below code to copy the data correctly.

private void copyAlltoClipboard()
{
    dgvItems.RightToLeft = RightToLeft.No;
    dgvItems.SelectAll();
    DataObject dataObj = dgvItems.GetClipboardContent();
    if (dataObj != null)
        Clipboard.SetDataObject(dataObj);
    dgvItems.RightToLeft = RightToLeft.Yes;
}

How to put a text beside the image?

You need to go throgh these scenario:

How about using display:inline-block?

1) Take one <div/> give it style=display:inline-block make it vertical-align:top and put image inside that div.

2) Take another div and give it also the same style display:inline-block; and put all the labels/divs inside this div.

Here is the prototype of your requirement

JS Fiddle Demo

Stop setInterval call in JavaScript

I guess the following code will help:

var refreshIntervalId = setInterval(fname, 10000);

clearInterval(refreshIntervalId);

You did the code 100% correct... So... What's the problem? Or it's a tutorial...

When use getOne and findOne methods Spring Data JPA

I really find very difficult from the above answers. From debugging perspective i almost spent 8 hours to know the silly mistake.

I have testing spring+hibernate+dozer+Mysql project. To be clear.

I have User entity, Book Entity. You do the calculations of mapping.

Were the Multiple books tied to One user. But in UserServiceImpl i was trying to find it by getOne(userId);

public UserDTO getById(int userId) throws Exception {

    final User user = userDao.getOne(userId);

    if (user == null) {
        throw new ServiceException("User not found", HttpStatus.NOT_FOUND);
    }
    userDto = mapEntityToDto.transformBO(user, UserDTO.class);

    return userDto;
}

The Rest result is

{
"collection": {
    "version": "1.0",
    "data": {
        "id": 1,
        "name": "TEST_ME",
        "bookList": null
    },
    "error": null,
    "statusCode": 200
},
"booleanStatus": null

}

The above code did not fetch the books which is read by the user let say.

The bookList was always null because of getOne(ID). After changing to findOne(ID). The result is

{
"collection": {
    "version": "1.0",
    "data": {
        "id": 0,
        "name": "Annama",
        "bookList": [
            {
                "id": 2,
                "book_no": "The karma of searching",
            }
        ]
    },
    "error": null,
    "statusCode": 200
},
"booleanStatus": null

}

How can I make the Android emulator show the soft keyboard?

I found out how to do this on the Android emulator itself (Menu, "Settings" App - not the settings of the emulator outside). All you need to do is:

open settings app -> Language & Input -> Go to the "Keyboard & Input Methods -> click Default

This will bring up a Dialog in which case you can then disable the Hardware Keyboard by switching the hardware keyboard from on to off. This will disable the Hardware keyboard and enable the softkeyboard.

Invalid syntax when using "print"?

You need parentheses:

print(2**100)

Run a batch file with Windows task scheduler

Make sure "Start In " has NO QUOTES.

Getting list of tables, and fields in each, in a database

Just throwing this out there - easy to now copy/paste into a word or google doc:

PRINT '<html><body>'
SET NOCOUNT ON
DECLARE @tableName VARCHAR(30)
DECLARE tableCursor CURSOR LOCAL FAST_FORWARD FOR
    SELECT T.name AS TableName 
      FROM sys.objects AS T
     WHERE T.type_desc = 'USER_TABLE'
     ORDER BY T.name
OPEN tableCursor
FETCH NEXT FROM tableCursor INTO @tableName
WHILE @@FETCH_STATUS = 0 BEGIN
    PRINT '<h2>' + @tableName + '</h2>'
    PRINT '<pre>'
    SELECT LEFT(C.name, 30) AS ColumnName,
           LEFT(ISC.DATA_TYPE, 10) AS DataType,
           C.max_length AS Size,
           CAST(P.precision AS VARCHAR(4)) + '/' + CAST(P.scale AS VARCHAR(4)) AS PrecScale,
           CASE WHEN C.is_nullable = 1 THEN 'Null' ELSE 'No Null' END AS [Nullable],
           LEFT(ISNULL(ISC.COLUMN_DEFAULT, ' '), 5)  AS [Default],
           CASE WHEN C.is_identity = 1 THEN 'Identity' ELSE '' END AS [Identity]
    FROM   sys.objects AS T
           JOIN sys.columns AS C ON T.object_id = C.object_id
           JOIN sys.types AS P ON C.system_type_id = P.system_type_id
           JOIN INFORMATION_SCHEMA.COLUMNS AS ISC ON T.name = ISC.TABLE_NAME AND C.name = ISC.COLUMN_NAME
    WHERE  T.type_desc = 'USER_TABLE'
      AND  T.name = @tableName
    ORDER BY T.name, ISC.ORDINAL_POSITION
    PRINT '</pre>'
    FETCH NEXT FROM tableCursor INTO @tableName

END

CLOSE tableCursor
DEALLOCATE tableCursor
SET NOCOUNT OFF
PRINT '</body></html>'

How to compare two strings are equal in value, what is the best method?

string1.equals(string2) is the way.

It returns true if string1 is equals to string2 in value. Else, it will return false.

equals reference

Changing the child element's CSS when the parent is hovered

Stephen's answer is correct but here's my adaptation of his answer:

HTML

<div class="parent">
    <p> parent 1 </p>
    <div class="child">
        Text Block 1
    </div>
</div>

<div class="parent">
    <p> parent 2 </p>
    <div class="child">
        Text Block 2
    </div>
</div>

CSS

.parent { width: 100px; min-height: 100px; color: red; }
.child { width: 50px; min-height: 20px; color: blue; display: none; }
.parent:hover .child, .parent.hover .child { display: block; }

jQuery

//this is only necessary for IE and should be in a conditional comment

jQuery('.parent').hover(function () {
    jQuery(this).addClass('hover');
}, function () {
    jQuery(this).removeClass('hover');
});

You can see this example working over at jsFiddle.

How to get a random number in Ruby

Try array#shuffle method for randomization

array = (1..10).to_a
array.shuffle.first

How to do a redirect to another route with react-router?

How to do a redirect to another route with react-router?

For example, when a user clicks a link <Link to="/" />Click to route</Link> react-router will look for / and you can use Redirect to and send the user somewhere else like the login route.

From the docs for ReactRouterTraining:

Rendering a <Redirect> will navigate to a new location. The new location will override the current location in the history stack, like server-side redirects (HTTP 3xx) do.

import { Route, Redirect } from 'react-router'

<Route exact path="/" render={() => (
  loggedIn ? (
    <Redirect to="/dashboard"/>
  ) : (
    <PublicHomePage/>
  )
)}/>

to: string, The URL to redirect to.

<Redirect to="/somewhere/else"/>

to: object, A location to redirect to.

<Redirect to={{
  pathname: '/login',
  search: '?utm=your+face',
  state: { referrer: currentLocation }
}}/>

AngularJS - Access to child scope

While jm-'s answer is the best way to handle this case, for future reference it is possible to access child scopes using a scope's $$childHead, $$childTail, $$nextSibling and $$prevSibling members. These aren't documented so they might change without notice, but they're there if you really need to traverse scopes.

// get $$childHead first and then iterate that scope's $$nextSiblings
for(var cs = scope.$$childHead; cs; cs = cs.$$nextSibling) {
    // cs is child scope
}

Fiddle

CSS to hide INPUT BUTTON value text

Instead, just do a hook_form_alter and make the button an image button and you are done!

Select a Dictionary<T1, T2> with LINQ

A more explicit option is to project collection to an IEnumerable of KeyValuePair and then convert it to a Dictionary.

Dictionary<int, string> dictionary = objects
    .Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
    .ToDictionary(x=>x.Key, x=>x.Value);

Trying to get PyCharm to work, keep getting "No Python interpreter selected"

Go to File->Settings->Project Settings->Project Interpreter->Python Interpreters

There will be a "+" sign on the right side. Navigate to your python binary, PyCharm will figure out the rest.

How to make ConstraintLayout work with percentage values?

you can use app:layout_constraintVertical_weight it same as layout_weight in linearlayout

<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
    android:id="@+id/button4"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="Button"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toLeftOf="@+id/button5"
    app:layout_constraintVertical_weight="1"/>

<Button
    android:id="@+id/button5"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="Button"
    app:layout_constraintLeft_toRightOf="@+id/button4"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintVertical_weight="1"/>
</android.support.constraint.ConstraintLayout>

NOTE: app:layout_constraintVertical_weight(app:layout_constraintHorizontal_weight) will work with android:layout_width="0dp" (android:layout_height="0dp"

Returning a regex match in VBA (excel)

You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).

For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.

Function ExtractSDI(ByVal text As String) As String

Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)

If allMatches.count <> 0 Then
    result = allMatches.Item(0).submatches.Item(0)
End If

ExtractSDI = result

End Function

If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:

Ex) =RegexExtract(A1, "(sdi \d+)", ", ")

Here is:

Function RegexExtract(ByVal text As String, _
                      ByVal extract_what As String, _
                      Optional seperator As String = "") As String

Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)

For i = 0 To allMatches.count - 1
    For j = 0 To allMatches.Item(i).submatches.count - 1
        result = result & seperator & allMatches.Item(i).submatches.Item(j)
    Next
Next

If Len(result) <> 0 Then
    result = Right(result, Len(result) - Len(seperator))
End If

RegexExtract = result

End Function

*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.

Postgresql Select rows where column = array

In my case, I needed to work with a column that has the data, so using IN() didn't work. Thanks to @Quassnoi for his examples. Here is my solution:

SELECT column(s) FROM table WHERE expr|column = ANY(STRING_TO_ARRAY(column,',')::INT[])

I spent almost 6 hours before I stumble on the post.

CSS to prevent child element from inheriting parent styles

Unfortunately, you're out of luck here.

There is inherit to copy a certain value from a parent to its children, but there is no property the other way round (which would involve another selector to decide which style to revert).

You will have to revert style changes manually:

div { color: green; }

form div { color: red; }

form div div.content { color: green; }

If you have access to the markup, you can add several classes to style precisely what you need:

form div.sub { color: red; }

form div div.content { /* remains green */ }

Edit: The CSS Working Group is up to something:

div.content {
  all: revert;
}

No idea, when or if ever this will be implemented by browsers.

Edit 2: As of March 2015 all modern browsers but Safari and IE/Edge have implemented it: https://twitter.com/LeaVerou/status/577390241763467264 (thanks, @Lea Verou!)

Edit 3: default was renamed to revert.

How do I parse a URL into hostname and path in javascript?

Use https://www.npmjs.com/package/uri-parse-lib for this

var t = parserURI("http://user:[email protected]:8080/directory/file.ext?query=1&next=4&sed=5#anchor");

Remove pandas rows with duplicate indices

If anyone like me likes chainable data manipulation using the pandas dot notation (like piping), then the following may be useful:

df3 = df3.query('~index.duplicated()')

This enables chaining statements like this:

df3.assign(C=2).query('~index.duplicated()').mean()

how to add script src inside a View when using Layout

Depending how you want to implement it (if there was a specific location you wanted the scripts) you could implement a @section within your _Layout which would enable you to add additional scripts from the view itself, while still retaining structure. e.g.

_Layout

<!DOCTYPE html>
<html>
  <head>
    <title>...</title>
    <script src="@Url.Content("~/Scripts/jquery.min.js")"></script>
    @RenderSection("Scripts",false/*required*/)
  </head>
  <body>
    @RenderBody()
  </body>
</html>

View

@model MyNamespace.ViewModels.WhateverViewModel
@section Scripts
{
  <script src="@Url.Content("~/Scripts/jqueryFoo.js")"></script>
}

Otherwise, what you have is fine. If you don't mind it being "inline" with the view that was output, you can place the <script> declaration within the view.

How to replicate background-attachment fixed on iOS

It has been asked in the past, apparently it costs a lot to mobile browsers, so it's been disabled.

Check this comment by @PaulIrish:

Fixed-backgrounds have huge repaint cost and decimate scrolling performance, which is, I believe, why it was disabled.

you can see workarounds to this in this posts:

Fixed background image with ios7

Fixed body background scrolls with the page on iOS7

DataTables: Cannot read property 'length' of undefined

When you have JSON data then the following error appears enter image description here

A better solution is to assign a var data for the local json array object, details see: https://datatables.net/manual/tech-notes/4

This is helps you to display table contents.

 $(document).ready(function(){   

        $('#customer_table').DataTable( {
         "aaData": data,

           "aoColumns": [{
                            "mDataProp": "name_en"
                        }, {
                            "mDataProp": "phone"
                        }, {
                            "mDataProp": "email"
                        }, {
                            "mDataProp": "facebook"
                        }]
            });
        });

How to force 'cp' to overwrite directory instead of creating another one inside?

You can do this using -T option in cp.
See Man page for cp.

-T, --no-target-directory
    treat DEST as a normal file

So as per your example, following is the file structure.

$ tree test
test
|-- bar
|   |-- a
|   `-- b
`-- foo
    |-- a
    `-- b
2 directories, 4 files

You can see the clear difference when you use -v for Verbose.
When you use just -R option.

$ cp -Rv foo/ bar/
`foo/' -> `bar/foo'
`foo/b' -> `bar/foo/b'
`foo/a' -> `bar/foo/a'
 $ tree
 |-- bar
 |   |-- a
 |   |-- b
 |   `-- foo
 |       |-- a
 |       `-- b
 `-- foo
     |-- a
     `-- b
3 directories, 6 files

When you use the option -T it overwrites the contents, treating the destination like a normal file and not directory.

$ cp -TRv foo/ bar/
`foo/b' -> `bar/b'
`foo/a' -> `bar/a'

$ tree
|-- bar
|   |-- a
|   `-- b
`-- foo
    |-- a
    `-- b
2 directories, 4 files

This should solve your problem.

Excel VBA - How to Redim a 2D array?

You could do this array(0)= array(0,1,2,3).

Sub add_new(data_array() As Variant, new_data() As Variant)
    Dim ar2() As Variant, fl As Integer
    If Not (isEmpty(data_array)) = True Then
        fl = 0
    Else
        fl = UBound(data_array) + 1
    End If
    ReDim Preserve data_array(fl)
    data_array(fl) = new_data
End Sub

Sub demo()
    Dim dt() As Variant, nw(0, 1) As Variant
    nw(0, 0) = "Hi"
    nw(0, 1) = "Bye"
    Call add_new(dt, nw)
    nw(0, 0) = "Good"
    nw(0, 1) = "Bad"
    Call add_new(dt, nw)
End Sub

What are Transient and Volatile Modifiers?

Volatile means other threads can edit that particular variable. So the compiler allows access to them.

http://www.javamex.com/tutorials/synchronization_volatile.shtml

Transient means that when you serialize an object, it will return its default value on de-serialization

http://www.geekinterview.com/question_details/2

Run a php app using tomcat?

A tad late, but here goes.

How about http://wiki.apache.org/tomcat/UsingPhp if you just want to run the real php on tomcat.

Concerning running tomcat on port 80 there's always jsvc, just google jsvc + tomcat.

How to check if an item is selected from an HTML drop down list?

I believe this is the most simple in all aspects unless you call the validate function be other means. With no/null/empty value to your first option is easier to validate. You could also eliminate the first option and start with the most popular card type.

<form name="myForm">
<select id="cardtype" name="cards">
<option value="">--- Please select ---</option>
<option value="mastercard" selected="selected">Mastercard</option>
<option value="maestro">Maestro</option>
<option value="solo">Solo (UK only)</option>
<option value="visaelectron">Visa Electron</option>
<option value="visadebit">Visa Debit</option>
</select><br />

<input type="submit" name="submit" class="button" value="SUBMIT" onmouseover="validate()"></form>

<script>
function validate() {
 if (document.myform.cards.value == "") {
    alert("Please select a card type");
    document.myForm.cards.focus();
}
</script>

Undoing accidental git stash pop

Try using How to recover a dropped stash in Git? to find the stash you popped. I think there are always two commits for a stash, since it preserves the index and the working copy (so often the index commit will be empty). Then git show them to see the diff and use patch -R to unapply them.

How to add ASP.NET 4.0 as Application Pool on IIS 7, Windows 7

I just encountered this and whilst we already had .NET 4.0 installed on the server it turns out we only had the "Client Profile" version and not the "Full" version. Installing the latter fixed the problem.

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

You could check if your method is private. Spent a lot of time fixing this dumb mistake ...

How to read all files in a folder from Java?

There are many good answers above, here's a different approach: In a maven project, everything you put in the resources folder is copied by default in the target/classes folder. To see what is available at runtime

 ClassLoader contextClassLoader = 
 Thread.currentThread().getContextClassLoader();
    URL resource = contextClassLoader.getResource("");
    File file = new File(resource.toURI());
    File[] files = file.listFiles();
    for (File f : files) {
        System.out.println(f.getName());
    }

Now to get the files from a specific folder, let's say you have a folder called 'res' in your resources folder, just replace:

URL resource = contextClassLoader.getResource("res");

If you want to have access in your com.companyName package then:

contextClassLoader.getResource("com.companyName");

How can I declare a two dimensional string array?

You probably want this:

string[,] Tablero = new string[3,3];

This will create you a matrix-like array where all rows have the same length.

The array in your sample is a so-called jagged array, i.e. an array of arrays where the elements can be of different size. A jagged array would have to be created in a different way:

string[][] Tablero = new string[3][];
for (int i = 0; i < Tablero.GetLength(0); i++)
{
    Tablero[i] = new string[3];
}

You can also use initializers to fill the array elements with data:

string[,] Tablero = new string[,]
{
    {"1.1","1.2", "1.3"},
    {"2.1","2.2", "2.3"},
    {"3.1", "3.2", "3.3"}
};

And in case of a jagged array:

string[][] Tablero = new string[][]
{
    new string[] {"1.1","1.2", "1.3"},
    new string[] {"2.1","2.2", "2.3"},
    new string[] {"3.1", "3.2", "3.3"}
};

Debugging PHP Mail() and/or PHPMailer

It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.

I've always used phpMailer's SMTP feature:

$mail->IsSMTP();
$mail->Host = "localhost";

And if you need debug info:

$mail->SMTPDebug  = 2; // enables SMTP debug information (for testing)
                       // 1 = errors and messages
                       // 2 = messages only

Build error, This project references NuGet

In my case, I deleted the Previous Project & created a new project with different name, when i was building the Project it shows me the same error.

I just edited the Project Name in csproj file of the Project & it Worked...!

EntityType has no key defined error

All is right but in my case i have two class like this

namespace WebAPI.Model
{
   public class ProductsModel
{ 
        [Table("products")]
        public class Products
        {
            [Key]
            public int slno { get; set; }

            public int productId { get; set; }
            public string ProductName { get; set; }

            public int Price { get; set; }
}
        }
    }

After deleting the upper class it works fine for me.

postgresql - add boolean column to table set default

ALTER TABLE users
  ADD COLUMN "priv_user" BOOLEAN DEFAULT FALSE;

you can also directly specify NOT NULL

ALTER TABLE users
  ADD COLUMN "priv_user" BOOLEAN NOT NULL DEFAULT FALSE;

UPDATE: following is only true for versions before postgresql 11.

As Craig mentioned on filled tables it is more efficient to split it into steps:

ALTER TABLE users ADD COLUMN priv_user BOOLEAN;
UPDATE users SET priv_user = 'f';
ALTER TABLE users ALTER COLUMN priv_user SET NOT NULL;
ALTER TABLE users ALTER COLUMN priv_user SET DEFAULT FALSE;

Set Label Text with JQuery

The checkbox is in a td, so need to get the parent first:

$("input:checkbox").on("change", function() {
    $(this).parent().next().find("label").text("TESTTTT");
});

Alternatively, find a label which has a for with the same id (perhaps more performant than reverse traversal) :

$("input:checkbox").on("change", function() {
    $("label[for='" + $(this).attr('id') + "']").text("TESTTTT");
});

Or, to be more succinct just this.id:

$("input:checkbox").on("change", function() {
    $("label[for='" + this.id + "']").text("TESTTTT");
});

Extracting the last n characters from a string in R

Another reasonably straightforward way is to use regular expressions and sub:

sub('.*(?=.$)', '', string, perl=T)

So, "get rid of everything followed by one character". To grab more characters off the end, add however many dots in the lookahead assertion:

sub('.*(?=.{2}$)', '', string, perl=T)

where .{2} means .., or "any two characters", so meaning "get rid of everything followed by two characters".

sub('.*(?=.{3}$)', '', string, perl=T)

for three characters, etc. You can set the number of characters to grab with a variable, but you'll have to paste the variable value into the regular expression string:

n = 3
sub(paste('.+(?=.{', n, '})', sep=''), '', string, perl=T)

get all keys set in memcached

Found a way, thanks to the link here (with the original google group discussion here)

First, Telnet to your server:

telnet 127.0.0.1 11211

Next, list the items to get the slab ids:

stats items
STAT items:3:number 1
STAT items:3:age 498
STAT items:22:number 1
STAT items:22:age 498
END

The first number after ‘items’ is the slab id. Request a cache dump for each slab id, with a limit for the max number of keys to dump:

stats cachedump 3 100
ITEM views.decorators.cache.cache_header..cc7d9 [6 b; 1256056128 s]
END

stats cachedump 22 100
ITEM views.decorators.cache.cache_page..8427e [7736 b; 1256056128 s]
END

"’" showing on page instead of " ' "

If your content type is already UTF8 , then it is likely the data is already arriving in the wrong encoding. If you are getting the data from a database, make sure the database connection uses UTF-8.

If this is data from a file, make sure the file is encoded correctly as UTF-8. You can usually set this in the "Save as..." Dialog of the editor of your choice.

If the data is already broken when you view it in the source file, chances are that it used to be a UTF-8 file but was saved in the wrong encoding somewhere along the way.

How to convert Windows end of line in Unix end of line (CR/LF to LF)

Go back to Windows, tell Eclipse to change the encoding to UTF-8, then back to Unix and run d2u on the files.

.net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible

For me, I had ~6 different Nuget packages to update and when I selected Microsoft.AspNetCore.All first, I got the referenced error.

I started at the bottom and updated others first (EF Core, EF Design Tools, etc), then when the only one that was left was Microsoft.AspNetCore.All it worked fine.

What's the point of 'meta viewport user-scalable=no' in the Google Maps API

From the v3 documentation (Developer's Guide > Concepts > Developing for Mobile Devices):

Android and iOS devices respect the following <meta> tag:

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

This setting specifies that the map should be displayed full-screen and should not be resizable by the user. Note that the iPhone's Safari browser requires this <meta> tag be included within the page's <head> element.

Disabling Minimize & Maximize On WinForm?

you can simply disable maximize inside form constructor.

 public Form1(){
     InitializeComponent();
     MaximizeBox = false;
 }

to minimize when closing.

private void Form1_FormClosing(Object sender, FormClosingEventArgs e) {
    e.Cancel = true;
    WindowState = FormWindowState.Minimized;
}

Get the time difference between two datetimes

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') //[days, years, months, seconds, ...]
//Result 1 

Worked for me

See more in http://momentjs.com/docs/#/displaying/difference/

In Node.js, how do I turn a string to a json?

use the JSON function >

JSON.parse(theString)

Will using 'var' affect performance?

There is no runtime performance cost to using var. Though, I would suspect there to be a compiling performance cost as the compiler needs to infer the type, though this will most likely be negligable.

Checking for a null object in C++

C++ references naturally can't be null, you don't need the check. The function can only be called by passing a reference to an existing object.

Converting NumPy array into Python List structure?

Use tolist():

import numpy as np
>>> np.array([[1,2,3],[4,5,6]]).tolist()
[[1, 2, 3], [4, 5, 6]]

Note that this converts the values from whatever numpy type they may have (e.g. np.int32 or np.float32) to the "nearest compatible Python type" (in a list). If you want to preserve the numpy data types, you could call list() on your array instead, and you'll end up with a list of numpy scalars. (Thanks to Mr_and_Mrs_D for pointing that out in a comment.)

How do I bind Twitter Bootstrap tooltips to dynamically created elements?

For me, only catching the mouseenter event was a bit buggy, and the tooltip was not showing/hiding properly. I had to write this, and it is now working perfectly:

$(document).on('mouseenter','[rel=tooltip]', function(){
    $(this).tooltip('show');
});

$(document).on('mouseleave','[rel=tooltip]', function(){
    $(this).tooltip('hide');
});

How to convert Rows to Columns in Oracle?

If you are using Oracle 10g, you can use the DECODE function to pivot the rows into columns:

CREATE TABLE doc_tab (
  loan_number VARCHAR2(20),
  document_type VARCHAR2(20),
  document_id VARCHAR2(20)
);

INSERT INTO doc_tab VALUES('992452533663', 'Voters ID', 'XPD0355636');
INSERT INTO doc_tab VALUES('992452533663', 'Pan card', 'CHXPS5522D');
INSERT INTO doc_tab VALUES('992452533663', 'Drivers licence', 'DL-0420110141769');

COMMIT;

SELECT
    loan_number,
    MAX(DECODE(document_type, 'Voters ID', document_id)) AS voters_id,
    MAX(DECODE(document_type, 'Pan card', document_id)) AS pan_card,
    MAX(DECODE(document_type, 'Drivers licence', document_id)) AS drivers_licence
  FROM
    doc_tab
GROUP BY loan_number
ORDER BY loan_number;

Output:

LOAN_NUMBER   VOTERS_ID            PAN_CARD             DRIVERS_LICENCE    
------------- -------------------- -------------------- --------------------
992452533663  XPD0355636           CHXPS5522D           DL-0420110141769     

You can achieve the same using Oracle PIVOT clause, introduced in 11g:

SELECT *
  FROM doc_tab
PIVOT (
  MAX(document_id) FOR document_type IN ('Voters ID','Pan card','Drivers licence')
);

SQLFiddle example with both solutions: SQLFiddle example

Read more about pivoting here: Pivot In Oracle by Tim Hall

How to make a copy of an object in C#

You can use MemberwiseClone

obj myobj2 = (obj)myobj.MemberwiseClone();

The copy is a shallow copy which means the reference properties in the clone are pointing to the same values as the original object but that shouldn't be an issue in your case as the properties in obj are of value types.

If you own the source code, you can also implement ICloneable

how to pass command line arguments to main method dynamically

If you want to launch VM by sending arguments, you should send VM arguments and not Program arguments.

Program arguments are arguments that are passed to your application, which are accessible via the "args" String array parameter of your main method. VM arguments are arguments such as System properties that are passed to the JavaSW interpreter. The Debug configuration above is essentially equivalent to:

java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3

The VM arguments go after the call to your Java interpreter (ie, 'java') and before the Java class. Program arguments go after your Java class.

Consider a program ArgsTest.java:

package test;

import java.io.IOException;

    public class ArgsTest {

        public static void main(String[] args) throws IOException {

            System.out.println("Program Arguments:");
            for (String arg : args) {
                System.out.println("\t" + arg);
            }

            System.out.println("System Properties from VM Arguments");
            String sysProp1 = "sysProp1";
            System.out.println("\tName:" + sysProp1 + ", Value:" + System.getProperty(sysProp1));
            String sysProp2 = "sysProp2";
            System.out.println("\tName:" + sysProp2 + ", Value:" + System.getProperty(sysProp2));

        }
    }

If given input as,

java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3 

in the commandline, in project bin folder would give the following result:

Program Arguments:
  pro1
  pro2
  pro3
System Properties from VM Arguments
  Name:sysProp1, Value:sp1
  Name:sysProp2, Value:sp2

sequelize findAll sort order in nodejs

You can accomplish this in a very back-handed way with the following code:

exports.getStaticCompanies = function () {
    var ids = [46128, 2865, 49569, 1488, 45600, 61991, 1418, 61919, 53326, 61680]
    return Company.findAll({
        where: {
            id: ids
        },
        attributes: ['id', 'logo_version', 'logo_content_type', 'name', 'updated_at'],
        order: sequelize.literal('(' + ids.map(function(id) {
            return '"Company"."id" = \'' + id + '\'');
        }).join(', ') + ') DESC')
    });
};

This is somewhat limited because it's got very bad performance characteristics past a few dozen records, but it's acceptable at the scale you're using.

This will produce a SQL query that looks something like this:

[...] ORDER BY ("Company"."id"='46128', "Company"."id"='2865', "Company"."id"='49569', [...])

Reload chart data via JSON with Highcharts

EDIT: The response down below is more correct!

https://stackoverflow.com/a/8408466/387285

http://www.highcharts.com/ref/#series-object

HTML:

<SELECT id="list">
<OPTION VALUE="A">Data Set A
<OPTION VALUE="B">Data Set B
</SELECT>
<button id="change">Refresh Table</button>

<div id="container" style="height: 400px"></div>

Javascript:

var options = {
    chart: {
        renderTo: 'container',
        defaultSeriesType: 'spline'
    },
    series: []
};

$("#change").click(function() {
    if ($("#list").val() == "A") {
        options.series = [{name: 'A', data: [1,2,3,2,1]}]
        // $.get('/dough/includes/live-chart.php?mode=month'
    } else {
        options.series = [{name: 'B', data: [3,2,1,2,3]}]
        // $.get('/dough/includes/live-chart.php?mode=newmode'
    } 

    var chart = new Highcharts.Chart(options);    
});

This is a very simple example since I don't have my files here with me but the basic idea is that every time the user selects new options for the stuff they want to see, you're going to have replace the .series data object with the new information from your server and then recreate the chart using the new Highcharts.Chart();.

Hope this helps! John

EDIT:

Check this out, its from something I've worked on in the past:

$("table#tblGeneralInfo2 > tbody > tr").each(function (index) {
    if (index != 0) {
        var chartnumbervalue = parseInt($(this).find("td:last").text());
        var charttextvalue = $(this).find("td:first").text();
        chartoptions.series[0].data.push([charttextvalue, chartnumbervalue]);
    }
});

I had a table with information in the first and last tds that I needed to add to the pie chart. I loop through each of the rows and push in the values. Note: I use chartoptions.series[0].data since pie charts only have 1 series.

Setting the correct PATH for Eclipse

I have resolved this problem by adding or changing variables in environment variables. Go to Win7 -> My Computer - > Properties - > Advanced system settings -> environment Variables

  1. If there is no variable JAVA_HOME, add it with value of variable, with route to folder where your JDK installed, for examle C:\Program Files\Java\jdk-11.0.2
  2. If there is no variable PATH or it have another value, change the value of variable to C:\Program Files\Java\jdk-11.0.2\bin or add variable PATH with this value

Good Luck

How to create a dynamic array of integers

You might want to consider using the Standard Template Library . It's simple and easy to use, plus you don't have to worry about memory allocations.

http://www.cplusplus.com/reference/stl/vector/vector/

int size = 5;                    // declare the size of the vector
vector<int> myvector(size, 0);   // create a vector to hold "size" int's
                                 // all initialized to zero
myvector[0] = 1234;              // assign values like a c++ array

Embed ruby within URL : Middleman Blog

<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %>   <i class="fa fa-facebook">     Facebook Share    </i> <%end%> 

I am assuming that current_article_url is http://0.0.0.0:4567/link_to_title

Javascript - validation, numbers only

Regular expressions are great, but why not just make sure it's a number before trying to do something with it?

function addemup() {
var n1 = document.getElementById("num1");
var n2 = document.getElementById("num2");
sum = Number(n1.value) + Number(n2.value);
    if(Number(sum)) {
        alert(sum);
        } else {
            alert("Numbers only, please!");
        };
    };

Android: set view style programmatically

You can apply a style to your activity by doing:

super.setTheme( R.style.MyAppTheme );

or Android default:

super.setTheme( android.R.style.Theme );

in your activity, before setContentView().

How to get value from form field in django framework?

It is easy if you are using django version 3.1 and above

def login_view(request):
    if(request.POST):
        yourForm= YourForm(request.POST)
        itemValue = yourForm['your_filed_name'].value()
        # Check if you get the value
        return HttpResponse(itemValue )
    else:
        return render(request, "base.html")

Check if a varchar is a number (TSQL)

Do not forget to exclude carriage returns from your data !!!

as in:

SELECT 
  Myotherval
  , CASE WHEN TRIM(REPLACE([MyVal], char(13) + char(10), '')) not like '%[^0-9]%' and RTRIM(REPLACE([MyVal], char(13) + char(10), '')) not like '.' and isnumeric(REPLACE([MyVal], char(13) + char(10), '')) = 1 THEN 'my number: ' +  [MyVal]
             ELSE ISNULL(Cast([MyVal] AS VARCHAR(8000)), '')
        END AS 'MyVal'
FROM MyTable

How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

"N/A" is a string and cannot be converted to a number. Catch the exception and handle it. For example:

    String text = "N/A";
    int intVal = 0;
    try {
        intVal = Integer.parseInt(text);
    } catch (NumberFormatException e) {
        //Log it if needed
        intVal = //default fallback value;
    }

Get class labels from Keras functional model

It is possible to save a "list" of labels in keras model directly. This way the user who uses the model for predictions and does not have any other sources of information can perform the lookup himself. Here is a dummy example of how one can perform an "injection" of labels

# assume we get labels as list
labels = ["cat","dog","horse","tomato"]
# here we start building our model with input image 299x299 and one output layer
xx = Input(shape=(299,299,3))
flat = Flatten()(xx)
output = Dense(shape=(4))(flat)
# here we perform injection of labels
tf_labels = tf.constant([labels],dtype="string")
tf_labels = tf.tile(labels,[tf.shape(xx)[0],1])
output_labels = Lambda(lambda x: tf_labels,name="label_injection")(xx)
#and finaly creating a model
model=tf.keras.Model(xx,[output,output_labels])

When used for prediction, this model returns tensor of scores and tensot of string labels. Model like this can be saved to h5. In this case the file contains the labels. This model can also be exported to saved_model and used for serving in the cloud.

NSNotificationCenter addObserver in Swift

In swift 3, Xcode 8.2:- checking battery state level

//Add observer
NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange), name: NSNotification.Name.UIDeviceBatteryStateDidChange, object: nil)


 //Fired when battery level changes

 func batteryStateDidChange(notification: NSNotification){
        //perform manipulation here
    }

Java Serializable Object to Byte Array

Another interesting method is from com.fasterxml.jackson.databind.ObjectMapper

byte[] data = new ObjectMapper().writeValueAsBytes(JAVA_OBJECT_HERE)

Maven Dependency

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>

How does a Linux/Unix Bash script know its own PID?

If the process is a child process and $BASHPID is not set, it is possible to query the ppid of a created child process of the running process. It might be a bit ugly, but it works. Example:

sleep 1 &
mypid=$(ps -o ppid= -p "$!")

Difference between View and Request scope in managed beans

A @ViewScoped bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null or void (and thus navigates back to the same view). Once you refresh the page, or return a non-null string (even an empty string!) navigation outcome, then the view scope will end.

A @RequestScoped bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.

A @ViewScoped bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped bean. Every view has its own unique @ViewScoped bean.

See also:

How to set 777 permission on a particular folder?

Easiest way to set permissions to 777 is to connect to Your server through FTP Application like FileZilla, right click on folder, module_installation, and click Change Permissions - then write 777 or check all permissions.

HashMap and int as key

If you code in Android, there is SparseArray, mapping integer to object.

Select statement to find duplicates on certain fields

To get the list of fields for which there are multiple records, you can use..

select field1,field2,field3, count(*)
  from table_name
  group by field1,field2,field3
  having count(*) > 1

Check this link for more information on how to delete the rows.

http://support.microsoft.com/kb/139444

There should be a criterion for deciding how you define "first rows" before you use the approach in the link above. Based on that you'll need to use an order by clause and a sub query if needed. If you can post some sample data, it would really help.

How to change the color of progressbar in C# .NET 3.5?

Modificaton to dustyburwell's answer. (I don't have enough rep to edit it myself.) Like his answer, it works with "Visual Styles" enabled. You can just set the progressbar's ForeColor property in whatever form's design view.

using System;
using System.Windows.Forms;
using System.Drawing;

public class ProgressBarEx : ProgressBar
{
    private SolidBrush brush = null;

    public ProgressBarEx()
    {
        this.SetStyle(ControlStyles.UserPaint, true);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        if (brush == null || brush.Color != this.ForeColor)
            brush = new SolidBrush(this.ForeColor);

        Rectangle rec = new Rectangle(0, 0, this.Width, this.Height);
        if (ProgressBarRenderer.IsSupported)
            ProgressBarRenderer.DrawHorizontalBar(e.Graphics, rec);
        rec.Width = (int)(rec.Width * ((double)Value / Maximum)) - 4;
        rec.Height = rec.Height - 4;
        e.Graphics.FillRectangle(brush, 2, 2, rec.Width, rec.Height);
    }
}

Horizontal scroll css?

I figured it this way:

* { padding: 0; margin: 0 }
body { height: 100%; white-space: nowrap }
html { height: 100% }

.red { background: red }
.blue { background: blue }
.yellow { background: yellow }

.header { width: 100%; height: 10%; position: fixed }
.wrapper { width: 1000%; height: 100%; background: green }
.page { width: 10%; height: 100%; float: left }

<div class="header red"></div>
<div class="wrapper">
    <div class="page yellow"></div>
    <div class="page blue"></div>
    <div class="page yellow"></div>
    <div class="page blue"></div>
    <div class="page yellow"></div>
    <div class="page blue"></div>
    <div class="page yellow"></div>
    <div class="page blue"></div>
    <div class="page yellow"></div>
    <div class="page blue"></div>
</div>

I have the wrapper at 1000% and ten pages at 10% each. I set mine up to still have "pages" with each being 100% of the window (color coded). You can do eight pages with an 800% wrapper. I guess you can leave out the colors and have on continues page. I also set up a fixed header, but that's not necessary. Hope this helps.

How to write log to file

I prefer the simplicity and flexibility of the 12 factor app recommendation for logging. To append to a log file you can use shell redirection. The default logger in Go writes to stderr (2).

./app 2>> logfile

See also: http://12factor.net/logs

multiprocessing.Pool: When to use apply, apply_async or map?

Regarding apply vs map:

pool.apply(f, args): f is only executed in ONE of the workers of the pool. So ONE of the processes in the pool will run f(args).

pool.map(f, iterable): This method chops the iterable into a number of chunks which it submits to the process pool as separate tasks. So you take advantage of all the processes in the pool.

AddRange to a Collection

Agree with some guys above and Lipert's opinion. In my case, it's quite often to do like this:

ICollection<int> A;
var B = new List<int> {1,2,3,4,5};
B.ForEach(A.Add);

To have an extension method for such operation a bit redundant in my view.

How to get source code of a Windows executable?

There's nothing you can do about it i'm afraid as you won't be able to view it in a readable format, it's pretty much intentional and it'll show the interpreted machine code, there would be no formatting or comments as you normally get in .cs/.c files.

It's pretty much a hit and miss scenario.

Someone has already asked about it on another website

Including a .js file within a .js file

I basically do like this, create new element and attach that to <head>

var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);

You may also use onload event to each script you attach, but please test it out, I am not so sure it works cross-browser or not.

x.onload=callback_function;

How to get UTF-8 working in Java webapps?

Nice detailed answer. just wanted to add one more thing which will definitely help others to see the UTF-8 encoding on URLs in action .

Follow the steps below to enable UTF-8 encoding on URLs in firefox.

  1. type "about:config" in the address bar.

  2. Use the filter input type to search for "network.standard-url.encode-query-utf8" property.

  3. the above property will be false by default, turn that to TRUE.
  4. restart the browser.

UTF-8 encoding on URLs works by default in IE6/7/8 and chrome.

How do I open phone settings when a button is clicked?

I have seen this line of code

UIApplication.sharedApplication() .openURL(NSURL(string:"prefs:root=General")!)

is not working, it didn't work for me in ios10/ Xcode 8, just a small code difference, please replace this with

UIApplication.sharedApplication().openURL(NSURL(string:"App-Prefs:root=General")!)

Swift3

UIApplication.shared.openURL(URL(string:"prefs:root=General")!)

Replace with

UIApplication.shared.openURL(URL(string:"App-Prefs:root=General")!)

Hope it helps. Cheers.

How to generate and manually insert a uniqueidentifier in sql server?

ApplicationId must be of type UniqueIdentifier. Your code works fine if you do:

DECLARE @TTEST TABLE
(
  TEST UNIQUEIDENTIFIER
)

DECLARE @UNIQUEX UNIQUEIDENTIFIER
SET @UNIQUEX = NEWID();

INSERT INTO @TTEST
(TEST)
VALUES
(@UNIQUEX);

SELECT * FROM @TTEST

Therefore I would say it is safe to assume that ApplicationId is not the correct data type.

Nginx - Customizing 404 page

These answers are no longer recommended since try_files works faster than if in this context. Simply add try_files in your php location block to test if the file exists, otherwise return a 404.

location ~ \.php {
    try_files $uri =404;
    ...
}

Basic text editor in command prompt?

There is no command based text editors in windows (at least from Windows 7). But you can try the vi windows clone available here : http://www.vim.org/

lambda expression for exists within list

var query = list.Where(r => listofIds.Any(id => id == r.Id));

Another approach, useful if the listOfIds array is large:

HashSet<int> hash = new HashSet<int>(listofIds);
var query = list.Where(r => hash.Contains(r.Id));

Call two functions from same onclick

You can create a single function that calls both of those, and then use it in the event.

function myFunction(){
    pay();
    cls();
}

And then, for the button:

<input id="btn" type="button" value="click" onclick="myFunction();"/>

How do I pick randomly from an array?

Random Number of Random Items from an Array

def random_items(array)
  array.sample(1 + rand(array.count))
end

Examples of possible results:

my_array = ["one", "two", "three"]
my_array.sample(1 + rand(my_array.count))

=> ["two", "three"]
=> ["one", "three", "two"]
=> ["two"]

How to set a radio button in Android

If you want to do it in code, you can call the check member of RadioGroup:

radioGroup.check(R.id.radioButtonId);

This will check the button you specify and uncheck the others.

How to get full path of a file?

In mac mentioned below line works. No need to add any fancy lines.

> pwd filename

How would I get everything before a : in a string Python

Just use the split function. It returns a list, so you can keep the first element:

>>> s1.split(':')
['Username', ' How are you today?']
>>> s1.split(':')[0]
'Username'

Using form input to access camera and immediately upload photos using web app

It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.

<input id="myFileInput" type="file" accept="image/*;capture=camera">

var myInput = document.getElementById('myFileInput');

function sendPic() {
    var file = myInput.files[0];

    // Send file here either by adding it to a `FormData` object 
    // and sending that via XHR, or by simply passing the file into 
    // the `send` method of an XHR instance.
}

myInput.addEventListener('change', sendPic, false);

How can I get the "network" time, (from the "Automatic" setting called "Use network-provided values"), NOT the time on the phone?

the time signal is not built into network antennas: you have to use the NTP protocol in order to retrieve the time on a ntp server. there are plenty of ntp clients, available as standalone executables or libraries.

the gps signal does indeed include a precise time signal, which is available with any "fix".

however, if nor the network, nor the gps are available, your only choice is to resort on the time of the phone... your best solution would be to use a system wide setting to synchronize automatically the phone time to the gps or ntp time, then always use the time of the phone.

note that the phone time, if synchronized regularly, should not differ much from the gps or ntp time. also note that forcing a user to synchronize its time may be intrusive, you 'd better ask your user if he accepts synchronizing. at last, are you sure you absolutely need a time that precise ?

Android: how to parse URL String with spaces to URI object?

To handle spaces, @, and other unsafe characters in arbitrary locations in the url path, Use Uri.Builder in combination with a local instance of URL as I have described here:

private Uri.Builder builder;
public Uri getUriFromUrl(String thisUrl) {
    URL url = new URL(thisUrl);
    builder =  new Uri.Builder()
                            .scheme(url.getProtocol())
                            .authority(url.getAuthority())
                            .appendPath(url.getPath());
    return builder.build();
}

jQuery - Create hidden form element on the fly

function addHidden(theForm, key, value) {
    // Create a hidden input element, and append it to the form:
    var input = document.createElement('input');
    input.type = 'hidden';
    input.name = key; //name-as-seen-at-the-server
    input.value = value;
    theForm.appendChild(input);
}

// Form reference:
var theForm = document.forms['detParameterForm'];

// Add data:
addHidden(theForm, 'key-one', 'value');

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

Use a literal control and write your html like this:

literal1.text = "<h2><p>Notify:</p> alert</h2>";

How can I convert a Timestamp into either Date or DateTime object?

java.time

Modern answer: use java.time, the modern Java date and time API, for your date and time work. Back in 2011 it was right to use the Timestamp class, but since JDBC 4.2 it is no longer advised.

For your work we need a time zone and a couple of formatters. We may as well declare them static:

static ZoneId zone = ZoneId.of("America/Marigot");
static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm xx");

Now the code could be for example:

    while(resultSet.next()) {
        ZonedDateTime dtStart = resultSet.getObject("dtStart", OffsetDateTime.class)
                 .atZoneSameInstant(zone);

        // I would like to then have the date and time
        // converted into the formats mentioned...
        String dateFormatted = dtStart.format(dateFormatter);
        String timeFormatted = dtStart.format(timeFormatter);
        System.out.format("Date: %s; time: %s%n", dateFormatted, timeFormatted);
    }

Example output (using the time your question was asked):

Date: 09/20/2011; time: 18:13 -0400

In your database timestamp with time zone is recommended for timestamps. If this is what you’ve got, retrieve an OffsetDateTime as I am doing in the code. I am also converting the retrieved value to the user’s time zone before formatting date and time separately. As time zone I supplied America/Marigot as an example, please supply your own. You may also leave out the time zone conversion if you don’t want any, of course.

If the datatype in SQL is a mere timestamp without time zone, retrieve a LocalDateTime instead. For example:

        ZonedDateTime dtStart = resultSet.getObject("dtStart", LocalDateTime.class)
                 .atZone(zone);

No matter the details I trust you to do similarly for dtEnd.

I wasn’t sure what you meant by the xx in HH:MM xx. I just left it in the format pattern string, which yields the UTC offset in hours and minutes without colon.

Link: Oracle tutorial: Date Time explaining how to use java.time.

Use Expect in a Bash script to provide a password to an SSH command

Another way that I found useful to use a small Expect script from a Bash script is as follows.

...
Bash script start
Bash commands
...
expect - <<EOF
spawn your-command-here
expect "some-pattern"
send "some-command"
...
...
EOF
...
More Bash commands
...

This works because ...If the string "-" is supplied as a filename, standard input is read instead...

handling DATETIME values 0000-00-00 00:00:00 in JDBC

Alternative answer, you can use this JDBC URL directly in your datasource configuration:

jdbc:mysql://yourserver:3306/yourdatabase?zeroDateTimeBehavior=convertToNull

Edit:

Source: MySQL Manual

Datetimes with all-zero components (0000-00-00 ...) — These values can not be represented reliably in Java. Connector/J 3.0.x always converted them to NULL when being read from a ResultSet.

Connector/J 3.1 throws an exception by default when these values are encountered as this is the most correct behavior according to the JDBC and SQL standards. This behavior can be modified using the zeroDateTimeBehavior configuration property. The allowable values are:

  • exception (the default), which throws an SQLException with an SQLState of S1009.
  • convertToNull, which returns NULL instead of the date.
  • round, which rounds the date to the nearest closest value which is 0001-01-01.

Update: Alexander reported a bug affecting mysql-connector-5.1.15 on that feature. See CHANGELOGS on the official website.

How can I link a photo in a Facebook album to a URL

Unfortunately, no. This feature is not available for facebook albums.

How to add custom validation to an AngularJS form?

Custom Validations that call a Server

Use the ngModelController $asyncValidators API which handles asynchronous validation, such as making an $http request to the backend. Functions added to the object must return a promise that must be resolved when valid or rejected when invalid. In-progress async validations are stored by key in ngModelController.$pending. For more information, see AngularJS Developer Guide - Forms (Custom Validation).

ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  var value = modelValue || viewValue;

  // Lookup user by username
  return $http.get('/api/users/' + value).
     then(function resolved() {
       //username exists, this means validation fails
       return $q.reject('exists');
     }, function rejected() {
       //username does not exist, therefore this validation passes
       return true;
     });
};

For more information, see


Using the $validators API

The accepted answer uses the $parsers and $formatters pipelines to add a custom synchronous validator. AngularJS 1.3+ added a $validators API so there is no need to put validators in the $parsers and $formatters pipelines:

app.directive('blacklist', function (){ 
   return {
      require: 'ngModel',
      link: function(scope, elem, attr, ngModel) {           
          ngModel.$validators.blacklist = function(modelValue, viewValue) {
              var blacklist = attr.blacklist.split(',');
              var value = modelValue || viewValue;
              var valid = blacklist.indexOf(value) === -1;
              return valid;
          });    
      }
   };
});

For more information, see AngularJS ngModelController API Reference - $validators.

How to create a file on Android Internal Storage?

Hi try this it will create directory + file inside it

File mediaDir = new File("/sdcard/download/media");
if (!mediaDir.exists()){
    mediaDir.mkdir();
}

File resolveMeSDCard = new File("/sdcard/download/media/hello_file.txt");
resolveMeSDCard.createNewFile();
FileOutputStream fos = new FileOutputStream(resolveMeSDCard);
fos.write(string.getBytes());
fos.close();

System.out.println("Your file has been written");  

What is the strict aliasing rule?

Strict aliasing is not allowing different pointer types to the same data.

This article should help you understand the issue in full detail.

Using :after to clear floating elements

Write like this:

.wrapper:after {
    content: '';
    display: block;
    clear: both;
}

Check this http://jsfiddle.net/EyNnk/1/

test if event handler is bound to an element in jQuery

I wrote a very tiny plugin called "once" which do that:

$.fn.once = function(a, b) {
    return this.each(function() {
        $(this).off(a).on(a,b);
    });
};

And simply:

$(element).once('click', function(){
});

MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"

check to make the field you are referencing to is an exact match with foreign key, in my case one was unsigned and the other was signed so i just changed them to match and this worked

ALTER TABLE customer_information ADD CONSTRAINT fk_customer_information1 FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE

Get the new record primary key ID from MySQL insert query?

BEWARE !! of LAST_INSERT_ID() if trying to return this primary key value within PHP.

I know this thread is not tagged PHP, but for anybody who came across this answer looking to return a MySQL insert id from a PHP scripted insert using standard mysql_query calls - it wont work and is not obvious without capturing SQL errors.

The newer mysqli supports multiple queries - which LAST_INSERT_ID() actually is a second query from the original.

IMO a separate SELECT to identify the last primary key is safer than the optional mysql_insert_id() function returning the AUTO_INCREMENT ID generated from the previous INSERT operation.

Setting timezone in Python

Be aware that running

import os
os.system("tzutil /s \"Central Standard Time\"");

will alter Windows system time, NOT just the local python environment time (so is definitley NOT the same as:

>>> os.environ['TZ'] = 'Europe/London'
>>> time.tzset()

which will only set in the current environment time (in Unix only)

jQuery - find table row containing table cell containing specific text

   <input type="text" id="text" name="search">
<table id="table_data">
        <tr class="listR"><td>PHP</td></tr>
        <tr class="listR"><td>MySql</td></tr>
        <tr class="listR"><td>AJAX</td></tr>
        <tr class="listR"><td>jQuery</td></tr>
        <tr class="listR"><td>JavaScript</td></tr>
        <tr class="listR"><td>HTML</td></tr>
        <tr class="listR"><td>CSS</td></tr>
        <tr class="listR"><td>CSS3</td></tr>
</table>

$("#textbox").on('keyup',function(){
        var f = $(this).val();
      $("#table_data tr.listR").each(function(){
            if ($(this).text().search(new RegExp(f, "i")) < 0) {
                $(this).fadeOut();
             } else {
                 $(this).show();
            }
        });
    });

Demo You can perform by search() method with use RegExp matching text

Creating a JSON response using Django and Python

First import this:

from django.http import HttpResponse

If you have the JSON already:

def your_method(request):
    your_json = [{'key1': value, 'key2': value}]
    return HttpResponse(your_json, 'application/json')

If you get the JSON from another HTTP request:

def your_method(request):
    response = request.get('https://www.example.com/get/json')
    return HttpResponse(response, 'application/json')

creating custom tableview cells in swift

It is Purely swift notation an working for me

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        var cellIdentifier:String = "CustomFields"
        var cell:CustomCell? = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? CustomCell
        if (cell == nil)
        {
            var nib:Array = NSBundle.mainBundle().loadNibNamed("CustomCell", owner: self, options: nil)
            cell = nib[0] as? CustomCell
        }
        return cell!
    }

Unable to Resolve Module in React Native App

reload the app and the cause of this error is the changes of files location made in react-native dependency which other libraries like native-base point to.

To solve it you need to view the mentioned file and change the file location to the correct location.

How do I get the size of a java.sql.ResultSet?

ResultSet rs = ps.executeQuery();
int rowcount = 0;
if (rs.last()) {
  rowcount = rs.getRow();
  rs.beforeFirst(); // not rs.first() because the rs.next() below will move on, missing the first element
}
while (rs.next()) {
  // do your standard per row stuff
}

How to Resize a Bitmap in Android?

As of API 19, Bitmap setWidth(int width) and setHeight(int height) exist. http://developer.android.com/reference/android/graphics/Bitmap.html

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

some problem, but I find the solution, this is :


2 February Feb 28 (29 in leap years)

this is my code

 public string GetCountArchiveByMonth(int iii)
        {
// iii: is number of months, use any number other than (**2**)

            con.Open();

            SqlCommand cmd10 = con.CreateCommand();
            cmd10.CommandType = CommandType.Text;
            cmd10.CommandText = "select count(id_post) from posts where dateadded between CONVERT(VARCHAR, @start, 103) and CONVERT(VARCHAR, @end, 103)";
            cmd10.Parameters.AddWithValue("@start", "" + iii + "/01/2019");
            cmd10.Parameters.AddWithValue("@end", "" + iii + "/30/2019");
            string result = cmd10.ExecuteScalar().ToString();

            con.Close();

            return result;
        }

now for test

 lbl1.Text = GetCountArchiveByMonth(**7**).ToString();  // here use any number other than (**2**)

**

because of check **February** is maxed 28 days,

**

How can I convert a string to a float in mysql?

It turns out I was just missing DECIMAL on the CAST() description:

DECIMAL[(M[,D])]

Converts a value to DECIMAL data type. The optional arguments M and D specify the precision (M specifies the total number of digits) and the scale (D specifies the number of digits after the decimal point) of the decimal value. The default precision is two digits after the decimal point.

Thus, the following query worked:

UPDATE table SET
latitude = CAST(old_latitude AS DECIMAL(10,6)),
longitude = CAST(old_longitude AS DECIMAL(10,6));

Setting font on NSAttributedString on UITextView disregards line spacing

Attributed String Programming Guide:

UIFont *font = [UIFont fontWithName:@"Palatino-Roman" size:14.0];
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:font
                                forKey:NSFontAttributeName];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"strigil" attributes:attrsDictionary];

Update: I tried to use addAttribute: method in my own app, but it seemed to be not working on the iOS 6 Simulator:

NSLog(@"%@", textView.attributedText);

The log seems to show correctly added attributes, but the view on iOS simulator was not display with attributes.

POST request with a simple string in body with Alamofire

If you want to post string as raw body in request

return Alamofire.request(.POST, "http://mywebsite.com/post-request" , parameters: [:], encoding: .Custom({
            (convertible, params) in
            let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest

            let data = ("myBodyString" as NSString).dataUsingEncoding(NSUTF8StringEncoding)
            mutableRequest.HTTPBody = data
            return (mutableRequest, nil)
        }))

Does VBA contain a comment block syntax?

There is no syntax for block quote in VBA. The work around is to use the button to quickly block or unblock multiple lines of code.

Getting the names of all files in a directory with PHP

I have smaller code todo this:

$path = "Pending2Post/";
$files = scandir($path);
foreach ($files as &$value) {
    echo "<a href='http://localhost/".$value."' target='_blank' >".$value."</a><br/><br/>";
}

What is default list styling (CSS)?

An answer for the future: CSS 4 will probably contain the revert keyword, which reverts a property to its value from the user or user-agent stylesheet [source]. As of writing this, only Safari supports this – check here for updates on browser support.

In your case you would use:

.my_container ol, .my_container ul {
    list-style: revert;
}

See also this other answer with some more details.

What happened to Lodash _.pluck?

If you really want _.pluck support back, you can use a mixin:

const _ = require("lodash")

_.mixin({
    pluck: _.map
})

Because map now supports a string (the "iterator") as an argument instead of a function.

What HTTP traffic monitor would you recommend for Windows?

Try Wireshark:

Wireshark is the world's foremost network protocol analyzer, and is the de facto (and often de jure) standard across many industries and educational institutions.

There is a bit of a learning curve but it is far and away the best tool available.

Converting an object to a string

If you can use lodash you can do it this way:

> var o = {a:1, b:2};
> '{' + _.map(o, (value, key) => key + ':' + value).join(', ') + '}'
'{a:1, b:2}'

With lodash map() you can iterate over Objects as well. This maps every key/value entry to its string representation:

> _.map(o, (value, key) => key + ':' + value)
[ 'a:1', 'b:2' ]

And join() put the array entries together.

If you can use ES6 Template String, this works also:

> `{${_.map(o, (value, key) => `${key}:${value}`).join(', ')}}`
'{a:1, b:2}'

Please note this do not goes recursive through the Object:

> var o = {a:1, b:{c:2}}
> _.map(o, (value, key) => `${key}:${value}`)
[ 'a:1', 'b:[object Object]' ]

Like node's util.inspect() will do:

> util.inspect(o)
'{ a: 1, b: { c: 2 } }'

making matplotlib scatter plots from dataframes in Python's pandas

I will recommend to use an alternative method using seaborn which more powerful tool for data plotting. You can use seaborn scatterplot and define colum 3 as hue and size.

Working code:

import pandas as pd
import seaborn as sns
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20),'col_name_3': np.arange(20)*100}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df, hue="col_name_3",size="col_name_3")

enter image description here

How do I copy items from list to list without foreach?

And this is if copying a single property to another list is needed:

targetList.AddRange(sourceList.Select(i => i.NeededProperty));

array filter in python?

This was just asked a couple of days ago (but I cannot find it):

>>> A = [6, 7, 8, 9, 10, 11, 12]
>>> subset_of_A = set([6, 9, 12])
>>> [i for i in A if i not in subset_of_A]
[7, 8, 10, 11]

It might be better to use sets from the beginning, depending on the context. Then you can use set operations like other answers show.

However, converting lists to sets and back only for these operations is slower than list comprehension.

how to clear localstorage,sessionStorage and cookies in javascript? and then retrieve?

There is no way to retrieve localStorage, sessionStorage or cookie values via javascript in the browser after they've been deleted via javascript.

If what you're really asking is if there is some other way (from outside the browser) to recover that data, that's a different question and the answer will entirely depend upon the specific browser and how it implements the storage of each of those types of data.

For example, Firefox stores cookies as individual files. When a cookie is deleted, its file is deleted. That means that the cookie can no longer be accessed via the browser. But, we know that from outside the browser, using system tools, the contents of deleted files can sometimes be retrieved.

If you wanted to look into this further, you'd have to discover how each browser stores each data type on each platform of interest and then explore if that type of storage has any recovery strategy.

PHP add elements to multidimensional array with array_push

As in the multi-dimensional array an entry is another array, specify the index of that value to array_push:

array_push($md_array['recipe_type'], $newdata);

How to paginate with Mongoose in Node.js?

You can either use skip() and limit(), but it's very inefficient. A better solution would be a sort on indexed field plus limit(). We at Wunderflats have published a small lib here: https://github.com/wunderflats/goosepage It uses the first way.

ListBox with ItemTemplate (and ScrollBar!)

I have never had any luck with any scrollable content placed inside a stackpanel (anything derived from ScrollableContainer. The stackpanel has an odd layout mechanism that confuses child controls when the measure operation is completed and I found the vertical size ends up infinite, therefore not constrained - so it goes beyond the boundaries of the container and ends up clipped. The scrollbar doesn't show because the control thinks it has all the space in the world when it doesn't.

You should always place scrollable content inside a container that can resolve to a known height during its layout operation at runtime so that the scrollbars size appropriately. The parent container up in the visual tree must be able to resolve to an actual height, and this happens in the grid if you set the height of the RowDefinition o to auto or fixed.

This also happens in Silverlight.

-em-

NPM: npm-cli.js not found when running npm

create a npm folder manually inside node_modules and rerun the installer with repair options. It copies the missing files.

How to link to a <div> on another page?

You simply combine the ideas of a link to another page, as with href=foo.html, and a link to an element on the same page, as with href=#bar, so that the fragment like #bar is written immediately after the URL that refers to another page:

<a href="foo.html#bar">Some nice link text</a>

The target is specified the same was as when linking inside one page, e.g.

<div id="bar">
<h2>Some heading</h2>
Some content
</div>

or (if you really want to link specifically to a heading only)

<h2 id="bar">Some heading</h2>

What is log4j's default log file dumping path

You can see the log info in the console view of your IDE if you are not using any log4j properties to generate log file. You can define log4j.properties in your project so that those properties would be used to generate log file. A quick sample is listed below.

# Global logging configuration
log4j.rootLogger=DEBUG, stdout, R

# SQL Map logging configuration...
log4j.logger.com.ibatis=INFO
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=INFO
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=INFO
log4j.logger.com.ibatis.SQLMap.engine.impl.SQL MapClientDelegate=INFO

log4j.logger.java.sql.Connection=INFO
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.ResultSet=INFO

log4j.logger.org.apache.http=ERROR

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=MyLog.log
log4j.appender.R.MaxFileSize=50000KB
log4j.appender.R.Encoding=UTF-8

# Keep one backup file
log4j.appender.R.MaxBackupIndex=1

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d %5p [%t] (%F\:%L) - %m%n

implementing merge sort in C++

The problem with merge sort is the merge, if you don't actually need to implement the merge, then it is pretty simple (for a vector of ints):

#include <algorithm>
#include <vector>
using namespace std;

typedef vector<int>::iterator iter;

void mergesort(iter b, iter e) {
    if (e -b > 1) {
        iter m = b + (e -b) / 2;
        mergesort(b, m);
        mergesort(m, e);
        inplace_merge(b, m, e);
    }
}

Show/hide image with JavaScript

If you already have a JavaScript function called showImage defined to show the image, you can link as such:

<a href="javascript:showImage()">show image</a>

If you need help defining the function, I would try:

function showImage() {
    var img = document.getElementById('myImageId');
    img.style.visibility = 'visible';
}

Or, better yet,

function setImageVisible(id, visible) {
    var img = document.getElementById(id);
    img.style.visibility = (visible ? 'visible' : 'hidden');
}

Then, your links would be:

<a href="javascript:setImageVisible('myImageId', true)">show image</a>
<a href="javascript:setImageVisible('myImageId', false)">hide image</a>

java.rmi.ConnectException: Connection refused to host: 127.0.1.1;

I had the same exact problem and my issue was that I had 2 IP addresses from 2 different networks configured in the etc/hosts as below.

10.xxx.x.xxx    localhost
192.xxx.x.xxx   localhost

This should be because there was a conflict as to which IP to be used for the other devices to reach the rmiregistry over the network.

Once I removed the extra-record that is not required, I was able to solve the issue.

So my etc/hosts file had only the following record.

10.xxx.x.xxx    localhost

What is the best IDE for PHP?

There is a new guy in town, PhpStorm from JetBrains. You use it and I bet you will forget all the other editors. It's bit pricey though, unfortunately.

Fragments within Fragments

I have an application that I am developing that is laid out similar with Tabs in the Action Bar that launches fragments, some of these Fragments have multiple embedded Fragments within them.

I was getting the same error when I tried to run the application. It seems like if you instantiate the Fragments within the xml layout after a tab was unselected and then reselected I would get the inflator error.

I solved this replacing all the fragments in xml with Linearlayouts and then useing a Fragment manager/ fragment transaction to instantiate the fragments everything seems to working correctly at least on a test level right now.

I hope this helps you out.

How do I get the day of week given a date?

Assuming you are given the day, month, and year, you could do:

import datetime
DayL = ['Mon','Tues','Wednes','Thurs','Fri','Satur','Sun']
date = DayL[datetime.date(year,month,day).weekday()] + 'day'
#Set day, month, year to your value
#Now, date is set as an actual day, not a number from 0 to 6.

print(date)

Resizing Images in VB.NET

This will re-size any image using the best quality with support for 32bpp with alpha. The new image will have the original image centered inside the new one at the original aspect ratio.

#Region " ResizeImage "
    Public Overloads Shared Function ResizeImage(SourceImage As Drawing.Image, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
        Dim bmSource = New Drawing.Bitmap(SourceImage)

        Return ResizeImage(bmSource, TargetWidth, TargetHeight)
    End Function

    Public Overloads Shared Function ResizeImage(bmSource As Drawing.Bitmap, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
        Dim bmDest As New Drawing.Bitmap(TargetWidth, TargetHeight, Drawing.Imaging.PixelFormat.Format32bppArgb)

        Dim nSourceAspectRatio = bmSource.Width / bmSource.Height
        Dim nDestAspectRatio = bmDest.Width / bmDest.Height

        Dim NewX = 0
        Dim NewY = 0
        Dim NewWidth = bmDest.Width
        Dim NewHeight = bmDest.Height

        If nDestAspectRatio = nSourceAspectRatio Then
            'same ratio
        ElseIf nDestAspectRatio > nSourceAspectRatio Then
            'Source is taller
            NewWidth = Convert.ToInt32(Math.Floor(nSourceAspectRatio * NewHeight))
            NewX = Convert.ToInt32(Math.Floor((bmDest.Width - NewWidth) / 2))
        Else
            'Source is wider
            NewHeight = Convert.ToInt32(Math.Floor((1 / nSourceAspectRatio) * NewWidth))
            NewY = Convert.ToInt32(Math.Floor((bmDest.Height - NewHeight) / 2))
        End If

        Using grDest = Drawing.Graphics.FromImage(bmDest)
            With grDest
                .CompositingQuality = Drawing.Drawing2D.CompositingQuality.HighQuality
                .InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
                .PixelOffsetMode = Drawing.Drawing2D.PixelOffsetMode.HighQuality
                .SmoothingMode = Drawing.Drawing2D.SmoothingMode.AntiAlias
                .CompositingMode = Drawing.Drawing2D.CompositingMode.SourceOver

                .DrawImage(bmSource, NewX, NewY, NewWidth, NewHeight)
            End With
        End Using

        Return bmDest
    End Function
#End Region

Laravel: getting a a single value from a MySQL query

On laravel 5.6 it has a very simple solution:

User::where('username', $username)->first()->groupName;

It will return groupName as a string.

How to remove the arrows from input[type="number"] in Opera

I've been using some simple CSS and it seems to remove them and work fine.

_x000D_
_x000D_
input[type=number]::-webkit-inner-spin-button, _x000D_
input[type=number]::-webkit-outer-spin-button { _x000D_
    -webkit-appearance: none;_x000D_
    -moz-appearance: none;_x000D_
    appearance: none;_x000D_
    margin: 0; _x000D_
}
_x000D_
<input type="number" step="0.01"/>
_x000D_
_x000D_
_x000D_

This tutorial from CSS Tricks explains in detail & also shows how to style them

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

One way of doing this without changing Volley's source code is to check for the response data in the VolleyError and parse it your self.

As of f605da3 commit, Volley throws a ServerError exception that contains the raw network response.

So you can do something similar to this in your error listener:

/* import com.android.volley.toolbox.HttpHeaderParser; */
public void onErrorResponse(VolleyError error) {

    // As of f605da3 the following should work
    NetworkResponse response = error.networkResponse;
    if (error instanceof ServerError && response != null) {
        try {
            String res = new String(response.data,
                       HttpHeaderParser.parseCharset(response.headers, "utf-8"));
            // Now you can use any deserializer to make sense of data
            JSONObject obj = new JSONObject(res);
        } catch (UnsupportedEncodingException e1) {
            // Couldn't properly decode data to string
            e1.printStackTrace();
        } catch (JSONException e2) {
            // returned data is not JSONObject?
            e2.printStackTrace();
        }
    }
}

For future, if Volley changes, one can follow the above approach where you need to check the VolleyError for raw data that has been sent by the server and parse it.

I hope that they implement that TODO mentioned in the source file.

Safely override C++ virtual functions

I would suggest a slight change in your logic. It may or may not work, depending on what you need to accomplish.

handle_event() can still do the "boring default code" but instead of being virtual, at the point where you want it to do the "new exciting code" have the base class call an abstract method (i.e. must-be-overridden) method that will be supplied by your descendant class.

EDIT: And if you later decide that some of your descendant classes do not need to provide "new exciting code" then you can change the abstract to virtual and supply an empty base class implementation of that "inserted" functionality.

Counting the number of elements in array

This expands on the answer by Denis Bubnov.

I used this to find child values of array elements—namely if there was a anchor field in paragraphs on a Drupal 8 site to build a table of contents.

{% set count = 0 %}
{% for anchor in items %}
    {% if anchor.content['#paragraph'].field_anchor_link.0.value %}
        {% set count = count + 1 %}
    {% endif %}
{% endfor %}

{% if count > 0 %}
 ---  build the toc here --
{% endif %}

Remote origin already exists on 'git push' to a new repository

git remote rm origin
git remote add origin [email protected]:username/myapp.git

Bootstrap 3.0 Sliding Menu from left

I believe that although javascript is an option here, you have a smoother animation through forcing hardware accelerate with CSS3. You can achieve this by setting the following CSS3 properties on the moving div:

div.hardware-accelarate {
     -webkit-transform: translate3d(0,0,0);
        -moz-transform: translate3d(0,0,0);
         -ms-transform: translate3d(0,0,0);
          -o-transform: translate3d(0,0,0);
             transform: translate3d(0,0,0);
}

I've made a plunkr setup for ya'll to test and tweak...

TypeError: $ is not a function when calling jQuery function

This should fix it:

jQuery(document).ready(function($){
  //you can now use $ as your jQuery object.
  var body = $( 'body' );
});

Put simply, WordPress runs their own scripting before you can and they release the $ var so it won't collide with other libraries. This makes total sense, as WordPress is used for all kinds of web sites, apps, and of course, blogs.

From their documentation:

The jQuery library included with WordPress is set to the noConflict() mode (see wp-includes/js/jquery/jquery.js). This is to prevent compatibility problems with other JavaScript libraries that WordPress can link.

In the noConflict() mode, the global $ shortcut for jQuery is not available...

How can I remove time from date with Moment.js?

Use format('LL')

Depending on what you're trying to do with it, format('LL') could do the trick. It produces something like this:

Moment().format('LL'); // => April 29, 2016

curl Failed to connect to localhost port 80

In my case, the file ~/.curlrc had a wrong proxy configured.

Launch Image does not show up in my iOS App

I just figured this out. My launch image was not showing up, I get a white screen when launching on a device (iPhone 6, 7+) or testFlight. Fix: Renamed "Landing_screen.png" to just "Landing_screen" removing .png part. The image icon in Xcode changed to white icon and in the launch screen storyboard the image appears as a question mark now. The Launch image now appears and not the white screen. My Setup: I am using Swift 3.1 with Xcode 8.3.1. In LaunchScreen.storyboard I added a simple image view and stretched the image to fit the view controller. I set auto layout constraints Top/Bottom/Leading/Trailing space to superview to 0.

How to hide 'Back' button on navigation bar on iPhone?

In c# or Xamarin.ios, this.NavigationItem.HidesBackButton = true;

Where do I put image files, css, js, etc. in Codeigniter?

I'm using the latest version of CodeIgniter 3.1.0. The folder structure of it is:

  • system
  • application
  • user_guide
  • assets
    • images
    • js
    • css

That's where you should put the images, css and js files inside the assets folder.

Git: can't undo local changes (error: path ... is unmerged)

git checkout foo/bar.txt

did you tried that? (without a HEAD keyword)

I usually revert my changes this way.

Where does MAMP keep its php.ini?

I was struggling with this too. My changes weren't being reflected in phpInfo. It wasn't until I stopped my servers and then restarted them again that my changes actually took effect.

How to setup Main class in manifest file in jar produced by NetBeans project

Adding manifest.file=manifest.mf into project.properties and creating manifest.mf file in the project directory works fine in NB 6.9 and should work also in NB 6.8.

Converting String to "Character" array in Java

One liner with :

String str = "testString";

//[t, e, s, t, S, t, r, i, n, g]
Character[] charObjectArray = 
    str.chars().mapToObj(c -> (char)c).toArray(Character[]::new); 

What it does is:

  • get an IntStream of the characters (you may want to also look at codePoints())
  • map each 'character' value to Character (you need to cast to actually say that its really a char, and then Java will box it automatically to Character)
  • get the resulting array by calling toArray()