Programs & Examples On #Swt

SWT: The Standard Widget Toolkit is a user interface library for Java maintained by the Eclipse Foundation. SWT uses native widgets wherever possible to provide a look and feel consistent with the host platform. SWT is a third-party library (not included in the JVM) and applications that rely on it must distribute the appropriate library for each target operating system. Use this tag for questions about developing SWT based applications.

Create GUI using Eclipse (Java)

Yes, there is one. It is an eclipse-plugin called Visual Editor. You can download it here

Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )

I removed C:\ProgramData\Oracle\Java\javapath from my path, and it worked for me.

But make sure you include x64 JDK and JRE addresses in your path.

Eclipse Bug: Unhandled event loop exception No more handles

I had the same problem and finally figured out, that it was the Logitech SetPoint Software.

Deinstalled it - and the error is gone.

Java Desktop application: SWT vs. Swing

Interesting question. I don't know SWT too well to brag about it (unlike Swing and AWT) but here's the comparison done on SWT/Swing/AWT.

http://www.developer.com/java/other/article.php/10936_2179061_2/Swing-and-SWT-A-Tale-of-Two-Java-GUI-Libraries.htm

And here's the site where you can get tutorial on basically anything on SWT (http://www.java2s.com/Tutorial/Java/0280__SWT/Catalog0280__SWT.htm)

Hope you make a right decision (if there are right decisions in coding)... :-)

Java GUI frameworks. What to choose? Swing, SWT, AWT, SwingX, JGoodies, JavaFX, Apache Pivot?

Swing + SwingX + Miglayout is my combination of choice. Miglayout is so much simpler than Swings perceived 200 different layout managers and much more powerful. Also, it provides you with the ability to "debug" your layouts, which is especially handy when creating complex layouts.

pthread function from a class

The above answers are good, but in my case, 1st approach that converts the function to be a static didn't work. I was trying to convert exiting code to move into thread function but that code had lots to references to non-static class members already. The second solution of encapsulating into C++ object works, but has 3-level wrappers to run a thread.

I had an alternate solution that uses existing C++ construct - 'friend' function, and it worked perfect for my case. An example of how I used 'friend' (will use the above same example for names showing how it can be converted into a compact form using friend)

    class MyThreadClass
    {
    public:
       MyThreadClass() {/* empty */}
       virtual ~MyThreadClass() {/* empty */}

       bool Init()
       {
          return (pthread_create(&_thread, NULL, &ThreadEntryFunc, this) == 0);
       }

       /** Will not return until the internal thread has exited. */
       void WaitForThreadToExit()
       {
          (void) pthread_join(_thread, NULL);
       }

    private:
       //our friend function that runs the thread task
       friend void* ThreadEntryFunc(void *);

       pthread_t _thread;
    };

    //friend is defined outside of class and without any qualifiers
    void* ThreadEntryFunc(void *obj_param) {
    MyThreadClass *thr  = ((MyThreadClass *)obj_param); 

    //access all the members using thr->

    return NULL;
    }

Ofcourse, we can use boost::thread and avoid all these, but I was trying to modify the C++ code to not use boost (the code was linking against boost just for this purpose)

Center/Set Zoom of Map to cover all visible Markers?

There is this MarkerClusterer client side utility available for google Map as specified here on Google Map developer Articles, here is brief on what's it's usage:

There are many approaches for doing what you asked for:

  • Grid based clustering
  • Distance based clustering
  • Viewport Marker Management
  • Fusion Tables
  • Marker Clusterer
  • MarkerManager

You can read about them on the provided link above.

Marker Clusterer uses Grid Based Clustering to cluster all the marker wishing the grid. Grid-based clustering works by dividing the map into squares of a certain size (the size changes at each zoom) and then grouping the markers into each grid square.

Before Clustering Before Clustering

After Clustering After Clustering

I hope this is what you were looking for & this will solve your problem :)

What is the difference between parseInt(string) and Number(string) in JavaScript?

parseInt("123qwe")

returns 123

Number("123qwe")

returns NaN

In other words parseInt() parses up to the first non-digit and returns whatever it had parsed. Number() wants to convert the entire string into a number, which can also be a float BTW.


EDIT #1: Lucero commented about the radix that can be used along with parseInt(). As far as that is concerned, please see THE DOCTOR's answer below (I'm not going to copy that here, the doc shall have a fair share of the fame...).


EDIT #2: Regarding use cases: That's somewhat written between the lines already. Use Number() in cases where you indirectly want to check if the given string completely represents a numeric value, float or integer. parseInt()/parseFloat() aren't that strict as they just parse along and stop when the numeric value stops (radix!), which makes it useful when you need a numeric value at the front "in case there is one" (note that parseInt("hui") also returns NaN). And the biggest difference is the use of radix that Number() doesn't know of and parseInt() may indirectly guess from the given string (that can cause weird results sometimes).

java.net.MalformedURLException: no protocol

Try instead of db.parse(xml):

Document doc = db.parse(new InputSource(new StringReader(**xml**)));

Hidden Features of Xcode

Xcode code formatting... is one of the thing you need when you want to make your code readable and look good.

You can do the code formatting by yourself or save some time using scripts.

One good way is.. use Uncrustify. It is explained in Code Formatting in Xcode.

Python not working in the command line of git bash

I am using MINGW64 via Visual Studio Code on Windows 10 and trying to install node-sass (which requires python2). I followed felixrieseberg/windows-build-tools #56 on Github which solved my issue.

This is a special case, but I'm posting in case someone has the same problem:

npm --add-python-to-path='true' --debug install --global windows-build-tools

This installs python and other required build tools to %USERPROFILE%\.windows-build-tools\python27.

IIS Manager in Windows 10

after turning IIS on (by going to Windows Features On/Off) type inetmgr in search bar or run

Open youtube video in Fancybox jquery

This has a regular expression so it's easier to just copy and paste the youtube url. Is great for when you use a CMS for clients.

/*fancybox yt video*/
$(".fancybox-video").click(function() {
    $.fancybox({

    padding: 0,
        'autoScale'     : false,
        'transitionIn'  : 'none',
        'transitionOut' : 'none',
        'title'         : this.title,
        'width'         : 795,
        'height'        : 447,
        'href'          : this.href.replace(new RegExp("watch.*v=","i"), "v/"),
        'type'          : 'swf',
        'swf'           : {
        'wmode'             : 'transparent',
        'allowfullscreen'   : 'true'
         }

    });
    return false;
});

Parse XLSX with Node and create json

**podria ser algo asi en react y electron**

 xslToJson = workbook => {
        //var data = [];
        var sheet_name_list = workbook.SheetNames[0];
        return XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list], {
            raw: false,
            dateNF: "DD-MMM-YYYY",
            header:1,
            defval: ""
        });
    };

    handleFile = (file /*:File*/) => {
        /* Boilerplate to set up FileReader */
        const reader = new FileReader();
        const rABS = !!reader.readAsBinaryString;

        reader.onload = e => {
            /* Parse data */
            const bstr = e.target.result;
            const wb = XLSX.read(bstr, { type: rABS ? "binary" : "array" });
            /* Get first worksheet */
            let arr = this.xslToJson(wb);

            console.log("arr ", arr)
            var dataNueva = []

            arr.forEach(data => {
                console.log("data renaes ", data)
            })
            // this.setState({ DataEESSsend: dataNueva })
            console.log("dataNueva ", dataNueva)

        };


        if (rABS) reader.readAsBinaryString(file);
        else reader.readAsArrayBuffer(file);
    };

    handleChange = e => {
        const files = e.target.files;
        if (files && files[0]) {
            this.handleFile(files[0]);
        }
    };

Can an AJAX response set a cookie?

Yes, you can set cookie in the AJAX request in the server-side code just as you'd do for a normal request since the server cannot differentiate between a normal request or an AJAX request.

AJAX requests are just a special way of requesting to server, the server will need to respond back as in any HTTP request. In the response of the request you can add cookies.

How to obfuscate Python code effectively?

I'll write my answer in a didactic manner...

First type into your Python interpreter:

import this

then, go and take a look to the file this.py in your Lib directory within your Python distribution and try to understand what it does.

After that, take a look to the eval function in the documentation:

help(eval)

Now you should have found a funny way to protect your code. But beware, because that only works for people that are less intelligent than you! (and I'm not trying to be offensive, anyone smart enough to understand what you did could reverse it).

Android ListView Selector Color

The list selector drawable is a StateListDrawable — it contains reference to multiple drawables for each state the list can be, like selected, focused, pressed, disabled...

While you can retrieve the drawable using getSelector(), I don't believe you can retrieve a specific Drawable from a StateListDrawable, nor does it seem possible to programmatically retrieve the colour directly from a ColorDrawable anyway.

As for setting the colour, you need a StateListDrawable as described above. You can set this on your list using the android:listSelector attribute, defining the drawable in XML like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_enabled="false" android:state_focused="true"
        android:drawable="@drawable/item_disabled" />
  <item android:state_pressed="true"
        android:drawable="@drawable/item_pressed" />
  <item android:state_focused="true"
        android:drawable="@drawable/item_focused" />
</selector>

How can I roll back my last delete command in MySQL?

A "rollback" only works if you used transactions. That way you can group queries together and undo all queries if only one of them fails.

But if you already committed the transaction (or used a regular DELETE-query), the only way of getting your data back is to recover it from a previously made backup.

Sort matrix according to first column in R

Read the data:

foo <- read.table(text="1 349
  1 393
  1 392
  4 459
  3 49
  3 32
  2 94")

And sort:

foo[order(foo$V1),]

This relies on the fact that order keeps ties in their original order. See ?order.

Showing line numbers in IPython/Jupyter Notebooks

1.press esc to enter the command mode 2.perss l(it L in lowcase) to show the line number

Get current time in hours and minutes

you can use command

date | awk '{print $4}'| cut -d ':' -f3

as you mentioned using only the date|awk '{print $4}' pipeline gives you something like this

20:18:19

so as we can see if we want to extract some part of this string then we need a delimiter , for our case it is :, so we decide to chop on the basis of :. Now this delimiter will chop the string into three parts i.e. 20 ,18 and 19 , as we want the second one we use -f2 in our command. to sum up ,

cut : chops some string based on delimeter.

-d : delimeter (here :)

-f2 : the chopped off token that we want.

Fastest JavaScript summation

For your specific case, just use the reduce method of Arrays:

var sumArray = function() {
    // Use one adding function rather than create a new one each
    // time sumArray is called
    function add(a, b) {
        return a + b;
    }

    return function(arr) {
        return arr.reduce(add);
    };
}();

alert( sumArray([2, 3, 4]) );

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

You're talking about histograms, but this doesn't quite make sense. Histograms and bar charts are different things. An histogram would be a bar chart representing the sum of values per year, for example. Here, you just seem to be after bars.

Here is a complete example from your data that shows a bar of for each required value at each date:

import pylab as pl
import datetime

data = """0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014"""

values = []
dates = []

for line in data.split("\n"):
    x, y = line.split()
    values.append(int(x))
    dates.append(datetime.datetime.strptime(y, "%d-%m-%Y").date())

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(dates, values, width=100)
ax.xaxis_date()

You need to parse the date with strptime and set the x-axis to use dates (as described in this answer).

If you're not interested in having the x-axis show a linear time scale, but just want bars with labels, you can do this instead:

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(range(len(dates)), values)

EDIT: Following comments, for all the ticks, and for them to be centred, pass the range to set_ticks (and move them by half the bar width):

fig = pl.figure()
ax = pl.subplot(111)
width=0.8
ax.bar(range(len(dates)), values, width=width)
ax.set_xticks(np.arange(len(dates)) + width/2)
ax.set_xticklabels(dates, rotation=90)

PHP PDO: charset, set names?

For completeness, there're actually three ways to set the encoding when connecting to MySQL from PDO and which ones are available depend on your PHP version. The order of preference would be:

  1. charset parameter in the DSN string
  2. Run SET NAMES utf8 with PDO::MYSQL_ATTR_INIT_COMMAND connection option
  3. Run SET NAMES utf8 manually

This sample code implements all three:

<?php

define('DB_HOST', 'localhost');
define('DB_SCHEMA', 'test');
define('DB_USER', 'test');
define('DB_PASSWORD', 'test');
define('DB_ENCODING', 'utf8');


$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_SCHEMA;
$options = array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
);

if( version_compare(PHP_VERSION, '5.3.6', '<') ){
    if( defined('PDO::MYSQL_ATTR_INIT_COMMAND') ){
        $options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . DB_ENCODING;
    }
}else{
    $dsn .= ';charset=' . DB_ENCODING;
}

$conn = @new PDO($dsn, DB_USER, DB_PASSWORD, $options);

if( version_compare(PHP_VERSION, '5.3.6', '<') && !defined('PDO::MYSQL_ATTR_INIT_COMMAND') ){
    $sql = 'SET NAMES ' . DB_ENCODING;
    $conn->exec($sql);
}

Doing all three is probably overkill (unless you're writing a class you plan to distribute or reuse).

Java split string to array

Try this

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

How can I check if PostgreSQL is installed or not via Linux script?

We can simply write:

psql --version

output show like:

psql (PostgreSQL) 11.5 (Ubuntu 11.5-1.pgdg18.04+1)

What is the backslash character (\\)?

The \ on it's own is used to escape special characters, such as \n (new line), \t (tabulation), \" (quotes) when typing these specific values in a System.out.println() statement.

Thus, if you want to print a backslash, \, you can't have it on it's own since the compiler will be expecting a special character (such as the ones above). Thus, to print a backslash you need to escape it, since itself is also one of these special characters, thus, \\ yields \.

How to alter SQL in "Edit Top 200 Rows" in SSMS 2008

Similar to David Hall's response, if you are a non-coder, it may be easiest to right-click within results, then choose Pane > Criteria. This allows you to adjust sort, add filters, etc... without adjusting SQL code.

Equivalent of jQuery .hide() to set visibility: hidden

An even simpler way to do this is to use jQuery's toggleClass() method

CSS

.newClass{visibility: hidden}

HTML

<a href="#" class=trigger>Trigger Element </a>
<div class="hidden_element">Some Content</div>

JS

$(document).ready(function(){
    $(".trigger").click(function(){
        $(".hidden_element").toggleClass("newClass");
    });
});

Django request get parameters

You may also use:

request.POST.get('section','') # => [39]
request.POST.get('MAINS','') # => [137] 
request.GET.get('section','') # => [39]
request.GET.get('MAINS','') # => [137]

Using this ensures that you don't get an error. If the POST/GET data with any key is not defined then instead of raising an exception the fallback value (second argument of .get() will be used).

How to test that no exception is thrown?

This may not be the best way but it definitely makes sure that exception is not thrown from the code block that is being tested.

import org.assertj.core.api.Assertions;
import org.junit.Test;

public class AssertionExample {

    @Test
    public void testNoException(){
        assertNoException();
    }    

    private void assertException(){
        Assertions.assertThatThrownBy(this::doNotThrowException).isInstanceOf(Exception.class);
    }

    private void assertNoException(){
        Assertions.assertThatThrownBy(() -> assertException()).isInstanceOf(AssertionError.class);
    }

    private void doNotThrowException(){
        //This method will never throw exception
    }
}

How to reference Microsoft.Office.Interop.Excel dll?

Use NuGet (VS 2013+):

The easiest way in any recent version of Visual Studio is to just use the NuGet package manager. (Even VS2013, with the NuGet Package Manager for Visual Studio 2013 extension.)

Right-click on "References" and choose "Manage NuGet Packages...", then just search for Excel.

enter image description here


VS 2012:

Older versions of VS didn't have access to NuGet.

  • Right-click on "References" and select "Add Reference".
  • Select "Extensions" on the left.
  • Look for Microsoft.Office.Interop.Excel.
    (Note that you can just type "excel" into the search box in the upper-right corner.)

VS2012/2013 References


VS 2008 / 2010:

  • Right-click on "References" and select "Add Reference".
  • Select the ".NET" tab.
  • Look for Microsoft.Office.Interop.Excel.

VS 2010 References

Reset IntelliJ UI to Default

On Mac OS for IntelliJ v12, shut down the IDE, and then you can execute:

rm -rf ~/Library/Preferences/IdeaIC12/*

Restart the IDE, or open a pom.xml of your choosing. You will be asked whether you want to import the preferences from an existing IntelliJ instance. Select the "No, I do not have a previous IntelliJ version" radio button.

Why is setTimeout(fn, 0) sometimes useful?

Preface:

Some of the other answers are correct but don't actually illustrate what the problem being solved is, so I created this answer to present that detailed illustration.

As such, I am posting a detailed walk-through of what the browser does and how using setTimeout() helps. It looks longish but is actually very simple and straightforward - I just made it very detailed.

UPDATE: I have made a JSFiddle to live-demonstrate the explanation below: http://jsfiddle.net/C2YBE/31/ . Many thanks to @ThangChung for helping to kickstart it.

UPDATE2: Just in case JSFiddle web site dies, or deletes the code, I added the code to this answer at the very end.


DETAILS:

Imagine a web app with a "do something" button and a result div.

The onClick handler for "do something" button calls a function "LongCalc()", which does 2 things:

  1. Makes a very long calculation (say takes 3 min)

  2. Prints the results of calculation into the result div.

Now, your users start testing this, click "do something" button, and the page sits there doing seemingly nothing for 3 minutes, they get restless, click the button again, wait 1 min, nothing happens, click button again...

The problem is obvious - you want a "Status" DIV, which shows what's going on. Let's see how that works.


So you add a "Status" DIV (initially empty), and modify the onclick handler (function LongCalc()) to do 4 things:

  1. Populate the status "Calculating... may take ~3 minutes" into status DIV

  2. Makes a very long calculation (say takes 3 min)

  3. Prints the results of calculation into the result div.

  4. Populate the status "Calculation done" into status DIV

And, you happily give the app to users to re-test.

They come back to you looking very angry. And explain that when they clicked the button, the Status DIV never got updated with "Calculating..." status!!!


You scratch your head, ask around on StackOverflow (or read docs or google), and realize the problem:

The browser places all its "TODO" tasks (both UI tasks and JavaScript commands) resulting from events into a single queue. And unfortunately, re-drawing the "Status" DIV with the new "Calculating..." value is a separate TODO which goes to the end of the queue!

Here's a breakdown of the events during your user's test, contents of the queue after each event:

  • Queue: [Empty]
  • Event: Click the button. Queue after event: [Execute OnClick handler(lines 1-4)]
  • Event: Execute first line in OnClick handler (e.g. change Status DIV value). Queue after event: [Execute OnClick handler(lines 2-4), re-draw Status DIV with new "Calculating" value]. Please note that while the DOM changes happen instantaneously, to re-draw the corresponding DOM element you need a new event, triggered by the DOM change, that went at the end of the queue.
  • PROBLEM!!! PROBLEM!!! Details explained below.
  • Event: Execute second line in handler (calculation). Queue after: [Execute OnClick handler(lines 3-4), re-draw Status DIV with "Calculating" value].
  • Event: Execute 3rd line in handler (populate result DIV). Queue after: [Execute OnClick handler(line 4), re-draw Status DIV with "Calculating" value, re-draw result DIV with result].
  • Event: Execute 4th line in handler (populate status DIV with "DONE"). Queue: [Execute OnClick handler, re-draw Status DIV with "Calculating" value, re-draw result DIV with result; re-draw Status DIV with "DONE" value].
  • Event: execute implied return from onclick handler sub. We take the "Execute OnClick handler" off the queue and start executing next item on the queue.
  • NOTE: Since we already finished the calculation, 3 minutes already passed for the user. The re-draw event didn't happen yet!!!
  • Event: re-draw Status DIV with "Calculating" value. We do the re-draw and take that off the queue.
  • Event: re-draw Result DIV with result value. We do the re-draw and take that off the queue.
  • Event: re-draw Status DIV with "Done" value. We do the re-draw and take that off the queue. Sharp-eyed viewers might even notice "Status DIV with "Calculating" value flashing for fraction of a microsecond - AFTER THE CALCULATION FINISHED

So, the underlying problem is that the re-draw event for "Status" DIV is placed on the queue at the end, AFTER the "execute line 2" event which takes 3 minutes, so the actual re-draw doesn't happen until AFTER the calculation is done.


To the rescue comes the setTimeout(). How does it help? Because by calling long-executing code via setTimeout, you actually create 2 events: setTimeout execution itself, and (due to 0 timeout), separate queue entry for the code being executed.

So, to fix your problem, you modify your onClick handler to be TWO statements (in a new function or just a block within onClick):

  1. Populate the status "Calculating... may take ~3 minutes" into status DIV

  2. Execute setTimeout() with 0 timeout and a call to LongCalc() function.

    LongCalc() function is almost the same as last time but obviously doesn't have "Calculating..." status DIV update as first step; and instead starts the calculation right away.

So, what does the event sequence and the queue look like now?

  • Queue: [Empty]
  • Event: Click the button. Queue after event: [Execute OnClick handler(status update, setTimeout() call)]
  • Event: Execute first line in OnClick handler (e.g. change Status DIV value). Queue after event: [Execute OnClick handler(which is a setTimeout call), re-draw Status DIV with new "Calculating" value].
  • Event: Execute second line in handler (setTimeout call). Queue after: [re-draw Status DIV with "Calculating" value]. The queue has nothing new in it for 0 more seconds.
  • Event: Alarm from the timeout goes off, 0 seconds later. Queue after: [re-draw Status DIV with "Calculating" value, execute LongCalc (lines 1-3)].
  • Event: re-draw Status DIV with "Calculating" value. Queue after: [execute LongCalc (lines 1-3)]. Please note that this re-draw event might actually happen BEFORE the alarm goes off, which works just as well.
  • ...

Hooray! The Status DIV just got updated to "Calculating..." before the calculation started!!!



Below is the sample code from the JSFiddle illustrating these examples: http://jsfiddle.net/C2YBE/31/ :

HTML code:

<table border=1>
    <tr><td><button id='do'>Do long calc - bad status!</button></td>
        <td><div id='status'>Not Calculating yet.</div></td>
    </tr>
    <tr><td><button id='do_ok'>Do long calc - good status!</button></td>
        <td><div id='status_ok'>Not Calculating yet.</div></td>
    </tr>
</table>

JavaScript code: (Executed on onDomReady and may require jQuery 1.9)

function long_running(status_div) {

    var result = 0;
    // Use 1000/700/300 limits in Chrome, 
    //    300/100/100 in IE8, 
    //    1000/500/200 in FireFox
    // I have no idea why identical runtimes fail on diff browsers.
    for (var i = 0; i < 1000; i++) {
        for (var j = 0; j < 700; j++) {
            for (var k = 0; k < 300; k++) {
                result = result + i + j + k;
            }
        }
    }
    $(status_div).text('calculation done');
}

// Assign events to buttons
$('#do').on('click', function () {
    $('#status').text('calculating....');
    long_running('#status');
});

$('#do_ok').on('click', function () {
    $('#status_ok').text('calculating....');
    // This works on IE8. Works in Chrome
    // Does NOT work in FireFox 25 with timeout =0 or =1
    // DOES work in FF if you change timeout from 0 to 500
    window.setTimeout(function (){ long_running('#status_ok') }, 0);
});

Strip off URL parameter with PHP

Wow, there are a lot of examples here. I am providing one that does some error handling. It rebuilds and returns the entire URL with the query-string-param-to-be-removed, removed. It also provides a bonus function that builds the current URL on the fly. Tested, works!

Credit to Mark B for the steps. This is a complete solution to tpow's "strip off this return parameter" original question -- might be handy for beginners, trying to avoid PHP gotchas. :-)

<?php

function currenturl_without_queryparam( $queryparamkey ) {
    $current_url = current_url();
    $parsed_url = parse_url( $current_url );
    if( array_key_exists( 'query', $parsed_url )) {
        $query_portion = $parsed_url['query'];
    } else {
        return $current_url;
    }

    parse_str( $query_portion, $query_array );

    if( array_key_exists( $queryparamkey , $query_array ) ) {
        unset( $query_array[$queryparamkey] );
        $q = ( count( $query_array ) === 0 ) ? '' : '?';
        return $parsed_url['scheme'] . '://' . $parsed_url['host'] . $parsed_url['path'] . $q . http_build_query( $query_array );
    } else {
        return $current_url;
    }
}

function current_url() {
    $current_url = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
    return $current_url;
}

echo currenturl_without_queryparam( 'key' );

?>

How to count instances of character in SQL Column

Below solution help to find out no of character present from a string with a limitation:

1) using SELECT LEN(REPLACE(myColumn, 'N', '')), but limitation and wrong output in below condition:

SELECT LEN(REPLACE('YYNYNYYNNNYYNY', 'N', ''));
--8 --Correct

SELECT LEN(REPLACE('123a123a12', 'a', ''));
--8 --Wrong

SELECT LEN(REPLACE('123a123a12', '1', ''));
--7 --Wrong

2) Try with below solution for correct output:

  • Create a function and also modify as per requirement.
  • And call function as per below

select dbo.vj_count_char_from_string('123a123a12','2');
--2 --Correct

select dbo.vj_count_char_from_string('123a123a12','a');
--2 --Correct

-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      VIKRAM JAIN
-- Create date: 20 MARCH 2019
-- Description: Count char from string
-- =============================================
create FUNCTION vj_count_char_from_string
(
    @string nvarchar(500),
    @find_char char(1)  
)
RETURNS integer
AS
BEGIN
    -- Declare the return variable here
    DECLARE @total_char int; DECLARE @position INT;
    SET @total_char=0; set @position = 1;

    -- Add the T-SQL statements to compute the return value here
    if LEN(@string)>0
    BEGIN
        WHILE @position <= LEN(@string) -1
        BEGIN
            if SUBSTRING(@string, @position, 1) = @find_char
            BEGIN
                SET @total_char+= 1;
            END
            SET @position+= 1;
        END
    END;

    -- Return the result of the function
    RETURN @total_char;

END
GO

How to convert / cast long to String?

See the reference documentation for the String class: String s = String.valueOf(date);

If your Long might be null and you don't want to get a 4-letter "null" string, you might use Objects.toString, like: String s = Objects.toString(date, null);


EDIT:

You reverse it using Long l = Long.valueOf(s); but in this direction you need to catch NumberFormatException

Go: panic: runtime error: invalid memory address or nil pointer dereference

for me one solution for this problem was to add in sql.Open ... sslmode=disable

JavaScript/jQuery: replace part of string?

It should be like this

$(this).text($(this).text().replace('N/A, ', ''))

How to find GCD, LCM on a set of numbers

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n0 = input.nextInt(); // number of intended input.
        int [] MyList = new int [n0];

        for (int i = 0; i < n0; i++)
            MyList[i] = input.nextInt();
            //input values stored in an array
        int i = 0;
        int count = 0;
            int gcd = 1; // Initial gcd is 1
            int k = 2; // Possible gcd
            while (k <= MyList[i] && k <= MyList[i]) {
                if (MyList[i] % k == 0 && MyList[i] % k == 0)
                    gcd = k; // Update gcd
                k++;
                count++; //checking array for gcd
            }
           // int i = 0;
            MyList [i] = gcd;
            for (int e: MyList) {
                System.out.println(e);

            }

            }

        }

Input placeholders for Internet Explorer

I created my own jQuery plugin after becoming frustrated that the existing shims would hide the placeholder on focus, which creates an inferior user experience and also does not match how Firefox, Chrome and Safari handle it. This is especially the case if you want an input to be focused when a page or popup first loads, while still showing the placeholder until text is entered.

https://github.com/nspady/jquery-placeholder-labels/

How do I get the value of text input field using JavaScript?

simple js

function copytext(text) {
    var textField = document.createElement('textarea');
    textField.innerText = text;
    document.body.appendChild(textField);
    textField.select();
    document.execCommand('copy');
    textField.remove();
}

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

jQuery ajax success callback function definition

I do not know why you are defining the parameter outside the script. That is unnecessary. Your callback function will be called with the return data as a parameter automatically. It is very possible to define your callback outside the sucess: i.e.

function getData() {
    $.ajax({
        url : 'example.com',
        type: 'GET',
        success : handleData
    })
}

function handleData(data) {
    alert(data);
    //do some stuff
}

the handleData function will be called and the parameter passed to it by the ajax function.

HttpContext.Current.Request.Url.Host what it returns?

The Host property will return the domain name you used when accessing the site. So, in your development environment, since you're requesting

http://localhost:950/m/pages/Searchresults.aspx?search=knife&filter=kitchen

It's returning localhost. You can break apart your URL like so:

Protocol: http
Host: localhost
Port: 950
PathAndQuery: /m/pages/SearchResults.aspx?search=knight&filter=kitchen

Error: unable to verify the first certificate in nodejs

Try adding the appropriate root certificate

This is always going to be a much safer option than just blindly accepting unauthorised end points, which should in turn only be used as a last resort.

This can be as simple as adding

require('https').globalAgent.options.ca = require('ssl-root-cas/latest').create();

to your application.

The SSL Root CAs npm package (as used here) is a very useful package regarding this problem.

How to update two tables in one statement in SQL Server 2005?

This works for MySQL and is really just an implicit transaction but it should go something like this:

UPDATE Table1 t1, Table2 t2 SET 
t2.field = t2.field+2,
t1.field = t1.field+2

WHERE t1.id = t2.foreign_id and t2.id = '123414'

if you are doing updates to multi tables that require multi statements… which is likely possible if you update one, then another based on other conditions… you should use a transaction. 

Check if a string is palindrome

Note that reversing the whole string (either with the rbegin()/rend() range constructor or with std::reverse) and comparing it with the input would perform unnecessary work.

It's sufficient to compare the first half of the string with the latter half, in reverse:

#include <string>
#include <algorithm>
#include <iostream>
int main()
{
    std::string s;
    std::cin >> s;
    if( equal(s.begin(), s.begin() + s.size()/2, s.rbegin()) )
        std::cout << "is a palindrome.\n";
    else
        std::cout << "is NOT a palindrome.\n";
}

demo: http://ideone.com/mq8qK

How to get the process ID to kill a nohup process?

jobs -l should give you the pid for the list of nohup processes. kill (-9) them gently. ;)

Reverse Y-Axis in PyPlot

You could also use function exposed by the axes object of the scatter plot

scatter = plt.scatter(x, y)
ax = scatter.axes
ax.invert_xaxis()
ax.invert_yaxis()

Best practices with STDIN in Ruby?

I'll add that in order to use ARGF with parameters, you need to clear ARGV before calling ARGF.each. This is because ARGF will treat anything in ARGV as a filename and read lines from there first.

Here's an example 'tee' implementation:

File.open(ARGV[0], 'w') do |file|
  ARGV.clear

  ARGF.each do |line|
    puts line
    file.write(line)
  end
end

Postgres FOR LOOP

Below is example you can use:

create temp table test2 (
  id1  numeric,
  id2  numeric,
  id3  numeric,
  id4  numeric,
  id5  numeric,
  id6  numeric,
  id7  numeric,
  id8  numeric,
  id9  numeric,
  id10 numeric) 
with (oids = false);

do
$do$
declare
     i int;
begin
for  i in 1..100000
loop
    insert into test2  values (random(), i * random(), i / random(), i + random(), i * random(), i / random(), i + random(), i * random(), i / random(), i + random());
end loop;
end;
$do$;

ERROR 2003 (HY000): Can't connect to MySQL server (111)

Sometimes when you have special characters in password you need to wrap it in '' characters, so to connect to db you could use:

mysql -uUSER -p'pa$$w0rd'

I had the same error and this solution solved it.

css display table cell requires percentage width

Note also that vertical-align:top; is often necessary for correct table cell appearance.

css table-cell, contents have unnecessary top margin

How to find whether a ResultSet is empty or not in Java?

Immediately after your execute statement you can have an if statement. For example

ResultSet rs = statement.execute();
if (!rs.next()){
//ResultSet is empty
}

Android Studio doesn't recognize my device

Click Revoke USB debugging authorization in Developer option and try it again.

How return error message in spring mvc @Controller

As Sotirios Delimanolis already pointed out in the comments, there are two options:

Return ResponseEntity with error message

Change your method like this:

@RequestMapping(method = RequestMethod.GET)
public ResponseEntity getUser(@RequestHeader(value="Access-key") String accessKey,
                              @RequestHeader(value="Secret-key") String secretKey) {
    try {
        // see note 1
        return ResponseEntity
            .status(HttpStatus.CREATED)                 
            .body(this.userService.chkCredentials(accessKey, secretKey, timestamp));
    }
    catch(ChekingCredentialsFailedException e) {
        e.printStackTrace(); // see note 2
        return ResponseEntity
            .status(HttpStatus.FORBIDDEN)
            .body("Error Message");
    }
}

Note 1: You don't have to use the ResponseEntity builder but I find it helps with keeping the code readable. It also helps remembering, which data a response for a specific HTTP status code should include. For example, a response with the status code 201 should contain a link to the newly created resource in the Location header (see Status Code Definitions). This is why Spring offers the convenient build method ResponseEntity.created(URI).

Note 2: Don't use printStackTrace(), use a logger instead.

Provide an @ExceptionHandler

Remove the try-catch block from your method and let it throw the exception. Then create another method in a class annotated with @ControllerAdvice like this:

@ControllerAdvice
public class ExceptionHandlerAdvice {

    @ExceptionHandler(ChekingCredentialsFailedException.class)
    public ResponseEntity handleException(ChekingCredentialsFailedException e) {
        // log exception
        return ResponseEntity
                .status(HttpStatus.FORBIDDEN)
                .body("Error Message");
    }        
}

Note that methods which are annotated with @ExceptionHandler are allowed to have very flexible signatures. See the Javadoc for details.

background: fixed no repeat not working on mobile

Thanks to the efforts of Vincent and work by Joey Hayes, I have this codepen working on android mobile that supports multiple fixed backgrounds

HTML:

<html>

<body>
  <nav>Nav to nowhere</nav>
  <article>

    <section class="bg-img bg-img1">
      <div class="content">
        <h1>Fixed backgrounds on a mobile browser</h1>
      </div>
    </section>

    <section class="solid">
      <h3>Scrolling Foreground Here</h3>
    </section>

    <section>
      <div class="content">
        <p>Quid securi etiam tamquam eu fugiat nulla pariatur. Cum ceteris in veneratione tui montes, nascetur mus. Quisque placerat facilisis egestas cillum dolore. Ambitioni dedisse scripsisse iudicaretur. Quisque ut dolor gravida, placerat libero vel,
          euismod.
        </p>
      </div>
    </section>

    <section class="solid">
      <h3>Scrolling Foreground Here</h3>
    </section>

    <section class="footer">
      <div class="content">
        <h3>The end is nigh.</h3>
      </div>
    </section>

  </article>
  </body>

CSS:

* {
  box-sizing: border-box;
}

body {
  font-family: "source sans pro";
  font-weight: 400;
  color: #fdfdfd;
}
body > section >.footer {
  overflow: hidden;
}

nav {
  position: fixed;
  top: 0;
  left: 0;
  height: 70px;
  width: 100%;
  background-color: silver;
  z-index: 999;
  text-align: center;
  font-size: 2em;
  opacity: 0.8;
}

article {
  position: relative;
  font-size: 1em;
}

section {
  height: 100vh;
  padding-top: 5em;
}

.bg-img::before {
  position: fixed;
  content: ' ';
  display: block;
  width: 100vw;
  min-height: 100vh;  
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background-position: center;
  background-size: cover;
  z-index: -10; 
}

.bg-img1:before {
      background-image: url('https://res.cloudinary.com/djhkdplck/image/upload/v1491326836/3balls_1280.jpg');
}
.bg-img2::before {
      background-image: url('https://res.cloudinary.com/djhkdplck/image/upload/v1491326840/icebubble-1280.jpg');
}
.bg-img3::before {
      background-image: url('https://res.cloudinary.com/djhkdplck/image/upload/v1491326844/soap-bubbles_1280.jpg');
}

h1, h2, h3 {
  font-family: lato;
  font-weight: 300;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.content {
  max-width: 50rem;
  margin: 0 auto;
}
.solid {
  min-height: 100vh;
  width: 100%;
  margin: auto;
  border: 1px solid white;
  background: rgba(255, 255, 255, 0.6);
}

.footer {
  background: rgba(2, 2, 2, 0.5);
}

JS/JQUERY

window.onload = function() {

  // Alternate Background Page with scrolling content (Bg Pages are odd#s)
  var $bgImg = $('.bg-img');
  var $nav = $('nav');
  var winh = window.innerHeight;
  var scrollPos = 0;
  var page = 1;
  var page1Bottom = winh;
  var page3Top = winh;
  var page3Bottom = winh * 3;
  var page5Top = winh * 3;
  var page5Bottom = winh * 5;

  $(window).on('scroll', function() {

    scrollPos = Number($(window).scrollTop().toFixed(2));
    page = Math.floor(Number(scrollPos / winh) +1);
    if (scrollPos >= 0 && scrollPos < page1Bottom ) {    
      if (! $bgImg.hasClass('bg-img1')) {

        removeBg( $bgImg, 2, 3, 1 ); // element, low, high, current
        $bgImg.addClass('bg-img1');
      }
    } else if (scrollPos >= page3Top && scrollPos <= page3Bottom) {
      if (! $bgImg.hasClass('bg-img2')) {

        removeBg( $bgImg, 1, 3, 2 ); // element, low, high, current
        $bgImg.addClass('bg-img2');
      }
    } else if (scrollPos >= page5Top && scrollPos <= page5Bottom) {
      if (! $bgImg.hasClass('bg-img3')) {

        removeBg( $bgImg, 1, 2, 3 ); // element, low, high, current
        $bgImg.addClass('bg-img3');
      }
    }
    $nav.html("Page# " + page + " window position: " + scrollPos);

  });
}

// This function was created to fix a problem where the mouse moves off the
// screen, this results in improper removal of background image class. Fix
// by removing any background class not applicable to current page.
function removeBg( el, low, high, current ) {
  if (low > high || low <= 0 || high <= 0) {
    console.log ("bad low/high parameters in removeBg");
  }
  for (var i=low; i<=high; i++) {
    if ( i != current ) { // avoid removing class we are trying to add
      if (el.hasClass('bg-img' +i )) {
        el.removeClass('bg-img' +i );
      }
    }
  } 
} // removeBg()

How to select a dropdown value in Selenium WebDriver using Java

WebDriver driver = new FirefoxDriver();
WebElement identifier = driver.findElement(By.id("periodId"));
Select select = new Select(identifier);
select.selectByVisibleText("Last 52 Weeks"); 

SVN icon overlays not showing properly

in my case, the tortoise icon not showing at all, I tried this and solved my problem :

  1. open registry
  2. HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\explorer\ShellIconOverlayIdentifiers
  3. delete all folder OneDrive
  4. delete all folder SkyDrive

(the point is to place all tortoise folder at top)

  1. open TaskManager and kill Explorer
  2. re run Explorer through TaskManager

In what cases will HTTP_REFERER be empty

BalusC's list is solid. One additional way this field frequently appears empty is when the user is behind a proxy server. This is similar to being behind a firewall but is slightly different so I wanted to mention it for the sake of completeness.

Javascript - Replace html using innerHTML

You are replacing the starting tag and then putting that back in innerHTML, so the code will be invalid. Make all the replacements before you put the code back in the element:

var html = strMessage1.innerHTML;
html = html.replace( /aaaaaa./g,'<a href=\"http://www.google.com/');
html = html.replace( /.bbbbbb/g,'/world\">Helloworld</a>');
strMessage1.innerHTML = html;

angular ng-repeat in reverse

Simple solution:- (no need to make any methods)

ng-repeat = "friend in friends | orderBy: reverse:true"

addClass and removeClass in jQuery - not removing class

I think that the problem is in the nesting of the elements. Once you attach an event to the outer element the clicks on the inner elements are actually firing the same click event for the outer element. So, you actually never go to the second state. What you can do is to check the clicked element. And if it is the close button then to avoid the class changing. Here is my solution:

var element = $(".clickable");
var closeButton = element.find(".close_button");
var onElementClick = function(e) {
    if(e.target !== closeButton[0]) {
        element.removeClass("spot").addClass("grown");
        element.off("click");
        closeButton.on("click", onCloseClick);
    }
}
var onCloseClick = function() {
    element.removeClass("grown").addClass("spot");
    closeButton.off("click");
    element.on("click", onElementClick);
}
element.on("click", onElementClick);

In addition I'm adding and removing event handlers.

JSFiddle -> http://jsfiddle.net/zmw9E/1/

Drawing rotated text on a HTML5 canvas

While this is sort of a follow up to the previous answer, it adds a little (hopefully).

Mainly what I want to clarify is that usually we think of drawing things like draw a rectangle at 10, 3.

So if we think about that like this: move origin to 10, 3, then draw rectangle at 0, 0. Then all we have to do is add a rotate in between.

Another big point is the alignment of the text. It's easiest to draw the text at 0, 0, so using the correct alignment can allow us to do that without measuring the text width.

We should still move the text by an amount to get it centered vertically, and unfortunately canvas does not have great line height support, so that's a guess and check thing ( correct me if there is something better ).

I've created 3 examples that provide a point and a text with 3 alignments, to show what the actual point on the screen is where the font will go.

enter image description here

var font, lineHeight, x, y;

x = 100;
y = 100;
font = 20;
lineHeight = 15; // this is guess and check as far as I know
this.context.font = font + 'px Arial';


// Right Aligned
this.context.save();
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);

this.context.textAlign = 'right';
this.context.fillText('right', 0, lineHeight / 2);

this.context.restore();

this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);


// Center
this.context.fillStyle = 'black';
x = 150;
y = 100;

this.context.save();
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);

this.context.textAlign = 'center';
this.context.fillText('center', 0, lineHeight / 2);

this.context.restore();

this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);


// Left
this.context.fillStyle = 'black';
x = 200;
y = 100;

this.context.save();
this.context.translate(x, y);
this.context.rotate(-Math.PI / 4);

this.context.textAlign = 'left';
this.context.fillText('left', 0, lineHeight / 2);

this.context.restore();

this.context.fillStyle = 'red';
this.context.fillRect(x, y, 2, 2);

The line this.context.fillText('right', 0, lineHeight / 2); is basically 0, 0, except we move slightly for the text to be centered near the point

How to append one file to another in Linux from the shell?

Another solution:

cat file1 | tee -a file2

tee has the benefit that you can append to as many files as you like, for example:

cat file1 | tee -a file2 file3 file3

will append the contents of file1 to file2, file3 and file4.

From the man page:

-a, --append
       append to the given FILEs, do not overwrite

Is Spring annotation @Controller same as @Service?

I already answered similar question on here Here is the Link

No both are different.

@Service annotation have use for other purpose and @Controller use for other. Actually Spring @Component, @Service, @Repository and @Controller annotations are used for automatic bean detection using classpath scan in Spring framework, but it doesn't ,mean that all functionalities are same. @Service: It indicates annotated class is a Service component in the business layer.

@Controller: Annotated class indicates that it is a controller components, and mainly used at presentation layer.

How to split a line into words separated by one or more spaces in bash?

More simple,

echo $line | sed 's/\s/\n/g'

\s --> whitespace character (space, tab, NL, FF, VT, CR). In many systems also valid [:space:]

\n --> new line

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

How do I delete files programmatically on Android?

first call the intent

Intent intenta = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intenta, 42);

then call the result

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case 42:
            if (resultCode == Activity.RESULT_OK) {
                Uri sdCardUri = data.getData();
                DocumentFile pickedDir = DocumentFile.fromTreeUri(this, sdCardUri);
                for (DocumentFile file : pickedDir.listFiles()) {
                    String pp = file.getName();
                    if(pp.equals("VLC.apk"))
                        file.delete();
                    String ppdf="";
                }
                File pathFile = new File(String.valueOf(sdCardUri));
                pathFile.delete();
            }
            break;
    }
}

SQL Server Regular expressions in T-SQL

How about the PATINDEX function?

The pattern matching in TSQL is not a complete regex library, but it gives you the basics.

(From Books Online)

Wildcard  Meaning  
% Any string of zero or more characters.

_ Any single character.

[ ] Any single character within the specified range 
    (for example, [a-f]) or set (for example, [abcdef]).

[^] Any single character not within the specified range 
    (for example, [^a - f]) or set (for example, [^abcdef]).

How do I convert a list into a string with spaces in Python?

"".join([i for i in my_list])

This should work just like you asked!

MS Access: how to compact current database in VBA

When the user exits the FE attempt to rename the backend MDB preferably with todays date in the name in yyyy-mm-dd format. Ensure you close all bound forms, including hidden forms, and reports before doing this. If you get an error message, oops, its busy so don't bother. If it is successful then compact it back.

See my Backup, do you trust the users or sysadmins? tips page for more info.

c++ custom compare function for std::sort()

std::pair already has the required comparison operators, which perform lexicographical comparisons using both elements of each pair. To use this, you just have to provide the comparison operators for types for types K and V.

Also bear in mind that std::sort requires a strict weak ordeing comparison, and <= does not satisfy that. You would need, for example, a less-than comparison < for K and V. With that in place, all you need is

std::vector<pair<K,V>> items; 
std::sort(items.begin(), items.end()); 

If you really need to provide your own comparison function, then you need something along the lines of

template <typename K, typename V>
bool comparePairs(const std::pair<K,V>& lhs, const std::pair<K,V>& rhs)
{
  return lhs.first < rhs.first;
}

How to return a class object by reference in C++?

You can only use

     Object& return_Object();

if the object returned has a greater scope than the function. For example, you can use it if you have a class where it is encapsulated. If you create an object in your function, use pointers. If you want to modify an existing object, pass it as an argument.

  class  MyClass{
      private:
        Object myObj;

      public:
         Object& return_Object() {
            return myObj;
         }

         Object* return_created_Object() {
            return new Object();
         }

         bool modify_Object( Object& obj) {
            //  obj = myObj; return true; both possible
            return obj.modifySomething() == true;
         }
   };

How to set time to 24 hour format in Calendar

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

public class MyClass {

    public static void main(String[] args) {


        Calendar cal = Calendar.getInstance();

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

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

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

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

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

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

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

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

    }

}

Android List View Drag and Drop sort

I recently stumbled upon this great Gist that gives a working implementation of a drag sort ListView, with no external dependencies needed.


Basically it consists on creating your custom Adapter extending ArrayAdapter as an inner class to the activity containing your ListView. On this adapter one then sets an onTouchListener to your List Items that will signal the start of the drag.

In that Gist they set the listener to a specific part of the layout of the List Item (the "handle" of the item), so one does not accidentally move it by pressing any part of it. Personally, I preferred to go with an onLongClickListener instead, but that is up to you to decide. Here an excerpt of that part:

public class MyArrayAdapter extends ArrayAdapter<String> {

    private ArrayList<String> mStrings = new ArrayList<String>();
    private LayoutInflater mInflater;
    private int mLayout;

    //constructor, clear, remove, add, insert...

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        View view = convertView;
        //inflate, etc...

        final String string = mStrings.get(position);
        holder.title.setText(string);

        // Here the listener is set specifically to the handle of the layout
        holder.handle.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    startDrag(string);
                    return true;
                }
                return false;
            }
        });

        // change color on dragging item and other things...         

        return view;
    }
}

This also involves adding an onTouchListener to the ListView, which checks if an item is being dragged, handles the swapping and invalidation, and stops the drag state. An excerpt of that part:

mListView.setOnTouchListener(new View.OnTouchListener() {
     @Override
     public boolean onTouch(View view, MotionEvent event) {
        if (!mSortable) { return false; }
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                break;
            }
            case MotionEvent.ACTION_MOVE: {
                // get positions
                int position = mListView.pointToPosition((int) event.getX(), 
                    (int) event.getY());
                if (position < 0) {
                    break;
                }
                // check if it's time to swap
                if (position != mPosition) {
                    mPosition = position;
                    mAdapter.remove(mDragString);
                    mAdapter.insert(mDragString, mPosition);
                }
                return true;
            }
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_OUTSIDE: {
                //stop drag state
                stopDrag();
                return true;
            }
        }
        return false;
    }
});

Finally, here is how the stopDrag and startDrag methods look like, which handle the enabling and disabling of the drag process:

public void startDrag(String string) {
    mPosition = -1;
    mSortable = true;
    mDragString = string;
    mAdapter.notifyDataSetChanged();
}

public void stopDrag() {
    mPosition = -1;
    mSortable = false;
    mDragString = null;
    mAdapter.notifyDataSetChanged();
}

Unable to get spring boot to automatically create database schema

Using the following two settings does work.

spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create

isPrime Function for Python Language

def is_prime(x):  
    if x < 2:  
        return False  
    for n in range(2, (x) - 1):  
        if x % n == 0:  
            return False  
    return True

Sys is undefined

In case none of the above works for you, and you happen to be overriding OnPreRenderComplete, make sure you call base.OnPreRenderComplete. My therapist is going to be happy to see me back

How to set app icon for Electron / Atom Shell App

win = new BrowserWindow({width: 1000, height: 1000,icon: __dirname + '/logo.png'}); //*.png or *.ico will also work 

in my case it worked !

Deactivate or remove the scrollbar on HTML

If you really need it...

html { overflow-y: hidden; }

How to turn on front flash light programmatically in Android?

Try this.

CameraManager camManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    String cameraId = null; // Usually front camera is at 0 position.
    try {
        cameraId = camManager.getCameraIdList()[0];
        camManager.setTorchMode(cameraId, true);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }

First Or Create

Previous answer is obsolete. It's possible to achieve in one step since Laravel 5.3, firstOrCreate now has second parameter values, which is being used for new record, but not for search

$user = User::firstOrCreate([
    'email' => '[email protected]'
], [
    'firstName' => 'Taylor',
    'lastName' => 'Otwell'
]);

rails simple_form - hidden field - create?

= f.input_field :title, as: :hidden, value: "some value"

Is also an option. Note, however, that it skips any wrapper defined for your form builder.

Detect application heap size in Android

Do you mean programatically, or just while you're developing and debugging? If the latter, you can see that info from the DDMS perspective in Eclipse. When your emulator (possibly even physical phone that is plugged in) is running, it will list the active processes in a window on the left. You can select it and there's an option to track the heap allocations.

Enum ToString with user friendly strings

Even cleaner summary:

using System;
using System.Reflection;

public class TextAttribute : Attribute
{
    public string Text;
    public TextAttribute(string text)
    {
        Text = text;
    }
}  

public static class EnumExtender
{
    public static string ToText(this Enum enumeration)
    {
        var memberInfo = enumeration.GetType().GetMember(enumeration.ToString());
        if (memberInfo.Length <= 0) return enumeration.ToString();

        var attributes = memberInfo[0].GetCustomAttributes(typeof(TextAttribute), false);
        return attributes.Length > 0 ? ((TextAttribute)attributes[0]).Text : enumeration.ToString();
    }
}

Same usage as underscore describes.

Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

Is your type really arbitrary? If you know it is just going to be a int float or string you could just do

 if val.dtype == float and np.isnan(val):

assuming it is wrapped in numpy , it will always have a dtype and only float and complex can be NaN

android fragment- How to save states of views in a fragment when another fragment is pushed on top of it

In fragment guide FragmentList example you can find:

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("curChoice", mCurCheckPosition);
}

Which you can use later like this:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if (savedInstanceState != null) {
        // Restore last state for checked position.
        mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
    }
}

I'm a beginner in Fragments but it seems like solution of your problem ;) OnActivityCreated is invoked after fragment returns from back stack.

How to use SQL Order By statement to sort results case insensitive?

You can also do ORDER BY TITLE COLLATE NOCASE.

Edit: If you need to specify ASC or DESC, add this after NOCASE like

ORDER BY TITLE COLLATE NOCASE ASC

or

ORDER BY TITLE COLLATE NOCASE DESC

deleting folder from java

I found this piece of code more understadable and working:

public static boolean deleteDir(File dir) {
    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    return dir.delete(); // The directory is empty now and can be deleted.
}

How to Convert Boolean to String

function ToStr($Val=null,$T=0){

    return is_string($Val)?"$Val"
    :
    (
        is_numeric($Val)?($T?"$Val":$Val)
        :
        (
            is_null($Val)?"NULL"
            :
            (
                is_bool($Val)?($Val?"TRUE":"FALSE")
                :
                (
                    is_array($Val)?@StrArr($Val,$T)
                    :
                    false
                )
            )
        )
    );

}
function StrArr($Arr,$T=0)
{
    $Str="";
    $i=-1;
    if(is_array($Arr))
    foreach($Arr AS $K => $V)
    $Str.=((++$i)?", ":null).(is_string($K)?"\"$K\"":$K)." => ".(is_string($V)?"\"$V\"":@ToStr($V,$T+1));
    return "array( ".($i?@ToStr($Arr):$Str)." )".($T?null:";");
}

$A = array(1,2,array('a'=>'b'),array('a','b','c'),true,false,ToStr(100));
echo StrArr($A); // OR ToStr($A) // OR ToStr(true) // OR StrArr(true)

ComboBox SelectedItem vs SelectedValue

This is a long-standing "feature" of the list controls in .NET in my experience. Personally, I would just bind to the on change of the SelectedValue property and write whatever additional code is necessary to workaround this "feature" (such as having two properties, binding to one for SelectedValue, and then, on the set of that property, updating the value from SelectedItem in your custom code).

Anyway, I hope that helps =D

How to create multiple output paths in Webpack config

I'm not sure if we have the same problem since webpack only support one output per configuration as of Jun 2016. I guess you already seen the issue on Github.

But I separate the output path by using the multi-compiler. (i.e. separating the configuration object of webpack.config.js).

var config = {
    // TODO: Add common Configuration
    module: {},
};

var fooConfig = Object.assign({}, config, {
    name: "a",
    entry: "./a/app",
    output: {
       path: "./a",
       filename: "bundle.js"
    },
});
var barConfig = Object.assign({}, config,{
    name: "b",
    entry: "./b/app",
    output: {
       path: "./b",
       filename: "bundle.js"
    },
});

// Return Array of Configurations
module.exports = [
    fooConfig, barConfig,       
];

If you have common configuration among them, you could use the extend library or Object.assign in ES6 or {...} spread operator in ES7.

How can I get the length of text entered in a textbox using jQuery?

Below mentioned code works perfectly fine for taking length of any characters entered in textbox.

$("#Texboxid").val().length;

What is Ad Hoc Query?

Ad hoc query is type of computer definition. Which means this query is specially design to obtain any information when it is only needed. Predefined. refer this https://www.youtube.com/watch?v=0c8JEKmVXhU

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

Avoid multiple place enabling CORS,Like WebApiCOnfig.cs, GrantResourceOwnerCredentials method in provider and Controller Header attribute etc. Below are the list which also cause the Access Control Allow Origin

  1. Web having truble in interacting with DB which you used.
  2. AWS Cloud If VPC of Web API and DB are different.

Below code is more then enough to fix the access control allow origin. //Make sure app.UseCors should be top of the code line of configuration.

   public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            //All other configurations
        }
    }

This slowed my problem.

Change color inside strings.xml

Use CDATA in the below way for formatting your text

<resources>
<string name="app_name">DemoShareActionButton</string>
<string name="intro_message">
    <b>
    <![CDATA[ This sample shows you how a provide a context-sensitive ShareActionProvider.
    ]]>
    </b>
    </string>

Just add any tag you want before the <![CDATA[ and you will get your proper output.

Convert string to ASCII value python

def stringToNumbers(ord(message)):
    return stringToNumbers
    stringToNumbers.append = (ord[0])
    stringToNumbers = ("morocco")

How to check if String value is Boolean type in Java?

return value.equals("false") || value.equals("true");

Eclipse CDT project built but "Launch Failed. Binary Not Found"

After trying everything here what worked for me was to grant execution permission to eclipse:

cd eclipse-installation-dir 
sudo chmod +x eclipse

Using Eclipse Luna on Ubuntu 12.04 LTS.

How to remove a package in sublime text 2

There are several answers, First IF you are using Package Control simply use Package Control's Remove Package command...

Ctrl+Shift+P

Package Control: Remove Package

If you installed the package manually, and are on a Windows machine...have no fear; Just modify the files manually.

First navigate to

C:\users\[Name]\AppData\Roaming\Sublime Text [version]\

There will be 4 directories:

  1. Installed Packages (Holds the Package Control config file, ignore)
  2. Packages (Holds Package source)
  3. Pristine Packages (Holds the versioning info, ignore)
  4. Settings (Sublime Setting Info, ignore)

First open ..\Packages folder and locate the folder named the same as your package; Delete it.

Secondly, open Sublime and navigate to the Preferences > Package Settings > Package Control > Settings-user

Third, locate the line where the package name you want to "uninstall"

{
    "installed_packages":
    [
        "Alignment",
        "All Autocomplete",
        "AngularJS",
        "AutoFileName",
        "BracketHighlighter",
        "Browser Support",
        "Case Conversion",
        "ColorPicker",
        "Emmet",
        "FileDiffs",
        "Format SQL",
        "Git",
        "Github Tools",
        "HTML-CSS-JS Prettify",
        "HTML5",
        "HTMLBeautify",
        "jQuery",
        "JsFormat",
        "JSHint",
        "JsMinifier",
        "LiveReload",
        "LoremIpsum",
        "LoremPixel",
        "Oracle PL SQL",
        "Package Control",
        "Placehold.it Image Tag Generator",
        "Placeholders",
        "Prefixr",
        "Search Stack Overflow",
        "SublimeAStyleFormatter",
        "SublimeCodeIntel",
        "Tag",
        "Theme - Centurion",
        "TortoiseSVN",
        "Zen Tabs"
    ]
}

NOTE Say the package you are removing is "Zen Tabs", you MUST also remove the , after "TortoiseSVN" or it will error.

Thus concludes the easiest way to remove or Install a Sublime Text Package.

How can I resize an image using Java?

You don't need a library to do this. You can do it with Java itself.

Chris Campbell has an excellent and detailed write-up on scaling images - see this article.

Chet Haase and Romain Guy also have a detailed and very informative write-up of image scaling in their book, Filthy Rich Clients.

How to set div width using ng-style

ngStyle accepts a map:

$scope.myStyle = {
    "width" : "900px",
    "background" : "red"
};

Fiddle

List Highest Correlation Pairs from a Large Correlation Matrix in Pandas?

Lot's of good answers here. The easiest way I found was a combination of some of the answers above.

corr = corr.where(np.triu(np.ones(corr.shape), k=1).astype(np.bool))
corr = corr.unstack().transpose()\
    .sort_values(by='column', ascending=False)\
    .dropna()

How to get previous month and year relative to today, using strtotime and date?

function getOnemonthBefore($date){
    $day = intval(date("t", strtotime("$date")));//get the last day of the month
    $month_date = date("y-m-d",strtotime("$date -$day days"));//get the day 1 month before
    return $month_date;
}

The resulting date is dependent to the number of days the input month is consist of. If input month is february (28 days), 28 days before february 5 is january 8. If input is may 17, 31 days before is april 16. Likewise, if input is may 31, resulting date will be april 30.

NOTE: the input takes complete date ('y-m-d') and outputs ('y-m-d') you can modify this code to suit your needs.

How do I format my oracle queries so the columns don't wrap?

set WRAP OFF
set PAGESIZE 0

Try using those settings.

How a thread should close itself in Java?

If you're at the top level - or able to cleanly get to the top level - of the thread, then just returning is nice. Throwing an exception isn't as clean, as you need to be able to check that nothing's going to catch the exception and ignore it.

The reason you need to use Thread.currentThread() in order to call interrupt() is that interrupt() is an instance method - you need to call it on the thread you want to interrupt, which in your case happens to be the current thread. Note that the interruption will only be noticed the next time the thread would block (e.g. for IO or for a monitor) anyway - it doesn't mean the exception is thrown immediately.

How to Set focus to first text input in a bootstrap modal after shown

The usual code (below) does not work for me:

$('#myModal').on('shown.bs.modal', function () {
  $('#myInput').focus()
})

I found the solution:

$('body').on('shown.bs.modal', '#myModal', function () {
    $('input:visible:enabled:first', this).focus();
})

Combining a class selector and an attribute selector with jQuery

This code works too:

$("input[reference=12345].myclass").css('border', '#000 solid 1px');

What does "&" at the end of a linux command mean?

I don’t know for sure but I’m reading a book right now and what I am getting is that a program need to handle its signal ( as when I press CTRL-C). Now a program can use SIG_IGN to ignore all signals or SIG_DFL to restore the default action.

Now if you do $ command & then this process running as background process simply ignores all signals that will occur. For foreground processes these signals are not ignored.

SQLite with encryption/password protection

You can password protect SQLite3 DB. For the first time before doing any operations, set password as follows.

SQLiteConnection conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
conn.SetPassword("password");
conn.open();

then next time you can access it like

conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;Password=password;");
conn.Open();

This wont allow any GUI editor to view Your data. Later if you wish to change the password, use conn.ChangePassword("new_password"); To reset or remove password, use conn.ChangePassword(String.Empty);

Freemarker iterating over hashmap keys

For completeness, it's worth mentioning there's a decent handling of empty collections in Freemarker since recently.

So the most convenient way to iterate a map is:

<#list tags>
<ul class="posts">
    <#items as tagName, tagCount>
        <li>{$tagName} (${tagCount})</li>
    </#items>
</ul>
<#else>
    <p>No tags found.</p>
</#list>

No more <#if ...> wrappers.

What is the correct way to restore a deleted file from SVN?

You should be able to just check out the one file you want to restore. Try something like svn co svn://your_repos/path/to/file/you/want/to/restore@rev where rev is the last revision at which the file existed.

I had to do exactly this a little while ago and if I remember correctly, using the -r option to svn didn't work; I had to use the :rev syntax. (Although I might have remembered it backwards...)

Python "extend" for a dictionary

As others have mentioned, a.update(b) for some dicts a and b will achieve the result you've asked for in your question. However, I want to point out that many times I have seen the extend method of mapping/set objects desire that in the syntax a.extend(b), a's values should NOT be overwritten by b's values. a.update(b) overwrites a's values, and so isn't a good choice for extend.

Note that some languages call this method defaults or inject, as it can be thought of as a way of injecting b's values (which might be a set of default values) in to a dictionary without overwriting values that might already exist.

Of course, you could simple note that a.extend(b) is nearly the same as b.update(a); a=b. To remove the assignment, you could do it thus:

def extend(a,b):
    """Create a new dictionary with a's properties extended by b,
    without overwriting.

    >>> extend({'a':1,'b':2},{'b':3,'c':4})
    {'a': 1, 'c': 4, 'b': 2}
    """
    return dict(b,**a)

Thanks to Tom Leys for that smart idea using a side-effect-less dict constructor for extend.

grep using a character vector with multiple patterns

Using the sapply

 patterns <- c("A1", "A9", "A6")
         df <- data.frame(name=c("A","Ale","Al","lex","x"),Letters=c("A1","A2","A9","A1","A9"))



   name Letters
1    A      A1
2  Ale      A2
3   Al      A9
4  lex      A1
5    x      A9


 df[unlist(sapply(patterns, grep, df$Letters, USE.NAMES = F)), ]
  name Letters
1    A      A1
4  lex      A1
3   Al      A9
5    x      A9

What is "406-Not Acceptable Response" in HTTP?

In my case for a API in .NET-Core, the api is set to work with XML (by default is set to response with JSON), so I add this annotation in my Controller :

[Produces("application/xml")]
public class MyController : ControllerBase {...}

Thank you for putting me on the path !

Comparing user-inputted characters in C

answer shouldn't be a pointer, the intent is obviously to hold a character. scanf takes the address of this character, so it should be called as

char answer;
scanf(" %c", &answer);

Next, your "or" statement is formed incorrectly.

if (answer == 'Y' || answer == 'y')

What you wrote originally asks to compare answer with the result of 'Y' || 'y', which I'm guessing isn't quite what you wanted to do.

Error You must specify a region when running command aws ecs list-container-instances

Just to add to answers by Mr. Dimitrov and Jason, if you are using a specific profile and you have put your region setting there,then for all the requests you need to add

"--profile" option.

For example:

Lets say you have AWS Playground profile, and the ~/.aws/config has [profile playground] which further has something like,

[profile playground] region=us-east-1

then, use something like below

aws ecs list-container-instances --cluster default --profile playground

right click context menu for datagridview

Use the CellMouseDown event on the DataGridView. From the event handler arguments you can determine which cell was clicked. Using the PointToClient() method on the DataGridView you can determine the relative position of the pointer to the DataGridView, so you can pop up the menu in the correct location.

(The DataGridViewCellMouseEvent parameter just gives you the X and Y relative to the cell you clicked, which isn't as easy to use to pop up the context menu.)

This is the code I used to get the mouse position, then adjust for the position of the DataGridView:

var relativeMousePosition = DataGridView1.PointToClient(Cursor.Position);
this.ContextMenuStrip1.Show(DataGridView1, relativeMousePosition);

The entire event handler looks like this:

private void DataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
    // Ignore if a column or row header is clicked
    if (e.RowIndex != -1 && e.ColumnIndex != -1)
    {
        if (e.Button == MouseButtons.Right)
        {
            DataGridViewCell clickedCell = (sender as DataGridView).Rows[e.RowIndex].Cells[e.ColumnIndex];

            // Here you can do whatever you want with the cell
            this.DataGridView1.CurrentCell = clickedCell;  // Select the clicked cell, for instance

            // Get mouse position relative to the vehicles grid
            var relativeMousePosition = DataGridView1.PointToClient(Cursor.Position);

            // Show the context menu
            this.ContextMenuStrip1.Show(DataGridView1, relativeMousePosition);
        }
    }
}

Recommended add-ons/plugins for Microsoft Visual Studio

How do I restart a program based on user input?

This line will unconditionally restart the running program from scratch:

os.execl(sys.executable, sys.executable, *sys.argv)

One of its advantage compared to the remaining suggestions so far is that the program itself will be read again.

This can be useful if, for example, you are modifying its code in another window.

Git for Windows: .bashrc or equivalent configuration files for Git Bash shell

Don't need to create a new file, it is already there!

/etc/bash.bashrc

Float right and position absolute doesn't work together

Generally speaking, float is a relative positioning statement, since it specifies the position of the element relative to its parent container (floating to the right or left). This means it's incompatible with the position:absolute property, because position:absolute is an absolute positioning statement. You can either float an element and allow the browser to position it relative to its parent container, or you can specify an absolute position and force the element to appear in a certain position regardless of its parent. If you want an absolutely-positioned element to appear on the right side of the screen, you can use position: absolute; right: 0;, but this will cause the element to always appear on the right edge of the screen regardless of how wide its parent div is (so it won't be "at the right of its parent div").

Why do I get a SyntaxError for a Unicode escape in my file path?

C:\\Users\\expoperialed\\Desktop\\Python This syntax worked for me.

gdb fails with "Unable to find Mach task port for process-id" error

In Snow Leopard and later Mac OS versions, it isn't enough to codesign the gdb executable.

You have to follow this guide to make it work: http://www.opensource.apple.com/source/lldb/lldb-69/docs/code-signing.txt

The guide explains how to do it for lldb, but the process is exactly the same for gdb.

Google Maps setCenter()

For me above solutions didn't work then I tried

map.setCenter(new google.maps.LatLng(lat, lng));

and it worked as expected.

How to echo xml file in php

If you just want to print the raw XML you don't need Simple XML. I added some error handling and a simple example of how you might want to use SimpleXML.

<?php 
$curl = curl_init();        
curl_setopt ($curl, CURLOPT_URL, 'http://rss.news.yahoo.com/rss/topstories');   
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);   
$result = curl_exec ($curl);   

if ($result === false) {
    die('Error fetching data: ' . curl_error($curl));   
}
curl_close ($curl);    

//we can at this point echo the XML if you want
//echo $result;

//parse xml string into SimpleXML objects
$xml = simplexml_load_string($result);

if ($xml === false) {
    die('Error parsing XML');   
}

//now we can loop through the xml structure
foreach ($xml->channel->item as $item) {
    print $item->title;   
}

Fastest way to update 120 Million records

declare @cnt bigint
set @cnt = 1

while @cnt*100<10000000 
 begin

UPDATE top(100) [Imp].[dbo].[tablename]
   SET [col1] = xxxx 
 WHERE[col1] is null  

  print '@cnt: '+convert(varchar,@cnt)
  set @cnt=@cnt+1
  end

Sticky Header after scrolling down

Here's is quite a list of jQuery plugins that will help achieve similar effect: http://jquery-plugins.net/tag/sticky-scroll

node.js + mysql connection pooling

i always use connection.relase(); after pool.getconnetion like

pool.getConnection(function (err, connection) {
      connection.release();
        if (!err)
        {
            console.log('*** Mysql Connection established with ', config.database, ' and connected as id ' + connection.threadId);
            //CHECKING USERNAME EXISTENCE
            email = receivedValues.email
            connection.query('SELECT * FROM users WHERE email = ?', [email],
                function (err, rows) {
                    if (!err)
                    {
                        if (rows.length == 1)
                        {
                            if (bcrypt.compareSync(req.body.password, rows[0].password))
                            {
                                var alldata = rows;
                                var userid = rows[0].id;
                                var tokendata = (receivedValues, userid);
                                var token = jwt.sign(receivedValues, config.secret, {
                                    expiresIn: 1440 * 60 * 30 // expires in 1440 minutes
                                });
                                console.log("*** Authorised User");
                                res.json({
                                    "code": 200,
                                    "status": "Success",
                                    "token": token,
                                    "userData": alldata,
                                    "message": "Authorised User!"
                                });
                                logger.info('url=', URL.url, 'Responce=', 'User Signin, username', req.body.email, 'User Id=', rows[0].id);
                                return;
                            }
                            else
                            {
                                console.log("*** Redirecting: Unauthorised User");
                                res.json({"code": 200, "status": "Fail", "message": "Unauthorised User!"});
                                logger.error('*** Redirecting: Unauthorised User');
                                return;
                            }
                        }
                        else
                        {
                            console.error("*** Redirecting: No User found with provided name");
                            res.json({
                                "code": 200,
                                "status": "Error",
                                "message": "No User found with provided name"
                            });
                            logger.error('url=', URL.url, 'No User found with provided name');
                            return;
                        }
                    }
                    else
                    {
                        console.log("*** Redirecting: Error for selecting user");
                        res.json({"code": 200, "status": "Error", "message": "Error for selecting user"});
                        logger.error('url=', URL.url, 'Error for selecting user', req.body.email);
                        return;
                    }
                });
            connection.on('error', function (err) {
                console.log('*** Redirecting: Error Creating User...');
                res.json({"code": 200, "status": "Error", "message": "Error Checking Username Duplicate"});
                return;
            });
        }
        else
        {
            Errors.Connection_Error(res);
        }
    });

React Error: Target Container is not a DOM Element

I got the same error i created the app with create-react-app but in /public/index.html also added matrialize script but there was to connection with "root" so i added

<div id="root"></div>

just before

<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/ materialize.min.js"></script>

And it worked for me .

how to store Image as blob in Sqlite & how to retrieve it?

for a ionic project


    var imgURI       = "";
    var imgBBDD      = ""; //sqllite for save into

    function takepicture() {
                var options = {
                    quality : 75,
                    destinationType : Camera.DestinationType.DATA_URL,
                    sourceType : Camera.PictureSourceType.CAMERA,
                    allowEdit : true,
                    encodingType: Camera.EncodingType.JPEG,
                    targetWidth: 300,
                    targetHeight: 300,
                    popoverOptions: CameraPopoverOptions,
                    saveToPhotoAlbum: false
                };

                $cordovaCamera.getPicture(options).then(function(imageData) {
                    imgURI = "data:image/jpeg;base64," + imageData;
                    imgBBDD = imageData;
                }, function(err) {
                    // An error occured. Show a message to the user
                });
            }

And now we put imgBBDD into SqlLite


     function saveImage = function (theId, theimage){
      var insertQuery = "INSERT INTO images(id, image) VALUES("+theId+", '"+theimage+"');"
      console.log('>>>>>>>');
      DDBB.SelectQuery(insertQuery)
                    .then( function(result) {
                        console.log("Image saved");
                    })
                    .catch( function(err) 
                     {
                        deferred.resolve(err);
                        return cb(err);
                    });
    }

A server side (php)


        $request = file_get_contents("php://input"); // gets the raw data
        $dades = json_decode($request,true); // true for return as array


    if($dades==""){
            $array = array();
            $array['error'] = -1;
            $array['descError'] = "Error when get the file";
            $array['logError'] = '';
            echo json_encode($array);
            exit;
        }
        //send the image again to the client
        header('Content-Type: image/jpeg');
        echo '';

How many bits is a "word"?

"most convenient block of data" probably refers to the width (in bits) of the WORD, in correspondance to the system bus width, or whatever underlying "bandwidth" is available. On a 16 bit system, with WORD being defined as 16 bits wide, moving data around in chunks the size of a WORD will be the most efficient way. (On hardware or "system" level.)

With Java being more or less platform independant, it just defines a "WORD" as the next size from a "BYTE", meaning "full bandwidth". I guess any platform that's able to run Java will use 32 bits for a WORD.

How to use Class<T> in Java?

I have found class<T> useful when I create service registry lookups. E.g.

<T> T getService(Class<T> serviceClass)
{
    ...
}

jQuery preventDefault() not triggered

If e.preventDefault(); is not working you must use e.stopImmediatePropagation(); instead.

For further informations take a look at : What's the difference between event.stopPropagation and event.preventDefault?

$("div.subtab_left li.notebook a").click(function(e) {
    e.stopImmediatePropagation();
    return false;
});

callback to handle completion of pipe

Here's a solution that handles errors in requests and calls a callback after the file is written:

request(opts)
    .on('error', function(err){ return callback(err)})
    .pipe(fs.createWriteStream(filename))
    .on('finish', function (err) {
        return callback(err);
    });

How to create a generic array?

Here is the implementation of LinkedList<T>#toArray(T[]):

public <T> T[] toArray(T[] a) {
    if (a.length < size)
        a = (T[])java.lang.reflect.Array.newInstance(
                            a.getClass().getComponentType(), size);
    int i = 0;
    Object[] result = a;
    for (Node<E> x = first; x != null; x = x.next)
        result[i++] = x.item;

    if (a.length > size)
        a[size] = null;

    return a;
}

In short, you could only create generic arrays through Array.newInstance(Class, int) where int is the size of the array.

Cannot overwrite model once compiled Mongoose

ther are so many good answer but for checking we can do easier job. i mean in most popular answer there is check.js ,our guy made it so much complicated ,i suggest:

function connectToDB() {
  if (mongoose.connection.readyState === 1) {
    console.log("already connected");
    return;
  }
  mongoose.connect(
    process.env.MONGODB_URL,
    {
      useCreateIndex: true,
      useFindAndModify: false,
      useNewUrlParser: true,
      useUnifiedTopology: true,
    },
    (err) => {
      if (err) throw err;
      console.log("DB connected");
    },
  );
}

readyState== 1 means connected
so does not try to connect again
so you won't get the error
i think it because of connecting while it is connected
it is another way of connecting to db

Angularjs dynamic ng-pattern validation

_x000D_
_x000D_
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>
_x000D_
<input type="number" require ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"><input type="submit">
_x000D_
_x000D_
_x000D_

Failed to find target with hash string 'android-25'

Make sure your computer is connected to the internet, then click on the link that comes with the error message i.e "install missing platform(s) and sync project". Give it a few seconds especially if your computer has low specs, it will bring up a window called SDK Quickfix Installation and everything is straightforward from there.

Simple logical operators in Bash

if ([ $NUM1 == 1 ] || [ $NUM2 == 1 ]) && [ -z "$STR" ]
then
    echo STR is empty but should have a value.
fi

Sourcetree - undo unpushed commits

  1. Right click on the commit you like to reset to (not the one you like to delete!)
  2. Select "Reset master to this commit"
  3. Select "Soft" reset.

A soft reset will keep your local changes.

Source: https://answers.atlassian.com/questions/153791/how-should-i-remove-push-commit-from-sourcetree

Edit

About git revert: This command creates a new commit which will undo other commits. E.g. if you have a commit which adds a new file, git revert could be used to make a commit which will delete the new file.

About applying a soft reset: Assume you have the commits A to E (A---B---C---D---E) and you like to delete the last commit (E). Then you can do a soft reset to commit D. With a soft reset commit E will be deleted from git but the local changes will be kept. There are more examples in the git reset documentation.

Spring JSON request getting 406 (not Acceptable)

<dependency>
    <groupId>com.fasterxml.jackson.jaxrs</groupId>
    <artifactId>jackson-jaxrs-base</artifactId>
    <version>2.6.3</version>
</dependency>

Python: How to use RegEx in an if statement?

if re.search(r'pattern', string):

Simple if-test:

if re.search(r'ing\b', "seeking a great perhaps"):     # any words end with ing?
    print("yes")

Pattern check, extract a substring, case insensitive:

match_object = re.search(r'^OUGHT (.*) BE$', "ought to be", flags=re.IGNORECASE)
if match_object:
    assert "to" == match_object.group(1)     # what's between ought and be?

Notes:

  • Use re.search() not re.match. Match restricts to the start of strings, a confusing convention if you ask me. If you do want a string-starting match, use caret or \A instead, re.search(r'^...', ...)

  • Use raw string syntax r'pattern' for the first parameter. Otherwise you would need to double up backslashes, as in re.search('ing\\b', ...)

  • In this example, \b is a special sequence meaning word-boundary in regex. Not to be confused with backspace.

  • re.search() returns None if it doesn't find anything, which is always falsy.

  • re.search() returns a Match object if it finds anything, which is always truthy.

  • a group is what matched inside parentheses

  • group numbering starts at 1

  • Specs

  • Tutorial

URL encoding in Android

For android, I would use String android.net.Uri.encode(String s)

Encodes characters in the given string as '%'-escaped octets using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes all other characters.

Ex/

String urlEncoded = "http://stackoverflow.com/search?q=" + Uri.encode(query);

How to set default values in Rails?

"Correct" is a dangerous word in Ruby. There's usually more than one way to do anything. If you know you'll always want that default value for that column on that table, setting them in a DB migration file is the easiest way:

class SetDefault < ActiveRecord::Migration
  def self.up
    change_column :people, :last_name, :type, :default => "Doe"
  end

  def self.down
    # You can't currently remove default values in Rails
    raise ActiveRecord::IrreversibleMigration, "Can't remove the default"
  end
end

Because ActiveRecord autodiscovers your table and column properties, this will cause the same default to be set in any model using it in any standard Rails app.

However, if you only want default values set in specific cases -- say, it's an inherited model that shares a table with some others -- then another elegant way is do it directly in your Rails code when the model object is created:

class GenericPerson < Person
  def initialize(attributes=nil)
    attr_with_defaults = {:last_name => "Doe"}.merge(attributes)
    super(attr_with_defaults)
  end
end

Then, when you do a GenericPerson.new(), it'll always trickle the "Doe" attribute up to Person.new() unless you override it with something else.

How to create a <style> tag with Javascript?

This object variable will append style tag to the head tag with type attribute and one simple transition rule inside that matches every single id/class/element. Feel free to modify content property and inject as many rules as you need. Just make sure that css rules inside content remain in one line (or 'escape' each new line, if You prefer so).

var script = {

  type: 'text/css', style: document.createElement('style'), 
  content: "* { transition: all 220ms cubic-bezier(0.390, 0.575, 0.565, 1.000); }",
  append: function() {

    this.style.type = this.type;
    this.style.appendChild(document.createTextNode(this.content));
    document.head.appendChild(this.style);

}}; script.append();

How to pass data in the ajax DELETE request other than headers

I was able to successfully pass through the data attribute in the ajax method. Here is my code

$.ajax({
     url: "/api/Gigs/Cancel",
     type: "DELETE",
     data: {
             "GigId": link.attr('data-gig-id')
           }

  })

The link.attr method simply returned the value of 'data-gig-id' .

Fast ceiling of an integer division in C / C++

For positive numbers

unsigned int x, y, q;

To round up ...

q = (x + y - 1) / y;

or (avoiding overflow in x+y)

q = 1 + ((x - 1) / y); // if x != 0

How to drop SQL default constraint without knowing its name?

To drop constraint for multiple columns:

declare @table_name nvarchar(256)

declare @Command nvarchar(max) = ''

set @table_name = N'ATableName'

select @Command = @Command + 'ALTER TABLE ' + @table_name + ' drop constraint ' + d.name + CHAR(10)+ CHAR(13)
from sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id
     and c.column_id = d.parent_column_id
where t.name = @table_name and c.name in ('column1','column2','column3')

--print @Command

execute (@Command)

how to change onclick event with jquery?

(2019) I used $('#'+id).removeAttr().off('click').on('click', function(){...});

I tried $('#'+id).off().on(...), but it wouldn't work to reset the onClick attribute every time it was called to be reset.

I use .on('click',function(){...}); to stay away from having to quote block all my javascript functions.

The O.P. could now use:

$(this).removeAttr('onclick').off('click').on('click', function(){ displayCalendar(document.prjectFrm[ia + 'dtSubDate'],'yyyy-mm-dd', this); });

Where this came through for me is when my div was set with the onClick attribute set statically:

<div onclick = '...'>

Otherwise, if I only had a dynamically attached a listener to it, I would have used the $('#'+id).off().on('click', function(){...});.

Without the off('click') my onClick listeners were being appended not replaced.

Is there a date format to display the day of the week in java?

SimpleDateFormat sdf=new SimpleDateFormat("EEE");

EEE stands for day of week for example Thursday is displayed as Thu.

string encoding and decoding?

That's because your input string can’t be converted according to the encoding rules (strict by default).

I don't know, but I always encoded using directly unicode() constructor, at least that's the ways at the official documentation:

unicode(your_str, errors="ignore")

How to copy Outlook mail message into excel using VBA or Macros

Since you have not mentioned what needs to be copied, I have left that section empty in the code below.

Also you don't need to move the email to the folder first and then run the macro in that folder. You can run the macro on the incoming mail and then move it to the folder at the same time.

This will get you started. I have commented the code so that you will not face any problem understanding it.

First paste the below mentioned code in the outlook module.

Then

  1. Click on Tools~~>Rules and Alerts
  2. Click on "New Rule"
  3. Click on "start from a blank rule"
  4. Select "Check messages When they arrive"
  5. Under conditions, click on "with specific words in the subject"
  6. Click on "specific words" under rules description.
  7. Type the word that you want to check in the dialog box that pops up and click on "add".
  8. Click "Ok" and click next
  9. Select "move it to specified folder" and also select "run a script" in the same box
  10. In the box below, specify the specific folder and also the script (the macro that you have in module) to run.
  11. Click on finish and you are done.

When the new email arrives not only will the email move to the folder that you specify but data from it will be exported to Excel as well.

UNTESTED

Const xlUp As Long = -4162

Sub ExportToExcel(MyMail As MailItem)
    Dim strID As String, olNS As Outlook.Namespace
    Dim olMail As Outlook.MailItem
    Dim strFileName As String

    '~~> Excel Variables
    Dim oXLApp As Object, oXLwb As Object, oXLws As Object
    Dim lRow As Long

    strID = MyMail.EntryID
    Set olNS = Application.GetNamespace("MAPI")
    Set olMail = olNS.GetItemFromID(strID)

    '~~> Establish an EXCEL application object
    On Error Resume Next
    Set oXLApp = GetObject(, "Excel.Application")

    '~~> If not found then create new instance
    If Err.Number <> 0 Then
        Set oXLApp = CreateObject("Excel.Application")
    End If
    Err.Clear
    On Error GoTo 0

    '~~> Show Excel
    oXLApp.Visible = True

    '~~> Open the relevant file
    Set oXLwb = oXLApp.Workbooks.Open("C:\Sample.xls")

    '~~> Set the relevant output sheet. Change as applicable
    Set oXLws = oXLwb.Sheets("Sheet1")

    lRow = oXLws.Range("A" & oXLApp.Rows.Count).End(xlUp).Row + 1

    '~~> Write to outlook
    With oXLws
        '
        '~~> Code here to output data from email to Excel File
        '~~> For example
        '
        .Range("A" & lRow).Value = olMail.Subject
        .Range("B" & lRow).Value = olMail.SenderName
        '
    End With

    '~~> Close and Clean up Excel
    oXLwb.Close (True)
    oXLApp.Quit
    Set oXLws = Nothing
    Set oXLwb = Nothing
    Set oXLApp = Nothing

    Set olMail = Nothing
    Set olNS = Nothing
End Sub

FOLLOWUP

To extract the contents from your email body, you can split it using SPLIT() and then parsing out the relevant information from it. See this example

Dim MyAr() As String

MyAr = Split(olMail.body, vbCrLf)

For i = LBound(MyAr) To UBound(MyAr)
    '~~> This will give you the contents of your email
    '~~> on separate lines
    Debug.Print MyAr(i)
Next i

HighCharts Hide Series Name from the Legend

Replace return 'Legend' by return ''

How to test a variable is null in python

Testing for name pointing to None and name existing are two semantically different operations.

To check if val is None:

if val is None:
    pass  # val exists and is None

To check if name exists:

try:
    val
except NameError:
    pass  # val does not exist at all

Quickly create large file on a Windows system

I was looking for a way to create a large dummy file with space allocation recently. All of the solutions look awkward. Finally I just started the DISKPART utility in Windows (embedded since Windows Vista):

DISKPART
CREATE VDISK FILE="C:\test.vhd" MAXIMUM=20000 TYPE=FIXED

Where MAXIMUM is the resulting file size, 20 GB here.

Use Font Awesome Icons in CSS

#content h2:before {
    content: "\f055";
    font-family: FontAwesome;
    left:0;
    position:absolute;
    top:0;
}

Example Link: https://codepen.io/bungeedesign/pen/XqeLQg

Get Icon code from: https://fontawesome.com/cheatsheet?from=io

This Handler class should be static or leaks might occur: IncomingHandler

I am not sure but you can try intialising handler to null in onDestroy()

jQuery - Call ajax every 10 seconds

You could try setInterval() instead:

var i = setInterval(function(){
   //Call ajax here
},10000)

c# dictionary How to add multiple values for single key?

When you add a string, do it differently depending on whether the key exists already or not. To add the string value for the key key:

List<string> list;
if (dictionary.ContainsKey(key)) {
  list = dictionary[key];
} else {
  list = new List<string>();
  dictionary.Add(ley, list);
}
list.Add(value);

Get list of all tables in Oracle?

The following query only list the required data, whereas the other answers gave me the extra data which only confused me.

select table_name from user_tables;

Padding a table row

Option 1

You could also solve it by adding a transparent border to the row (tr), like this

HTML

<table>
    <tr> 
         <td>1</td>
    </tr>
    <tr> 
         <td>2</td>
    </tr>
</table>

CSS

tr {
    border-top: 12px solid transparent;
    border-bottom: 12px solid transparent;
}

Works like a charm, although if you need regular borders, then this method will sadly not work.

Option 2

Since rows act as a way to group cells, the correct way to do this, would be to use

table {
    border-collapse: inherit;
    border-spacing: 0 10px;
}

How to get number of rows inserted by a transaction

In case you need further info for your log/audit you can OUTPUT clause: This way, not only you keep the number of rows affected, but also what records.

As an example of the Output Clause during inserts: SQL Server list of insert identities

DECLARE @InsertedIDs table(ID int);

INSERT INTO YourTable
    OUTPUT INSERTED.ID
        INTO @InsertedIDs 
    SELECT ...

HTH

Java - Convert int to Byte Array of 4 Bytes?

This should work:

public static final byte[] intToByteArray(int value) {
    return new byte[] {
            (byte)(value >>> 24),
            (byte)(value >>> 16),
            (byte)(value >>> 8),
            (byte)value};
}

Code taken from here.

Edit An even simpler solution is given in this thread.

Ajax Upload image

You can use jquery.form.js plugin to upload image via ajax to the server.

http://malsup.com/jquery/form/

Here is the sample jQuery ajax image upload script

(function() {
$('form').ajaxForm({
    beforeSubmit: function() {  
        //do validation here


    },

    beforeSend:function(){
       $('#loader').show();
       $('#image_upload').hide();
    },
    success: function(msg) {

        ///on success do some here
    }
}); })();  

If you have any doubt, please refer following ajax image upload tutorial here

http://www.smarttutorials.net/ajax-image-upload-using-jquery-php-mysql/

Letsencrypt add domain to existing certificate

You can replace the certificate by just running the certbot again with ./certbot-auto certonly

You will be prompted with this message if you try to generate a certificate for a domain that you have already covered by an existing certificate:

-------------------------------------------------------------------------------
You have an existing certificate that contains a portion of the domains you
requested (ref: /etc/letsencrypt/renewal/<domain>.conf)

It contains these names: <domain>

You requested these names for the new certificate: <domain>,
<the domain you want to add to the cert>.

Do you want to expand and replace this existing certificate with the new
certificate?
-------------------------------------------------------------------------------

Just chose Expand and replace it.

How to obtain a Thread id in Python?

threading.get_ident() works, or threading.current_thread().ident (or threading.currentThread().ident for Python < 2.6).

What is ":-!!" in C code?

Some people seem to be confusing these macros with assert().

These macros implement a compile-time test, while assert() is a runtime test.

git undo all uncommitted or unsaved changes

States transitioning from one commit to new commit

0. last commit,i.e. HEAD commit
1. Working tree changes, file/directory deletion,adding,modification.
2. The changes are staged in index
3. Staged changes are committed

Action for state transitioning

0->1: manual file/directory operation
1->2: git add .
2->3: git commit -m "xxx"

Check diff

0->1: git diff
0->2: git diff --cached
0->1, and 0->2: git diff HEAD
last last commit->last commit: git diff HEAD^ HEAD

Revert to last commit

2->1: git reset
1->0: git checkout .     #only for tracked files/directories(actions include modifying/deleting tracked files/directories)
1->0: git clean -fdx     #only for untracked files/directories(action includes adding new files/directories)
2->1, and 1->0: git reset --hard HEAD

Equivalent of git clone, without re-downloading anything

git reset && git checkout . && git clean -fdx

php error: Class 'Imagick' not found

For all to those having problems with this i did this tutorial:

How to install Imagemagick and Php module Imagick on ubuntu?

i did this 7 simple steps:

Update libraries, and packages

apt-get update

Remove obsolete things

apt-get autoremove

For the libraries of ImageMagick

apt-get install libmagickwand-dev

for the core class Imagick

apt-get install imagemagick

For create the binaries, and conections in beetween

pecl install imagick

Append the extension to your php.ini

echo "extension=imagick.so" >> /etc/php5/apache2/php.ini

Restart Apache

service apache2 restart

I found a problem. PHP searches for .so files in a folder called /usr/lib/php5/20100525, and the imagick.so is stored in a folder called /usr/lib/php5/20090626. So you have to copy the file to that folder.

How to add an Access-Control-Allow-Origin header

The accepted answer doesn't work for me unfortunately, since my site CSS files @import the font CSS files, and these are all stored on a Rackspace Cloud Files CDN.

Since the Apache headers are never generated (since my CSS is not on Apache), I had to do several things:

  1. Go to the Cloud Files UI and add a custom header (Access-Control-Allow-Origin with value *) for each font-awesome file
  2. Change the Content-Type of the woff and ttf files to font/woff and font/ttf respectively

See if you can get away with just #1, since the second requires a bit of command line work.

To add the custom header in #1:

  • view the cloud files container for the file
  • scroll down to the file
  • click the cog icon
  • click Edit Headers
  • select Access-Control-Allow-Origin
  • add the single character '*' (without the quotes)
  • hit enter
  • repeat for the other files

If you need to continue and do #2, then you'll need a command line with CURL

curl -D - --header "X-Auth-Key: your-auth-key-from-rackspace-cloud-control-panel" --header "X-Auth-User: your-cloud-username" https://auth.api.rackspacecloud.com/v1.0

From the results returned, extract the values for X-Auth-Token and X-Storage-Url

curl -X POST \
  -H "Content-Type: font/woff" \
  --header "X-Auth-Token: returned-x-auth-token" returned-x-storage-url/name-of-your-container/fonts/fontawesome-webfont.woff

curl -X POST \
  -H "Content-Type: font/ttf" \
  --header "X-Auth-Token: returned-x-auth-token" returned-x-storage-url/name-of-your-container/fonts/fontawesome-webfont.ttf

Of course, this process only works if you're using the Rackspace CDN. Other CDNs may offer similar facilities to edit object headers and change content types, so maybe you'll get lucky (and post some extra info here).

How can I use an ES6 import in Node.js?

You can also use npm package called esm which allows you to use ES6 modules in Node.js. It needs no configuration. With esm you will be able to use export/import in your JavaScript files.

Run the following command on your terminal

yarn add esm

or

npm install esm

After that, you need to require this package when starting your server with node. For example if your node server runs index.js file, you would use the command

node -r esm index.js

You can also add it in your package.json file like this

{
  "name": "My-app",
  "version": "1.0.0",
  "description": "Some Hack",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node -r esm index.js"
  },

}

Then run this command from the terminal to start your node server

npm start

Check this link for more details.

Is there a Google Keep API?

No there isn't. If you watch the http traffic and dump the page source you can see that there is an API below the covers, but it's not published nor available for 3rd party apps.

Check this link: https://developers.google.com/gsuite/products for updates.

However, there is an unofficial Python API under active development: https://github.com/kiwiz/gkeepapi

Open Sublime Text from Terminal in macOS

I achieve this with just one line in terminal (with Sublime 3):

alias subl='/usr/local/bin/sublime'

Seeing the underlying SQL in the Spring JdbcTemplate?

I use this line for Spring Boot applications:

logging.level.org.springframework.jdbc.core = TRACE

This approach pretty universal and I usually use it for any other classes inside my application.

Handle ModelState Validation in ASP.NET Web API

Like this, for example:

public HttpResponseMessage Post(Person person)
{
    if (ModelState.IsValid)
    {
        PersonDB.Add(person);
        return Request.CreateResponse(HttpStatusCode.Created, person);
    }
    else
    {
        // the code below should probably be refactored into a GetModelErrors
        // method on your BaseApiController or something like that

        var errors = new List<string>();
        foreach (var state in ModelState)
        {
            foreach (var error in state.Value.Errors)
            {
                errors.Add(error.ErrorMessage);
            }
        }
        return Request.CreateResponse(HttpStatusCode.Forbidden, errors);
    }
}

This will return a response like this (assuming JSON, but same basic principle for XML):

HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
(some headers removed here)

["A value is required.","The field First is required.","Some custom errorm essage."]

You can of course construct your error object/list any way you like, for example adding field names, field id's etc.

Even if it's a "one way" Ajax call like a POST of a new entity, you should still return something to the caller - something that indicates whether or not the request was successful. Imagine a site where your user will add some info about themselves via an AJAX POST request. What if the information they have tried to entered isn't valid - how will they know if their Save action was successful or not?

The best way to do this is using Good Old HTTP Status Codes like 200 OK and so on. That way your JavaScript can properly handle failures using the correct callbacks (error, success etc).

Here's a nice tutorial on a more advanced version of this method, using an ActionFilter and jQuery: http://asp.net/web-api/videos/getting-started/custom-validation

Use LIKE %..% with field values in MySQL

Use:

SELECT t1.Notes, 
       t2.Name
  FROM Table1 t1
  JOIN Table2 t2 ON t1.Notes LIKE CONCAT('%', t2.Name ,'%')

Remove all whitespace from C# string with regex

Regex.Replace does not modify its first argument (recall that strings are immutable in .NET) so the call

Regex.Replace(LastName, @"\s+", "");

leaves the LastName string unchanged. You need to call it like this:

LastName = Regex.Replace(LastName, @"\s+", "");

All three of your regular expressions would have worked. However, the first regex would remove all plus characters as well, which I imagine would be unintentional.

How do I update Node.js?

open cmd and type

npm i -g npm

CSS to make table 100% of max-width

I had the same issue it was due to that I had the bootstrap class "hidden-lg" on the table which caused it to stupidly become display: block !important;

I wonder how Bootstrap never considered to just instead do this:

@media (min-width: 1200px) {
    .hidden-lg {
         display: none;
    }
}

And then just leave the element whatever display it had before for other screensizes.. Perhaps it is too advanced for them to figure out..

Anyway so:

table {
    display: table; /* check so these really applies */
    width: 100%;
}

should work

What is the difference between null=True and blank=True in Django?

Here is an example of the field with blank= True and null=True

description = models.TextField(blank=True, null= True)

In this case: blank = True: tells our form that it is ok to leave the description field blank

and

null = True: tells our database that it is ok to record a null value in our db field and not give an error.

VirtualBox and vmdk vmx files

VMDK/VMX are VMWare file formats but you can use it with VirtualBox:

  1. Create a new Virtual Machine and when asks for a hard disk choose "Use an existing hard disk"
  2. Click on the "button with folder and green arrow image on the combo box right" which opens Virtual Media Manager, it looks like this (you can open it directly pressing CTRL+D on main window or in File > Virtual Media Manager menu)...
  3. Then you can add the VMDK/VMX hard disk image and setup it for your virtual machine :)

JavaScript array to CSV

const escapeString = item => (typeof item === 'string') ? `"${item}"` : String(item)

const arrayToCsv = (arr, seperator = ';') => arr.map(escapeString).join(seperator)

const rowKeysToCsv = (row, seperator = ';') => arrayToCsv(Object.keys(row))

const rowToCsv = (row, seperator = ';') => arrayToCsv(Object.values(row))

const rowsToCsv = (arr, seperator = ';') => arr.map(row => rowToCsv(row, seperator)).join('\n')

const collectionToCsvWithHeading = (arr, seperator = ';') => `${rowKeysToCsv(arr[0], seperator)}\n${rowsToCsv(arr, seperator)}`


// Usage: 

collectionToCsvWithHeading([
  { title: 't', number: 2 },
  { title: 't', number: 1 }
])

// Outputs: 
"title";"number"
"t";2
"t";1

Check the current number of connections to MongoDb

connect to the admin database and run db.serverStatus():

> var status = db.serverStatus()
> status.connections
   {"current" : 21, "available" : 15979}
> 

You can directly get by querying

db.serverStatus().connections

To understand what does MongoDb's db.serverStatus().connections response mean, read the documentation here.

connections

"connections" : {
   "current" : <num>,
   "available" : <num>,
   "totalCreated" : NumberLong(<num>)
},

connections A document that reports on the status of the connections. Use these values to assess the current load and capacity requirements of the server.

connections.current The number of incoming connections from clients to the database server . This number includes the current shell session. Consider the value of connections.available to add more context to this datum.

The value will include all incoming connections including any shell connections or connections from other servers, such as replica set members or mongos instances.

connections.available The number of unused incoming connections available. Consider this value in combination with the value of connections.current to understand the connection load on the database, and the UNIX ulimit Settings document for more information about system thresholds on available connections.

connections.totalCreated Count of all incoming connections created to the server. This number includes connections that have since closed.

What's a good (free) visual merge tool for Git? (on windows)

I've been using P4Merge, it's free and cross platform.

P4Merge

multiprocessing: How do I share a dict among multiple processes?

In addition to @senderle's here, some might also be wondering how to use the functionality of multiprocessing.Pool.

The nice thing is that there is a .Pool() method to the manager instance that mimics all the familiar API of the top-level multiprocessing.

from itertools import repeat
import multiprocessing as mp
import os
import pprint

def f(d: dict) -> None:
    pid = os.getpid()
    d[pid] = "Hi, I was written by process %d" % pid

if __name__ == '__main__':
    with mp.Manager() as manager:
        d = manager.dict()
        with manager.Pool() as pool:
            pool.map(f, repeat(d, 10))
        # `d` is a DictProxy object that can be converted to dict
        pprint.pprint(dict(d))

Output:

$ python3 mul.py 
{22562: 'Hi, I was written by process 22562',
 22563: 'Hi, I was written by process 22563',
 22564: 'Hi, I was written by process 22564',
 22565: 'Hi, I was written by process 22565',
 22566: 'Hi, I was written by process 22566',
 22567: 'Hi, I was written by process 22567',
 22568: 'Hi, I was written by process 22568',
 22569: 'Hi, I was written by process 22569',
 22570: 'Hi, I was written by process 22570',
 22571: 'Hi, I was written by process 22571'}

This is a slightly different example where each process just logs its process ID to the global DictProxy object d.

char *array and char array[]

The declaration and initialization

char *array = "One good thing about music";

declares a pointer array and make it point to a constant array of 31 characters.

The declaration and initialization

char array[] = "One, good, thing, about, music";

declares an array of characters, containing 31 characters.

And yes, the size of the arrays is 31, as it includes the terminating '\0' character.


Laid out in memory, it will be something like this for the first:

+-------+     +------------------------------+
| array | --> | "One good thing about music" |
+-------+     +------------------------------+

And like this for the second:

+------------------------------+
| "One good thing about music" |
+------------------------------+

Arrays decays to pointers to the first element of an array. If you have an array like

char array[] = "One, good, thing, about, music";

then using plain array when a pointer is expected, it's the same as &array[0].

That mean that when you, for example, pass an array as an argument to a function it will be passed as a pointer.

Pointers and arrays are almost interchangeable. You can not, for example, use sizeof(pointer) because that returns the size of the actual pointer and not what it points to. Also when you do e.g. &pointer you get the address of the pointer, but &array returns a pointer to the array. It should be noted that &array is very different from array (or its equivalent &array[0]). While both &array and &array[0] point to the same location, the types are different. Using the arrat above, &array is of type char (*)[31], while &array[0] is of type char *.


For more fun: As many knows, it's possible to use array indexing when accessing a pointer. But because arrays decays to pointers it's possible to use some pointer arithmetic with arrays.

For example:

char array[] = "Foobar";  /* Declare an array of 7 characters */

With the above, you can access the fourth element (the 'b' character) using either

array[3]

or

*(array + 3)

And because addition is commutative, the last can also be expressed as

*(3 + array)

which leads to the fun syntax

3[array]

Ant if else condition?

You can also do this with ant contrib's if task.

<if>
    <equals arg1="${condition}" arg2="true"/>
    <then>
        <copy file="${some.dir}/file" todir="${another.dir}"/>
    </then>
    <elseif>
        <equals arg1="${condition}" arg2="false"/>
        <then>
            <copy file="${some.dir}/differentFile" todir="${another.dir}"/>
        </then>
    </elseif>
    <else>
        <echo message="Condition was neither true nor false"/>
    </else>
</if>

JavaScript: Class.method vs. Class.prototype.method

Yes, the first function has no relationship with an object instance of that constructor function, you can consider it like a 'static method'.

In JavaScript functions are first-class objects, that means you can treat them just like any object, in this case, you are only adding a property to the function object.

The second function, as you are extending the constructor function prototype, it will be available to all the object instances created with the new keyword, and the context within that function (the this keyword) will refer to the actual object instance where you call it.

Consider this example:

// constructor function
function MyClass () {
  var privateVariable; // private member only available within the constructor fn

  this.privilegedMethod = function () { // it can access private members
    //..
  };
}

// A 'static method', it's just like a normal function 
// it has no relation with any 'MyClass' object instance
MyClass.staticMethod = function () {};

MyClass.prototype.publicMethod = function () {
  // the 'this' keyword refers to the object instance
  // you can access only 'privileged' and 'public' members
};

var myObj = new MyClass(); // new object instance

myObj.publicMethod();
MyClass.staticMethod();

Resolve absolute path from relative path and/or file name

Files See all other answers

Directories

With .. being your relative path, and assuming you are currently in D:\Projects\EditorProject:

cd .. & cd & cd EditorProject (the relative path)

returns absolute path e.g.

D:\Projects

Sqlite: CURRENT_TIMESTAMP is in GMT, not the timezone of the machine

I found on the sqlite documentation (https://www.sqlite.org/lang_datefunc.html) this text:

Compute the date and time given a unix timestamp 1092941466, and compensate for your local timezone.

SELECT datetime(1092941466, 'unixepoch', 'localtime');

That didn't look like it fit my needs, so I tried changing the "datetime" function around a bit, and wound up with this:

select datetime(timestamp, 'localtime')

That seems to work - is that the correct way to convert for your timezone, or is there a better way to do this?

Calculate mean across dimension in a 2D array

a.mean() takes an axis argument:

In [1]: import numpy as np

In [2]: a = np.array([[40, 10], [50, 11]])

In [3]: a.mean(axis=1)     # to take the mean of each row
Out[3]: array([ 25. ,  30.5])

In [4]: a.mean(axis=0)     # to take the mean of each col
Out[4]: array([ 45. ,  10.5])

Or, as a standalone function:

In [5]: np.mean(a, axis=1)
Out[5]: array([ 25. ,  30.5])

The reason your slicing wasn't working is because this is the syntax for slicing:

In [6]: a[:,0].mean() # first column
Out[6]: 45.0

In [7]: a[:,1].mean() # second column
Out[7]: 10.5

How do I check if an element is hidden in jQuery?

You can use this:

$(element).is(':visible');

Example code

_x000D_
_x000D_
$(document).ready(function()_x000D_
{_x000D_
    $("#toggle").click(function()_x000D_
    {_x000D_
        $("#content").toggle();_x000D_
    });_x000D_
_x000D_
    $("#visiblity").click(function()_x000D_
    {_x000D_
       if( $('#content').is(':visible') )_x000D_
       {_x000D_
          alert("visible"); // Put your code for visibility_x000D_
       }_x000D_
       else_x000D_
       {_x000D_
          alert("hidden");_x000D_
       }_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>_x000D_
_x000D_
<p id="content">This is a Content</p>_x000D_
_x000D_
<button id="toggle">Toggle Content Visibility</button>_x000D_
<button id="visibility">Check Visibility</button>
_x000D_
_x000D_
_x000D_

How do you disable the unused variable warnings coming out of gcc in 3rd party code I do not wish to edit?

The -Wno-unused-variable switch usually does the trick. However, that is a very useful warning indeed if you care about these things in your project. It becomes annoying when GCC starts to warn you about things not in your code though.

I would recommend you keeping the warning on, but use -isystem instead of -I for include directories of third-party projects. That flag tells GCC not to warn you about the stuff you have no control over.

For example, instead of -IC:\\boost_1_52_0, say -isystem C:\\boost_1_52_0.

Hope it helps. Good Luck!

VSCode: How to Split Editor Vertically

The key bindings has been changed with version 1.20:

SHIFT+ALT+0 for Linux.

Presumably the same works for Windows also and CMD+OPT+0 for Mac.

TypeScript enum to object array

_x000D_
_x000D_
enum GoalProgressMeasurements {_x000D_
    Percentage = 1,_x000D_
    Numeric_Target = 2,_x000D_
    Completed_Tasks = 3,_x000D_
    Average_Milestone_Progress = 4,_x000D_
    Not_Measured = 5_x000D_
}_x000D_
    _x000D_
const array = []_x000D_
    _x000D_
for (const [key, value] of Object.entries(GoalProgressMeasurements)) {_x000D_
    if (!Number.isNaN(Number(key))) {_x000D_
        continue;_x000D_
    }_x000D_
_x000D_
    array.push({ id: value, name: key.replace('_', '') });_x000D_
}_x000D_
_x000D_
console.log(array);
_x000D_
_x000D_
_x000D_

How can I resolve "Your requirements could not be resolved to an installable set of packages" error?

Add "barryvdh/laravel-cors": "^0.7.3" at the end of require array inside composer.json

Save composer.json and run composer update

You are done !

Access denied for user 'root'@'localhost' (using password: Yes) after password reset LINUX

You can try this solution :-

To have mysql asking you for a password, you also need to specify the -p-option: (try with space between -p and password)

mysql -u root -p new_password

MySQLl access denied

In the Second link someone has commented the same problem.

List of all index & index columns in SQL Server DB

I have needed to get particular indexes, their index columns and their included columns as well. Here is the query I have used:

SELECT INX.[name] AS [Index Name]
      ,TBL.[name] AS [Table Name]
      ,DS1.[IndexColumnsNames]
      ,DS2.[IncludedColumnsNames]
FROM [sys].[indexes] INX
INNER JOIN [sys].[tables] TBL
    ON INX.[object_id] = TBL.[object_id]
CROSS APPLY 
(
    SELECT STUFF
    (
        (
            SELECT ' [' + CLS.[name] + ']'
            FROM [sys].[index_columns] INXCLS
            INNER JOIN [sys].[columns] CLS 
                ON INXCLS.[object_id] = CLS.[object_id] 
                AND INXCLS.[column_id] = CLS.[column_id]
            WHERE INX.[object_id] = INXCLS.[object_id] 
                AND INX.[index_id] = INXCLS.[index_id]
                AND INXCLS.[is_included_column] = 0
            FOR XML PATH('')
        )
        ,1
        ,1
        ,''
    ) 
) DS1 ([IndexColumnsNames])
CROSS APPLY 
(
    SELECT STUFF
    (
        (
            SELECT ' [' + CLS.[name] + ']'
            FROM [sys].[index_columns] INXCLS
            INNER JOIN [sys].[columns] CLS 
                ON INXCLS.[object_id] = CLS.[object_id] 
                AND INXCLS.[column_id] = CLS.[column_id]
            WHERE INX.[object_id] = INXCLS.[object_id] 
                AND INX.[index_id] = INXCLS.[index_id]
                AND INXCLS.[is_included_column] = 1
            FOR XML PATH('')
        )
        ,1
        ,1
        ,''
    ) 
) DS2 ([IncludedColumnsNames])

Using .otf fonts on web browsers

From the Google Font Directory examples:

@font-face {
  font-family: 'Tangerine';
  font-style: normal;
  font-weight: normal;
  src: local('Tangerine'), url('http://example.com/tangerine.ttf') format('truetype');
}
body {
  font-family: 'Tangerine', serif;
  font-size: 48px;
}

This works cross browser with .ttf, I believe it may work with .otf. (Wikipedia says .otf is mostly backwards compatible with .ttf) If not, you can convert the .otf to .ttf

Here are some good sites:

How to use Angular4 to set focus by element id

This helped to me (in ionic, but idea is the same) https://mhartington.io/post/setting-input-focus/

in template:

<ion-item>
      <ion-label>Home</ion-label>
      <ion-input #input type="text"></ion-input>
</ion-item>
<button (click)="focusInput(input)">Focus</button>

in controller:

  focusInput(input) {
    input.setFocus();
  }