Programs & Examples On #Cdda

Simple pagination in javascript

A simple client-side pagination example where data is fetched only once at page loading.

_x000D_
_x000D_
// dummy data_x000D_
        const myarr = [{ "req_no": 1, "title": "test1" },_x000D_
        { "req_no": 2, "title": "test2" },_x000D_
        { "req_no": 3, "title": "test3" },_x000D_
        { "req_no": 4, "title": "test4" },_x000D_
        { "req_no": 5, "title": "test5" },_x000D_
        { "req_no": 6, "title": "test6" },_x000D_
        { "req_no": 7, "title": "test7" },_x000D_
        { "req_no": 8, "title": "test8" },_x000D_
        { "req_no": 9, "title": "test9" },_x000D_
        { "req_no": 10, "title": "test10" },_x000D_
        { "req_no": 11, "title": "test11" },_x000D_
        { "req_no": 12, "title": "test12" },_x000D_
        { "req_no": 13, "title": "test13" },_x000D_
        { "req_no": 14, "title": "test14" },_x000D_
        { "req_no": 15, "title": "test15" },_x000D_
        { "req_no": 16, "title": "test16" },_x000D_
        { "req_no": 17, "title": "test17" },_x000D_
        { "req_no": 18, "title": "test18" },_x000D_
        { "req_no": 19, "title": "test19" },_x000D_
        { "req_no": 20, "title": "test20" },_x000D_
        { "req_no": 21, "title": "test21" },_x000D_
        { "req_no": 22, "title": "test22" },_x000D_
        { "req_no": 23, "title": "test23" },_x000D_
        { "req_no": 24, "title": "test24" },_x000D_
        { "req_no": 25, "title": "test25" },_x000D_
        { "req_no": 26, "title": "test26" }];_x000D_
_x000D_
        // on page load collect data to load pagination as well as table_x000D_
        const data = { "req_per_page": document.getElementById("req_per_page").value, "page_no": 1 };_x000D_
_x000D_
        // At a time maximum allowed pages to be shown in pagination div_x000D_
        const pagination_visible_pages = 4;_x000D_
_x000D_
_x000D_
        // hide pages from pagination from beginning if more than pagination_visible_pages_x000D_
        function hide_from_beginning(element) {_x000D_
            if (element.style.display === "" || element.style.display === "block") {_x000D_
                element.style.display = "none";_x000D_
            } else {_x000D_
                hide_from_beginning(element.nextSibling);_x000D_
            }_x000D_
        }_x000D_
        _x000D_
        // hide pages from pagination ending if more than pagination_visible_pages_x000D_
        function hide_from_end(element) {_x000D_
            if (element.style.display === "" || element.style.display === "block") {_x000D_
                element.style.display = "none";_x000D_
            } else {_x000D_
                hide_from_beginning(element.previousSibling);_x000D_
            }_x000D_
        }_x000D_
        _x000D_
        // load data and style for active page_x000D_
        function active_page(element, rows, req_per_page) {_x000D_
            var current_page = document.getElementsByClassName('active');_x000D_
            var next_link = document.getElementById('next_link');_x000D_
            var prev_link = document.getElementById('prev_link');_x000D_
            var next_tab = current_page[0].nextSibling; _x000D_
            var prev_tab = current_page[0].previousSibling;_x000D_
            current_page[0].className = current_page[0].className.replace("active", "");_x000D_
            if (element === "next") {_x000D_
                if (parseInt(next_tab.text).toString() === 'NaN') {_x000D_
                    next_tab.previousSibling.className += " active";_x000D_
                    next_tab.setAttribute("onclick", "return false");_x000D_
                } else {_x000D_
                    next_tab.className += " active"_x000D_
                    render_table_rows(rows, parseInt(req_per_page), parseInt(next_tab.text));_x000D_
                    if (prev_link.getAttribute("onclick") === "return false") {_x000D_
                        prev_link.setAttribute("onclick", `active_page('prev',\"${rows}\",${req_per_page})`);_x000D_
                    }_x000D_
                    if (next_tab.style.display === "none") {_x000D_
                        next_tab.style.display = "block";_x000D_
                        hide_from_beginning(prev_link.nextSibling)_x000D_
                    }_x000D_
                }_x000D_
            } else if (element === "prev") {_x000D_
                if (parseInt(prev_tab.text).toString() === 'NaN') {_x000D_
                    prev_tab.nextSibling.className += " active";_x000D_
                    prev_tab.setAttribute("onclick", "return false");_x000D_
                } else {_x000D_
                    prev_tab.className += " active";_x000D_
                    render_table_rows(rows, parseInt(req_per_page), parseInt(prev_tab.text));_x000D_
                    if (next_link.getAttribute("onclick") === "return false") {_x000D_
                        next_link.setAttribute("onclick", `active_page('next',\"${rows}\",${req_per_page})`);_x000D_
                    }_x000D_
                    if (prev_tab.style.display === "none") {_x000D_
                        prev_tab.style.display = "block";_x000D_
                        hide_from_end(next_link.previousSibling)_x000D_
                    }_x000D_
                }_x000D_
            } else {_x000D_
                element.className += "active";_x000D_
                render_table_rows(rows, parseInt(req_per_page), parseInt(element.text));_x000D_
                if (prev_link.getAttribute("onclick") === "return false") {_x000D_
                    prev_link.setAttribute("onclick", `active_page('prev',\"${rows}\",${req_per_page})`);_x000D_
                }_x000D_
                if (next_link.getAttribute("onclick") === "return false") {_x000D_
                    next_link.setAttribute("onclick", `active_page('next',\"${rows}\",${req_per_page})`);_x000D_
                }_x000D_
            }_x000D_
        }_x000D_
_x000D_
        // Render the table's row in table request-table_x000D_
        function render_table_rows(rows, req_per_page, page_no) {_x000D_
            const response = JSON.parse(window.atob(rows));_x000D_
            const resp = response.slice(req_per_page * (page_no - 1), req_per_page * page_no)_x000D_
            $('#request-table').empty()_x000D_
            $('#request-table').append('<tr><th>Index</th><th>Request No</th><th>Title</th></tr>');_x000D_
            resp.forEach(function (element, index) {_x000D_
                if (Object.keys(element).length > 0) {_x000D_
                    const { req_no, title } = element;_x000D_
                    const td = `<tr><td>${++index}</td><td>${req_no}</td><td>${title}</td></tr>`;_x000D_
                    $('#request-table').append(td)_x000D_
                }_x000D_
            });_x000D_
        }_x000D_
_x000D_
        // Pagination logic implementation_x000D_
        function pagination(data, myarr) {_x000D_
            const all_data = window.btoa(JSON.stringify(myarr));_x000D_
            $(".pagination").empty();_x000D_
            if (data.req_per_page !== 'ALL') {_x000D_
                let pager = `<a href="#" id="prev_link" onclick=active_page('prev',\"${all_data}\",${data.req_per_page})>&laquo;</a>` +_x000D_
                    `<a href="#" class="active" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>1</a>`;_x000D_
                const total_page = Math.ceil(parseInt(myarr.length) / parseInt(data.req_per_page));_x000D_
                if (total_page < pagination_visible_pages) {_x000D_
                    render_table_rows(all_data, data.req_per_page, data.page_no);_x000D_
                    for (let num = 2; num <= total_page; num++) {_x000D_
                        pager += `<a href="#" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>${num}</a>`;_x000D_
                    }_x000D_
                } else {_x000D_
                    render_table_rows(all_data, data.req_per_page, data.page_no);_x000D_
                    for (let num = 2; num <= pagination_visible_pages; num++) {_x000D_
                        pager += `<a href="#" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>${num}</a>`;_x000D_
                    }_x000D_
                    for (let num = pagination_visible_pages + 1; num <= total_page; num++) {_x000D_
                        pager += `<a href="#" style="display:none;" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>${num}</a>`;_x000D_
                    }_x000D_
                }_x000D_
                pager += `<a href="#" id="next_link" onclick=active_page('next',\"${all_data}\",${data.req_per_page})>&raquo;</a>`;_x000D_
                $(".pagination").append(pager);_x000D_
            } else {_x000D_
                render_table_rows(all_data, myarr.length, 1);_x000D_
            }_x000D_
        }_x000D_
_x000D_
        //calling pagination function_x000D_
        pagination(data, myarr);_x000D_
_x000D_
_x000D_
        // trigger when requests per page dropdown changes_x000D_
        function filter_requests() {_x000D_
            const data = { "req_per_page": document.getElementById("req_per_page").value, "page_no": 1 };_x000D_
            pagination(data, myarr);_x000D_
        }
_x000D_
.box {_x000D_
 float: left;_x000D_
 padding: 50px 0px;_x000D_
}_x000D_
_x000D_
.clearfix::after {_x000D_
 clear: both;_x000D_
 display: table;_x000D_
}_x000D_
_x000D_
.options {_x000D_
 margin: 5px 0px 0px 0px;_x000D_
 float: left;_x000D_
}_x000D_
_x000D_
.pagination {_x000D_
 float: right;_x000D_
}_x000D_
_x000D_
.pagination a {_x000D_
 color: black;_x000D_
 float: left;_x000D_
 padding: 8px 16px;_x000D_
 text-decoration: none;_x000D_
 transition: background-color .3s;_x000D_
 border: 1px solid #ddd;_x000D_
 margin: 0 4px;_x000D_
}_x000D_
_x000D_
.pagination a.active {_x000D_
 background-color: #4CAF50;_x000D_
 color: white;_x000D_
 border: 1px solid #4CAF50;_x000D_
}_x000D_
_x000D_
.pagination a:hover:not(.active) {_x000D_
 background-color: #ddd;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div>_x000D_
    <table id="request-table">_x000D_
   </table>_x000D_
</div>_x000D_
_x000D_
<div class="clearfix">_x000D_
 <div class="box options">_x000D_
  <label>Requests Per Page: </label>_x000D_
      <select id="req_per_page" onchange="filter_requests()">_x000D_
   <option>5</option>_x000D_
   <option>10</option>_x000D_
   <option>ALL</option>_x000D_
  </select>_x000D_
 </div>_x000D_
 <div class="box pagination">_x000D_
 </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

When and why to 'return false' in JavaScript?

Why return false, or in fact, why return anything?

The code return(val); in a function returns the value of val to the caller of the function. Or, to quote MDN web docs, it...

...ends function execution and specifies a value to be returned to the function caller. (Source: MDN Web Docs: return.)

return false; then is useful in event handlers, because this will value is used by the event-handler to determine further action. return false; cancels events that normally take place with a handler, while return true; lets those events to occur. To quote MDN web docs again...

The return value from the handler determines if the event is canceled. (Source: MDN Web Docs: DOM OnEvent Handlers.)

If you are cancelling an event, return false; by itself is insufficient.

You should also use Event.preventDefault(); and Event.stopPropagation();.

The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. (Source: MDN Webdocs.)

  • Event.stopPropagation(); : To stop the event from clicking a link within the containing parent's DOM (i.e., if two links overlapped visually in the UI).

The stopPropagation() method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. (Source: MDN Webdocs.)

Working Demos

In this demo, we cancel an onclick function of a link and prevent the link from being clicked with return false;, preventDefault(), and stopPropagation().

Full Working JSBin Demo.

StackOverflow Demo...

_x000D_
_x000D_
document.getElementById('my-link').addEventListener('click', function(e) {
  console.log('Click happened for: ' + e.target.id);
  e.preventDefault();
  e.stopPropagation();
  return false;
});
_x000D_
<a href="https://www.wikipedia.com/" id="my-link" target="_blank">Link</a>
_x000D_
_x000D_
_x000D_

Efficient way to Handle ResultSet in Java

RHT pretty much has it. Or you could use a RowSetDynaClass and let someone else do all the work :)

How to use absolute path in twig functions

Daniel's answer seems to work fine for now, but please note that generating absolute urls using twig's asset function is now deprecated:

DEPRECATED - Generating absolute URLs with the Twig asset() function was deprecated in 2.7 and will be removed in 3.0. Please use absolute_url() instead.

Here's the official announcement: http://symfony.com/blog/new-in-symfony-2-7-the-new-asset-component#template-function-changes

You have to use the absolute_url twig function:

{# Symfony 2.6 #}
{{ asset('logo.png', absolute = true) }}

{# Symfony 2.7 #}
{{ absolute_url(asset('logo.png')) }}

It is interesting to note that it also works with path function:

{{ absolute_url(path('index')) }}

Using Address Instead Of Longitude And Latitude With Google Maps API

Thought I'd share this code snippet that I've used before, this adds multiple addresses via Geocode and adds these addresses as Markers...

_x000D_
_x000D_
var addressesArray = [_x000D_
  'Address Str.No, Postal Area/city',_x000D_
  //follow this structure_x000D_
]_x000D_
var map = new google.maps.Map(document.getElementById('map'), {_x000D_
  center: {_x000D_
    lat: 12.7826,_x000D_
    lng: 105.0282_x000D_
  },_x000D_
  zoom: 6,_x000D_
  gestureHandling: 'cooperative'_x000D_
});_x000D_
var geocoder = new google.maps.Geocoder();_x000D_
for (i = 0; i < addressArray.length; i++) {_x000D_
  var address = addressArray[i];_x000D_
  geocoder.geocode({_x000D_
    'address': address_x000D_
  }, function(results, status) {_x000D_
    if (status === 'OK') {_x000D_
      var marker = new google.maps.Marker({_x000D_
        map: map,_x000D_
        position: results[0].geometry.location,_x000D_
        center: {_x000D_
          lat: 12.7826,_x000D_
          lng: 105.0282_x000D_
        },_x000D_
      });_x000D_
    } else {_x000D_
      alert('Geocode was not successful for the following reason: ' + status);_x000D_
    }_x000D_
  });_x000D_
}
_x000D_
_x000D_
_x000D_

Collectors.toMap() keyMapper -- more succinct expression?

We can use an optional merger function also in case of same key collision. For example, If two or more persons have the same getLast() value, we can specify how to merge the values. If we not do this, we could get IllegalStateException. Here is the example to achieve this...

Map<String, Person> map = 
roster
    .stream()
    .collect(
        Collectors.toMap(p -> p.getLast(),
                         p -> p,
                         (person1, person2) -> person1+";"+person2)
    );

Android dex gives a BufferOverflowException when building

I solved this problem. Just make this change in the project properties file:

target=android-18
sdk.build.tools=18.1.1

And in the manifest file:

uses-sdk android:minSdkVersion="8"
android:targetSdkVersion="18"

PHP class: Global variable as property in class

Simply use the global keyword.

e.g.:

class myClass() {
    private function foo() {
        global $MyNumber;
        ...

$MyNumber will then become accessible (and indeed modifyable) within that method.

However, the use of globals is often frowned upon (they can give off a bad code smell), so you might want to consider using a singleton class to store anything of this nature. (Then again, without knowing more about what you're trying to achieve this might be a very bad idea - a define could well be more useful.)

Fetch frame count with ffmpeg

You can use ffprobe to get frame number with the following commands

  1. first method

ffprobe.exe -i video_name -print_format json -loglevel fatal -show_streams -count_frames -select_streams v

which tell to print data in json format

select_streams v will tell ffprobe to just give us video stream data and if you remove it, it will give you audio information as well

and the output will be like

{
    "streams": [
        {
            "index": 0,
            "codec_name": "mpeg4",
            "codec_long_name": "MPEG-4 part 2",
            "profile": "Simple Profile",
            "codec_type": "video",
            "codec_time_base": "1/25",
            "codec_tag_string": "mp4v",
            "codec_tag": "0x7634706d",
            "width": 640,
            "height": 480,
            "coded_width": 640,
            "coded_height": 480,
            "has_b_frames": 1,
            "sample_aspect_ratio": "1:1",
            "display_aspect_ratio": "4:3",
            "pix_fmt": "yuv420p",
            "level": 1,
            "chroma_location": "left",
            "refs": 1,
            "quarter_sample": "0",
            "divx_packed": "0",
            "r_frame_rate": "10/1",
            "avg_frame_rate": "10/1",
            "time_base": "1/3000",
            "start_pts": 0,
            "start_time": "0:00:00.000000",
            "duration_ts": 256500,
            "duration": "0:01:25.500000",
            "bit_rate": "261.816000 Kbit/s",
            "nb_frames": "855",
            "nb_read_frames": "855",
            "disposition": {
                "default": 1,
                "dub": 0,
                "original": 0,
                "comment": 0,
                "lyrics": 0,
                "karaoke": 0,
                "forced": 0,
                "hearing_impaired": 0,
                "visual_impaired": 0,
                "clean_effects": 0,
                "attached_pic": 0
            },
            "tags": {
                "creation_time": "2005-10-17 22:54:33",
                "language": "eng",
                "handler_name": "Apple Video Media Handler",
                "encoder": "3ivx D4 4.5.1"
            }
        }
    ]
}

2. you can use

ffprobe -v error -show_format -show_streams video_name

which will give you stream data, if you want selected information like frame rate, use the following command

ffprobe -v error -select_streams v:0 -show_entries stream=avg_frame_rate -of default=noprint_wrappers=1:nokey=1 video_name

which give a number base on your video information, the problem is when you use this method, its possible you get a N/A as output.

for more information check this page FFProbe Tips

type checking in javascript

These days, ECMAScript 6 (ECMA-262) is "in the house". Use Number.isInteger(x) to ask the question you want to ask with respect to the type of x:

js> var x = 3
js> Number.isInteger(x)
true
js> var y = 3.1
js> Number.isInteger(y)
false

PHP header redirect 301 - what are the implications?

This is better:

<?php
//* Permanently redirect page
header("Location: new_page.php",TRUE,301);
?>

Just one call including code 301. Also notice the relative path to the file in the same directory (not "/dir/dir/new_page.php", etc.), which all modern browsers seem to support.

I think this is valid since PHP 5.1.2, possibly earlier.

Difference between DOMContentLoaded and load events

DOMContentLoaded==window.onDomReady()

Load==window.onLoad()

A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $(document).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $(window).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.

See: Using JQuery Core's document-ready documentation.

How do I create executable Java program?

You can use the jar tool bundled with the SDK and create an executable version of the program.

This is how it's done.

I'm posting the results from my command prompt because it's easier, but the same should apply when using JCreator.

First create your program:

$cat HelloWorldSwing.java
    package start;

    import javax.swing.*;

    public class HelloWorldSwing {
        public static void main(String[] args) {
            //Create and set up the window.
            JFrame frame = new JFrame("HelloWorldSwing");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            JLabel label = new JLabel("Hello World");
            frame.add(label);

            //Display the window.
            frame.pack();
            frame.setVisible(true);
        }
    }
    class Dummy {
        // just to have another thing to pack in the jar
    }

Very simple, just displays a window with "Hello World"

Then compile it:

$javac -d . HelloWorldSwing.java

Two files were created inside the "start" folder Dummy.class and HelloWorldSwing.class.

$ls start/
Dummy.class     HelloWorldSwing.class

Next step, create the jar file. Each jar file have a manifest file, where attributes related to the executable file are.

This is the content of my manifest file.

$cat manifest.mf
Main-class: start.HelloWorldSwing

Just describe what the main class is ( the one with the public static void main method )

Once the manifest is ready, the jar executable is invoked.

It has many options, here I'm using -c -m -f ( -c to create jar, -m to specify the manifest file , -f = the file should be named.. ) and the folder I want to jar.

$jar -cmf manifest.mf hello.jar start

This creates the .jar file on the system

enter image description here

You can later just double click on that file and it will run as expected.

enter image description here

To create the .jar file in JCreator you just have to use "Tools" menu, create jar, but I'm not sure how the manifest goes there.

Here's a video I've found about: Create a Jar File in Jcreator.

I think you may proceed with the other links posted in this thread once you're familiar with this ".jar" approach.

You can also use jnlp ( Java Network Launcher Protocol ) too.

JPA - Returning an auto generated id after persist()

You could also use GenerationType.TABLE instead of IDENTITY which is only available after the insert.

Select rows from a data frame based on values in a vector

Another option would be to use a keyed data.table:

library(data.table)
setDT(dt, key = 'fct')[J(vc)]  # or: setDT(dt, key = 'fct')[.(vc)]

which results in:

   fct X
1:   a 2
2:   a 7
3:   a 1
4:   c 3
5:   c 5
6:   c 9
7:   c 2
8:   c 4

What this does:

  • setDT(dt, key = 'fct') transforms the data.frame to a data.table (which is an enhanced form of a data.frame) with the fct column set as key.
  • Next you can just subset with the vc vector with [J(vc)].

NOTE: when the key is a factor/character variable, you can also use setDT(dt, key = 'fct')[vc] but that won't work when vc is a numeric vector. When vc is a numeric vector and is not wrapped in J() or .(), vc will work as a rowindex.

A more detailed explanation of the concept of keys and subsetting can be found in the vignette Keys and fast binary search based subset.

An alternative as suggested by @Frank in the comments:

setDT(dt)[J(vc), on=.(fct)]

When vc contains values that are not present in dt, you'll need to add nomatch = 0:

setDT(dt, key = 'fct')[J(vc), nomatch = 0]

or:

setDT(dt)[J(vc), on=.(fct), nomatch = 0]

How to add a “readonly” attribute to an <input>?

Check the code below:

<input id="mail">

<script>

 document.getElementById('mail').readOnly = true; // makes input readonline
 document.getElementById('mail').readOnly = false; // makes input writeable again

</script>

How to send post request to the below post method using postman rest client

1.Open postman app 2.Enter the URL in the URL bar in postman app along with the name of the design.Use slash(/) after URL to give the design name. 3.Select POST from the dropdown list from URL textbox. 4.Select raw from buttons available below the URL textbox. 5.Select JSON from the dropdown. 6.In the text area enter your data to be updated and enter send. 7.Select GET from dropdown list from URL textbox and enter send to see the updated result.

how to get file path from sd card in android

Environment.getExternalStorageDirectory() will NOT return path to micro SD card Storage.

how to get file path from sd card in android

By sd card, I am assuming that, you meant removable micro SD card.

In API level 19 i.e. in Android version 4.4 Kitkat, they have added File[] getExternalFilesDirs (String type) in Context Class that allows apps to store data/files in micro SD cards.

Android 4.4 is the first release of the platform that has actually allowed apps to use SD cards for storage. Any access to SD cards before API level 19 was through private, unsupported APIs.

Environment.getExternalStorageDirectory() was there from API level 1

getExternalFilesDirs(String type) returns absolute paths to application-specific directories on all shared/external storage devices. It means, it will return paths to both internal and external memory. Generally, second returned path would be the storage path for microSD card (if any).

But note that,

Shared storage may not always be available, since removable media can be ejected by the user. Media state can be checked using getExternalStorageState(File).

There is no security enforced with these files. For example, any application holding WRITE_EXTERNAL_STORAGE can write to these files.

The Internal and External Storage terminology according to Google/official Android docs is quite different from what we think.

Converting integer to digit list

If you have a string like this: '123456' and you want a list of integers like this: [1,2,3,4,5,6], use this:

>>>s = '123456'    
>>>list1 = [int(i) for i in list(s)]
>>>print(list1)

[1,2,3,4,5,6]

or if you want a list of strings like this: ['1','2','3','4','5','6'], use this:

>>>s = '123456'    
>>>list1 = list(s)
>>>print(list1)

['1','2','3','4','5','6']

PHP regular expression - filter number only

You can try that one:

$string = preg_replace('/[^0-9]/', '', $string);

Cheers.

How to increase request timeout in IIS?

I know the question was about ASP but maybe somebody will find this answer helpful.

If you have a server behind the IIS 7.5 (e.g. Tomcat). In my case I have a server farm with Tomcat server configured. In such case you can change the timeout using the IIS Manager:

  • go to Server Farms -> {Server Name} -> Proxy
  • change the value in the Time-out entry box
  • click Apply (top-right corner)

or you can change it in the cofig file:

  • open %WinDir%\System32\Inetsrv\Config\applicationHost.config
  • adjust the server webFarm configuration to be similar to the following

Example:

<webFarm name="${SERVER_NAME}" enabled="true"> 
  <server address="${SERVER_ADDRESS}" enabled="true">
    <applicationRequestRouting httpPort="${SERVER_PORT}" />
  </server>
  <applicationRequestRouting>
    <protocol timeout="${TIME}" />
  </applicationRequestRouting>
</webFarm>

The ${TIME} is in HH:mm:ss format (so if you want to set it to 90 seconds then put there 00:01:30)

In case of Tomcat (and probably other servlet containers) you have to remember to change the timeout in the %TOMCAT_DIR%\conf\server.xml (just search for connectionTimeout attribute in Connector tag, and remember that it is specified in milliseconds)

Converting from longitude\latitude to Cartesian coordinates

In python3.x it can be done using :

# Converting lat/long to cartesian
import numpy as np

def get_cartesian(lat=None,lon=None):
    lat, lon = np.deg2rad(lat), np.deg2rad(lon)
    R = 6371 # radius of the earth
    x = R * np.cos(lat) * np.cos(lon)
    y = R * np.cos(lat) * np.sin(lon)
    z = R *np.sin(lat)
    return x,y,z

How to know the version of pip itself

Any of the following should work

pip --version
# pip 19.0.3 from /usr/local/lib/python2.7/site-packages/pip (python 2.7)

or

pip -V       
# pip 19.0.3 from /usr/local/lib/python2.7/site-packages/pip (python 2.7)

or

pip3 -V      
# pip 19.0.3 from /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip (python 3.7)

SQL server ignore case in a where expression

What database are you on? With MS SQL Server, it's a database-wide setting, or you can over-ride it per-query with the COLLATE keyword.

how do I create an array in jquery?

Here is an example that I used.

<script>
  $(document).ready(function(){
      var array =  $.makeArray(document.getElementsByTagName(“p”));
      array.reverse(); 
      $(array).appendTo(document.body);
  });
</script>

Regex expressions in Java, \\s vs. \\s+

First of all you need to understand that final output of both the statements will be same i.e. to remove all the spaces from given string.

However x.replaceAll("\\s+", ""); will be more efficient way of trimming spaces (if string can have multiple contiguous spaces) because of potentially less no of replacements due the to fact that regex \\s+ matches 1 or more spaces at once and replaces them with empty string.

So even though you get the same output from both it is better to use:

x.replaceAll("\\s+", "");

Display all items in array using jquery

Original from Sept. 13, 2015:
Quick and easy.

$.each(yourArray, function(index, value){
    $('.element').html( $('.element').html() + '<span>' + value +'</span>')
});

Update Sept 9, 2019: No jQuery is needed to iterate the array.

yourArray.forEach((value) => {
    $(".element").html(`${$(".element").html()}<span>${value}</span>`);
});

/* --- Or without jQuery at all --- */

yourArray.forEach((value) => {
    document.querySelector(".element").innerHTML += `<span>${value}</span>`;
});

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

You need to create a query (in Visual Studio, right-click on the DB connection -> New Query) and execute the following SQL:

ALTER TABLE tblAlpha
ADD CONSTRAINT MyConstraint FOREIGN KEY (FK_id) REFERENCES
tblGamma(GammaID)
ON UPDATE CASCADE

To verify that your foreign key was created, execute the following SQL:

SELECT * FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS

Credit to E Jensen (http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=532377&SiteID=1)

How to concatenate two strings in SQL Server 2005

Try this:

DECLARE @COMBINED_STRINGS AS VARCHAR(50); -- Allocate just enough length for the two strings.

SET @COMBINED_STRINGS = 'rupesh''s' + 'malviya';
SELECT @COMBINED_STRINGS; -- Print your combined strings.

Or you can put your strings into variables. Such that:

DECLARE @COMBINED_STRINGS AS VARCHAR(50),
        @STRING1 AS VARCHAR(20),
        @STRING2 AS VARCHAR(20);

SET @STRING1 = 'rupesh''s';
SET @STRING2 = 'malviya';
SET @COMBINED_STRINGS = @STRING1 + @STRING2;

SELECT @COMBINED_STRINGS; 

Output:

rupesh'smalviya

Just add a space in your string as a separator.

Spring Data and Native Query with pagination

This is a hack for program using Spring Data JPA before Version 2.0.4.

Code has worked with PostgreSQL and MySQL :

public interface UserRepository extends JpaRepository<User, Long> {

@Query(value = "SELECT * FROM USERS WHERE LASTNAME = ?1 ORDER BY ?#{#pageable}",
       countQuery = "SELECT count(*) FROM USERS WHERE LASTNAME = ?1",
       nativeQuery = true)
   Page<User> findByLastname(String lastname, Pageable pageable);   
}

ORDER BY ?#{#pageable} is for Pageable. countQuery is for Page<User>.

CSS table td width - fixed, not flexible

The above suggestions trashed the layout of my table so I ended up using:

td {
  min-width: 30px;
  max-width: 30px;
  overflow: hidden;
}

This is horrible to maintain but was easier than re-doing all the existing css for the site. Hope it helps someone else.

excel VBA run macro automatically whenever a cell is changed

I was creating a form in which the user enters an email address used by another macro to email a specific cell group to the address entered. I patched together this simple code from several sites and my limited knowledge of VBA. This simply watches for one cell (In my case K22) to be updated and then kills any hyperlink in that cell.

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range

    ' The variable KeyCells contains the cells that will
    ' cause an alert when they are changed.
    Set KeyCells = Range("K22")

    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then

        Range("K22").Select
        Selection.Hyperlinks.Delete

    End If 
End Sub

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

Also you need to check if individual record is not getting updated in the logic because with update trigger in the place causes time out error too.

So, the solution is to make sure you perform bulk update after the loop/cursor instead of one record at a time in the loop.

Is it possible to capture the stdout from the sh DSL command in the pipeline

Try this:

def get_git_sha(git_dir='') {
    dir(git_dir) {
        return sh(returnStdout: true, script: 'git rev-parse HEAD').trim()
    }
}

node(BUILD_NODE) {
    ...
    repo_SHA = get_git_sha('src/FooBar.git')
    echo repo_SHA
    ...
}

Tested on:

  • Jenkins ver. 2.19.1
  • Pipeline 2.4

LINQ Where with AND OR condition

Linq With Or Condition by using Lambda expression you can do as below

DataTable dtEmp = new DataTable();

dtEmp.Columns.Add("EmpID", typeof(int));
dtEmp.Columns.Add("EmpName", typeof(string));
dtEmp.Columns.Add("Sal", typeof(decimal));
dtEmp.Columns.Add("JoinDate", typeof(DateTime));
dtEmp.Columns.Add("DeptNo", typeof(int));

dtEmp.Rows.Add(1, "Rihan", 10000, new DateTime(2001, 2, 1), 10);
dtEmp.Rows.Add(2, "Shafi", 20000, new DateTime(2000, 3, 1), 10);
dtEmp.Rows.Add(3, "Ajaml", 25000, new DateTime(2010, 6, 1), 10);
dtEmp.Rows.Add(4, "Rasool", 45000, new DateTime(2003, 8, 1), 20);
dtEmp.Rows.Add(5, "Masthan", 22000, new DateTime(2001, 3, 1), 20);


var res2 = dtEmp.AsEnumerable().Where(emp => emp.Field<int>("EmpID")
            == 1 || emp.Field<int>("EmpID") == 2);

foreach (DataRow row in res2)
{
    Label2.Text += "Emplyee ID: " + row[0] + "   &   Emplyee Name: " + row[1] + ",  ";
}

How can I make a JUnit test wait?

If it is an absolute must to generate delay in a test CountDownLatch is a simple solution. In your test class declare:

private final CountDownLatch waiter = new CountDownLatch(1);

and in the test where needed:

waiter.await(1000 * 1000, TimeUnit.NANOSECONDS); // 1ms

Maybe unnecessary to say but keeping in mind that you should keep wait times small and not cumulate waits to too many places.

Convert tuple to list and back

You have a tuple of tuples.
To convert every tuple to a list:

[list(i) for i in level] # list of lists

--- OR ---

map(list, level)

And after you are done editing, just convert them back:

tuple(tuple(i) for i in edited) # tuple of tuples

--- OR --- (Thanks @jamylak)

tuple(itertools.imap(tuple, edited))

You can also use a numpy array:

>>> a = numpy.array(level1)
>>> a
array([[1, 1, 1, 1, 1, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 0, 0, 0, 0, 1],
       [1, 1, 1, 1, 1, 1]])

For manipulating:

if clicked[0] == 1:
    x = (mousey + cameraY) // 60 # For readability
    y = (mousex + cameraX) // 60 # For readability
    a[x][y] = 1

Check if an array item is set in JS

var is a statement... so it's a reserved word... So just call it another way. And that's a better way of doing it (=== is better than ==)

if(typeof array[name] !== 'undefined') {
    alert("Has var");
} else {
    alert("Doesn't have var");
}

How to set an image as a background for Frame in Swing GUI of java?

The Background Panel entry shows a couple of different ways depending on your requirements.

How to print color in console using System.out.println?

If you use Kotlin (which works seamlessly with Java), you can make such an enum:

enum class AnsiColor(private val colorNumber: Byte) {
    BLACK(0), RED(1), GREEN(2), YELLOW(3), BLUE(4), MAGENTA(5), CYAN(6), WHITE(7);

    companion object {
        private const val prefix = "\u001B"
        const val RESET = "$prefix[0m"
        private val isCompatible = "win" !in System.getProperty("os.name").toLowerCase()
    }

    val regular get() = if (isCompatible) "$prefix[0;3${colorNumber}m" else ""
    val bold get() = if (isCompatible) "$prefix[1;3${colorNumber}m" else ""
    val underline get() = if (isCompatible) "$prefix[4;3${colorNumber}m" else ""
    val background get() = if (isCompatible) "$prefix[4${colorNumber}m" else ""
    val highIntensity get() = if (isCompatible) "$prefix[0;9${colorNumber}m" else ""
    val boldHighIntensity get() = if (isCompatible) "$prefix[1;9${colorNumber}m" else ""
    val backgroundHighIntensity get() = if (isCompatible) "$prefix[0;10${colorNumber}m" else ""
}

And then use is as such: (code below showcases the different styles for all colors)

val sampleText = "This is a sample text"
enumValues<AnsiColor>().forEach { ansiColor ->
    println("${ansiColor.regular}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.bold}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.underline}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.background}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.highIntensity}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.boldHighIntensity}$sampleText${AnsiColor.RESET}")
    println("${ansiColor.backgroundHighIntensity}$sampleText${AnsiColor.RESET}")
}

If running on Windows where these ANSI codes are not supported, the isCompatible check avoids issues by replacing the codes with empty string.

How do I write a Windows batch script to copy the newest file from a directory?

The accepted answer gives an example of using the newest file in a command and then exiting. If you need to do this in a bat file with other complex operations you can use the following to store the file name of the newest file in a variable:

FOR /F "delims=|" %%I IN ('DIR "*.*" /B /O:D') DO SET NewestFile=%%I

Now you can reference %NewestFile% throughout the rest of your bat file.

For example here is what we use to get the latest version of a database .bak file from a directory, copy it to a server, and then restore the db:

:Variables
SET DatabaseBackupPath=\\virtualserver1\Database Backups

echo.
echo Restore WebServer Database
FOR /F "delims=|" %%I IN ('DIR "%DatabaseBackupPath%\WebServer\*.bak" /B /O:D') DO SET NewestFile=%%I
copy "%DatabaseBackupPath%\WebServer\%NewestFile%" "D:\"

sqlcmd -U <username> -P <password> -d master -Q ^
"RESTORE DATABASE [ExampleDatabaseName] ^
FROM  DISK = N'D:\%NewestFile%' ^
WITH  FILE = 1,  ^
MOVE N'Example_CS' TO N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Example.mdf',  ^
MOVE N'Example_CS_log' TO N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Example_1.LDF',  ^
NOUNLOAD,  STATS = 10"

Convert cells(1,1) into "A1" and vice versa

The Address property of a cell can get this for you:

MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)

returns A1.

The other way around can be done with the Row and Column property of Range:

MsgBox Range("A1").Row & ", " & Range("A1").Column

returns 1,1.

How to get content body from a httpclient call?

If you are not wanting to use async you can add .Result to force the code to execute synchronously:

private string GetResponseString(string text)
{
    var httpClient = new HttpClient();

    var parameters = new Dictionary<string, string>();
    parameters["text"] = text;

    var response = httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters)).Result;
    var contents = response.Content.ReadAsStringAsync().Result;

    return contents;
 }  

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

In my case there was no DEFINER or root@localhost mentioned in my SQL file. Actually I was trying to import and run SQL file into SQLYog from Database->Import->Execute SQL Script menu. That was giving error.

Then I copied all the script from SQL file and ran in SQLYog query editor. That worked perfectly fine.

Range of values in C Int and Long 32 - 64 bits

It is better to include stdlib.h. Since without stdlibg it takes long as long

How to really read text file from classpath in Java

Scenario:

1) client-service-1.0-SNAPSHOT.jar has dependency read-classpath-resource-1.0-SNAPSHOT.jar

2) we want to read content of class path resources (sample.txt) of read-classpath-resource-1.0-SNAPSHOT.jar through client-service-1.0-SNAPSHOT.jar.

3) read-classpath-resource-1.0-SNAPSHOT.jar has src/main/resources/sample.txt

Here is working sample code I prepared, after 2-3days wasting my development time, I found the complete end-to-end solution, hope this helps to save your time

1.pom.xml of read-classpath-resource-1.0-SNAPSHOT.jar

<?xml version="1.0" encoding="UTF-8"?>
        <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
            <modelVersion>4.0.0</modelVersion>
            <groupId>jar-classpath-resource</groupId>
            <artifactId>read-classpath-resource</artifactId>
            <version>1.0-SNAPSHOT</version>
            <name>classpath-test</name>
            <properties>
                <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
                <org.springframework.version>4.3.3.RELEASE</org.springframework.version>
                <mvn.release.plugin>2.5.1</mvn.release.plugin>
                <output.path>${project.artifactId}</output.path>
                <io.dropwizard.version>1.0.3</io.dropwizard.version>
                <commons-io.verion>2.4</commons-io.verion>
            </properties>
            <dependencies>
                <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-core</artifactId>
                    <version>${org.springframework.version}</version>
                </dependency>
                <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-context</artifactId>
                    <version>${org.springframework.version}</version>
                </dependency>
                <dependency>
                    <groupId>commons-io</groupId>
                    <artifactId>commons-io</artifactId>
                    <version>${commons-io.verion}</version>
                </dependency>
            </dependencies>
            <build>
                <resources>
                    <resource>
                        <directory>src/main/resources</directory>
                    </resource>
                </resources>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-release-plugin</artifactId>
                        <version>${mvn.release.plugin}</version>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-compiler-plugin</artifactId>
                        <version>3.1</version>
                        <configuration>
                            <source>1.8</source>
                            <target>1.8</target>
                            <encoding>UTF-8</encoding>
                        </configuration>
                    </plugin>
                    <plugin>
                        <artifactId>maven-jar-plugin</artifactId>
                        <version>2.5</version>
                        <configuration>
                            <outputDirectory>${project.build.directory}/lib</outputDirectory>
                            <archive>
                                <manifest>
                                    <addClasspath>true</addClasspath>
                                    <useUniqueVersions>false</useUniqueVersions>
                                    <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                                    <mainClass>demo.read.classpath.resources.ClassPathResourceReadTest</mainClass>
                                </manifest>
                                <manifestEntries>
                                    <Implementation-Artifact-Id>${project.artifactId}</Implementation-Artifact-Id>
                                    <Class-Path>sample.txt</Class-Path>
                                </manifestEntries>
                            </archive>
                        </configuration>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-shade-plugin</artifactId>
                        <version>2.2</version>
                        <configuration>
                            <createDependencyReducedPom>false</createDependencyReducedPom>
                            <filters>
                                <filter>
                                    <artifact>*:*</artifact>
                                    <excludes>
                                        <exclude>META-INF/*.SF</exclude>
                                        <exclude>META-INF/*.DSA</exclude>
                                        <exclude>META-INF/*.RSA</exclude>
                                    </excludes>
                                </filter>
                            </filters>
                        </configuration>
                        <executions>
                            <execution>
                                <phase>package</phase>
                                <goals>
                                    <goal>shade</goal>
                                </goals>
                                <configuration>
                                    <transformers>
                                        <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
                                        <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                            <mainClass>demo.read.classpath.resources.ClassPathResourceReadTest</mainClass>
                                        </transformer>
                                    </transformers>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </project>

2.ClassPathResourceReadTest.java class in read-classpath-resource-1.0-SNAPSHOT.jar that loads the class path resources file content.

package demo.read.classpath.resources;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public final class ClassPathResourceReadTest {
    public ClassPathResourceReadTest() throws IOException {
        InputStream inputStream = getClass().getResourceAsStream("/sample.txt");
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        List<Object> list = new ArrayList<>();
        String line;
        while ((line = reader.readLine()) != null) {
            list.add(line);
        }
        for (Object s1: list) {
            System.out.println("@@@ " +s1);
        }
        System.out.println("getClass().getResourceAsStream('/sample.txt') lines: "+list.size());
    }
}

3.pom.xml of client-service-1.0-SNAPSHOT.jar

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>client-service</groupId>
    <artifactId>client-service</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>jar-classpath-resource</groupId>
            <artifactId>read-classpath-resource</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                    <outputDirectory>${project.build.directory}/lib</outputDirectory>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <useUniqueVersions>false</useUniqueVersions>
                            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                            <mainClass>com.crazy.issue.client.AccessClassPathResource</mainClass>
                        </manifest>
                        <manifestEntries>
                            <Implementation-Artifact-Id>${project.artifactId}</Implementation-Artifact-Id>
                            <Implementation-Source-SHA>${buildNumber}</Implementation-Source-SHA>
                            <Class-Path>sample.txt</Class-Path>
                        </manifestEntries>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <createDependencyReducedPom>false</createDependencyReducedPom>
                    <filters>
                        <filter>
                            <artifact>*:*</artifact>
                            <excludes>
                                <exclude>META-INF/*.SF</exclude>
                                <exclude>META-INF/*.DSA</exclude>
                                <exclude>META-INF/*.RSA</exclude>
                            </excludes>
                        </filter>
                    </filters>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.crazy.issue.client.AccessClassPathResource</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

4.AccessClassPathResource.java instantiate ClassPathResourceReadTest.java class where, it is going to load sample.txt and prints its content also.

package com.crazy.issue.client;

import demo.read.classpath.resources.ClassPathResourceReadTest;
import java.io.IOException;

public class AccessClassPathResource {
    public static void main(String[] args) throws IOException {
        ClassPathResourceReadTest test = new ClassPathResourceReadTest();
    }
}

5.Run Executable jar as follows:

[ravibeli@localhost lib]$ java -jar client-service-1.0-SNAPSHOT.jar
****************************************
I am in resources directory of read-classpath-resource-1.0-SNAPSHOT.jar
****************************************
3) getClass().getResourceAsStream('/sample.txt'): 3

Construct pandas DataFrame from items in nested dictionary

So I used to use a for loop for iterating through the dictionary as well, but one thing I've found that works much faster is to convert to a panel and then to a dataframe. Say you have a dictionary d

import pandas as pd
d
{'RAY Index': {datetime.date(2014, 11, 3): {'PX_LAST': 1199.46,
'PX_OPEN': 1200.14},
datetime.date(2014, 11, 4): {'PX_LAST': 1195.323, 'PX_OPEN': 1197.69},
datetime.date(2014, 11, 5): {'PX_LAST': 1200.936, 'PX_OPEN': 1195.32},
datetime.date(2014, 11, 6): {'PX_LAST': 1206.061, 'PX_OPEN': 1200.62}},
'SPX Index': {datetime.date(2014, 11, 3): {'PX_LAST': 2017.81,
'PX_OPEN': 2018.21},
datetime.date(2014, 11, 4): {'PX_LAST': 2012.1, 'PX_OPEN': 2015.81},
datetime.date(2014, 11, 5): {'PX_LAST': 2023.57, 'PX_OPEN': 2015.29},
datetime.date(2014, 11, 6): {'PX_LAST': 2031.21, 'PX_OPEN': 2023.33}}}

The command

pd.Panel(d)
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 2 (major_axis) x 4 (minor_axis)
Items axis: RAY Index to SPX Index
Major_axis axis: PX_LAST to PX_OPEN
Minor_axis axis: 2014-11-03 to 2014-11-06

where pd.Panel(d)[item] yields a dataframe

pd.Panel(d)['SPX Index']
2014-11-03  2014-11-04  2014-11-05 2014-11-06
PX_LAST 2017.81 2012.10 2023.57 2031.21
PX_OPEN 2018.21 2015.81 2015.29 2023.33

You can then hit the command to_frame() to turn it into a dataframe. I use reset_index as well to turn the major and minor axis into columns rather than have them as indices.

pd.Panel(d).to_frame().reset_index()
major   minor      RAY Index    SPX Index
PX_LAST 2014-11-03  1199.460    2017.81
PX_LAST 2014-11-04  1195.323    2012.10
PX_LAST 2014-11-05  1200.936    2023.57
PX_LAST 2014-11-06  1206.061    2031.21
PX_OPEN 2014-11-03  1200.140    2018.21
PX_OPEN 2014-11-04  1197.690    2015.81
PX_OPEN 2014-11-05  1195.320    2015.29
PX_OPEN 2014-11-06  1200.620    2023.33

Finally, if you don't like the way the frame looks you can use the transpose function of panel to change the appearance before calling to_frame() see documentation here http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Panel.transpose.html

Just as an example

pd.Panel(d).transpose(2,0,1).to_frame().reset_index()
major        minor  2014-11-03  2014-11-04  2014-11-05  2014-11-06
RAY Index   PX_LAST 1199.46    1195.323     1200.936    1206.061
RAY Index   PX_OPEN 1200.14    1197.690     1195.320    1200.620
SPX Index   PX_LAST 2017.81    2012.100     2023.570    2031.210
SPX Index   PX_OPEN 2018.21    2015.810     2015.290    2023.330

Hope this helps.

How to find prime numbers between 0 - 100?

I have slightly modified the Sieve of Sundaram algorithm to cut the unnecessary iterations and it seems to be very fast.

This algorithm is actually two times faster than the most accepted @Ted Hopp's solution under this topic. Solving the 78498 primes between 0 - 1M takes like 20~25 msec in Chrome 55 and < 90 msec in FF 50.1. Also @vitaly-t's get next prime algorithm looks interesting but also results much slower.

This is the core algorithm. One could apply segmentation and threading to get superb results.

_x000D_
_x000D_
"use strict";_x000D_
function primeSieve(n){_x000D_
  var a = Array(n = n/2),_x000D_
      t = (Math.sqrt(4+8*n)-2)/4,_x000D_
      u = 0,_x000D_
      r = [];_x000D_
  for(var i = 1; i <= t; i++){_x000D_
    u = (n-i)/(1+2*i);_x000D_
    for(var j = i; j <= u; j++) a[i + j + 2*i*j] = true;_x000D_
  }_x000D_
  for(var i = 0; i<= n; i++) !a[i] && r.push(i*2+1);_x000D_
  return r;_x000D_
}_x000D_
_x000D_
var primes = [];_x000D_
console.time("primes");_x000D_
primes = primeSieve(1000000);_x000D_
console.timeEnd("primes");_x000D_
console.log(primes.length);
_x000D_
_x000D_
_x000D_

The loop limits explained:

Just like the Sieve of Erasthotenes, the Sieve of Sundaram algorithm also crosses out some selected integers from the list. To select which integers to cross out the rule is i + j + 2ij = n where i and j are two indices and n is the number of the total elements. Once we cross out every i + j + 2ij, the remaining numbers are doubled and oddified (2n+1) to reveal a list of prime numbers. The final stage is in fact the auto discounting of the even numbers. It's proof is beautifully explained here.

Sieve of Sundaram is only fast if the loop indices start and end limits are correctly selected such that there shall be no (or minimal) redundant (multiple) elimination of the non-primes. As we need i and j values to calculate the numbers to cross out, i + j + 2ij up to n let's see how we can approach.

i) So we have to find the the max value i and j can take when they are equal. Which is 2i + 2i^2 = n. We can easily solve the positive value for i by using the quadratic formula and that is the line with t = (Math.sqrt(4+8*n)-2)/4,

j) The inner loop index j should start from i and run up to the point it can go with the current i value. No more than that. Since we know that i + j + 2ij = n, this can easily be calculated as u = (n-i)/(1+2*i);

While this will not completely remove the redundant crossings it will "greatly" eliminate the redundancy. For instance for n = 50 (to check for primes up to 100) instead of doing 50 x 50 = 2500, we will do only 30 iterations in total. So clearly, this algorithm shouldn't be considered as an O(n^2) time complexity one.

i  j  v
1  1  4
1  2  7
1  3 10
1  4 13
1  5 16
1  6 19
1  7 22  <<
1  8 25
1  9 28
1 10 31  <<
1 11 34
1 12 37  <<
1 13 40  <<
1 14 43
1 15 46
1 16 49  <<
2  2 12
2  3 17
2  4 22  << dupe #1
2  5 27
2  6 32
2  7 37  << dupe #2
2  8 42
2  9 47
3  3 24
3  4 31  << dupe #3
3  5 38
3  6 45
4  4 40  << dupe #4
4  5 49  << dupe #5

among which there are only 5 duplicates. 22, 31, 37, 40, 49. The redundancy is around 20% for n = 100 however it increases to ~300% for n = 10M. Which means a further optimization of SoS bears the potentital to obtain the results even faster as n grows. So one idea might be segmentation and to keep n small all the time.

So OK.. I have decided to take this quest a little further.

After some careful examination of the repeated crossings I have come to the awareness of the fact that, by the exception of i === 1 case, if either one or both of the i or j index value is among 4,7,10,13,16,19... series, a duplicate crossing is generated. Then allowing the inner loop to turn only when i%3-1 !== 0, a further cut down like 35-40% from the total number of the loops is achieved. So for instance for 1M integers the nested loop's total turn count dropped to like 1M from 1.4M. Wow..! We are talking almost O(n) here.

I have just made a test. In JS, just an empty loop counting up to 1B takes like 4000ms. In the below modified algorithm, finding the primes up to 100M takes the same amount of time.

I have also implemented the segmentation part of this algorithm to push to the workers. So that we will be able to use multiple threads too. But that code will follow a little later.

So let me introduce you the modified Sieve of Sundaram probably at it's best when not segmented. It shall compute the primes between 0-1M in about 15-20ms with Chrome V8 and Edge ChakraCore.

_x000D_
_x000D_
"use strict";_x000D_
function primeSieve(n){_x000D_
  var a = Array(n = n/2),_x000D_
      t = (Math.sqrt(4+8*n)-2)/4,_x000D_
      u = 0,_x000D_
      r = [];_x000D_
  for(var i = 1; i < (n-1)/3; i++) a[1+3*i] = true;_x000D_
  for(var i = 2; i <= t; i++){_x000D_
    u = (n-i)/(1+2*i);_x000D_
    if (i%3-1) for(var j = i; j < u; j++) a[i + j + 2*i*j] = true;_x000D_
  }_x000D_
  for(var i = 0; i< n; i++) !a[i] && r.push(i*2+1);_x000D_
  return r;_x000D_
}_x000D_
_x000D_
var primes = [];_x000D_
console.time("primes");_x000D_
primes = primeSieve(1000000);_x000D_
console.timeEnd("primes");_x000D_
console.log(primes.length);
_x000D_
_x000D_
_x000D_

Well... finally I guess i have implemented a sieve (which is originated from the ingenious Sieve of Sundaram) such that it's the fastest JavaScript sieve that i could have found over the internet, including the "Odds only Sieve of Eratosthenes" or the "Sieve of Atkins". Also this is ready for the web workers, multi-threading.

Think it this way. In this humble AMD PC for a single thread, it takes 3,300 ms for JS just to count up to 10^9 and the following optimized segmented SoS will get me the 50847534 primes up to 10^9 only in 14,000 ms. Which means 4.25 times the operation of just counting. I think it's impressive.

You can test it for yourself;

_x000D_
_x000D_
console.time("tare");_x000D_
for (var i = 0; i < 1000000000; i++);_x000D_
console.timeEnd("tare");
_x000D_
_x000D_
_x000D_

And here i introduce you to the segmented Seieve of Sundaram at it's best.

_x000D_
_x000D_
"use strict";_x000D_
function findPrimes(n){_x000D_
  _x000D_
  function primeSieve(g,o,r){_x000D_
    var t = (Math.sqrt(4+8*(g+o))-2)/4,_x000D_
        e = 0,_x000D_
        s = 0;_x000D_
    _x000D_
    ar.fill(true);_x000D_
    if (o) {_x000D_
      for(var i = Math.ceil((o-1)/3); i < (g+o-1)/3; i++) ar[1+3*i-o] = false;_x000D_
      for(var i = 2; i < t; i++){_x000D_
        s = Math.ceil((o-i)/(1+2*i));_x000D_
        e = (g+o-i)/(1+2*i);_x000D_
        if (i%3-1) for(var j = s; j < e; j++) ar[i + j + 2*i*j-o] = false;_x000D_
      }_x000D_
    } else {_x000D_
        for(var i = 1; i < (g-1)/3; i++) ar[1+3*i] = false;_x000D_
        for(var i = 2; i < t; i++){_x000D_
          e = (g-i)/(1+2*i);_x000D_
          if (i%3-1) for(var j = i; j < e; j++) ar[i + j + 2*i*j] = false;_x000D_
        }_x000D_
      }_x000D_
    for(var i = 0; i < g; i++) ar[i] && r.push((i+o)*2+1);_x000D_
    return r;_x000D_
  }_x000D_
  _x000D_
  var cs = n <= 1e6 ? 7500_x000D_
                    : n <= 1e7 ? 60000_x000D_
                               : 100000, // chunk size_x000D_
      cc = ~~(n/cs),                     // chunk count_x000D_
      xs = n % cs,                       // excess after last chunk_x000D_
      ar = Array(cs/2),                  // array used as map_x000D_
  result = [];_x000D_
  _x000D_
  for(var i = 0; i < cc; i++) result = primeSieve(cs/2,i*cs/2,result);_x000D_
  result = xs ? primeSieve(xs/2,cc*cs/2,result) : result;_x000D_
  result[0] *=2;_x000D_
  return result;_x000D_
}_x000D_
_x000D_
_x000D_
var primes = [];_x000D_
console.time("primes");_x000D_
primes = findPrimes(1000000000);_x000D_
console.timeEnd("primes");_x000D_
console.log(primes.length);
_x000D_
_x000D_
_x000D_

I am not sure if it gets any better than this. I would love to hear your opinions.

TextView bold via xml file?

Example:

use: android:textStyle="bold"

 <TextView
    android:id="@+id/txtVelocidade"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/txtlatitude"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="34dp"
    android:textStyle="bold"
    android:text="Aguardando GPS"
    android:textAppearance="?android:attr/textAppearanceLarge" />

Dynamically replace img src attribute with jQuery

This is what you wanna do:

var oldSrc = 'http://example.com/smith.gif';
var newSrc = 'http://example.com/johnson.gif';
$('img[src="' + oldSrc + '"]').attr('src', newSrc);

How to get the file ID so I can perform a download of a file from Google Drive API on Android?

In my opinion the easiest and fastest way to get a Google Drive file ID is from Google Drive on the web. Right-click the file name and select Get shareable link. The last part of the link is the file ID. Then you can cancel the sharing.

How to request a random row in SQL?

 SELECT * FROM table ORDER BY RAND() LIMIT 1

Convert YYYYMMDD to DATE

Use SELECT CONVERT(date, '20140327')

In your case,

SELECT [FIRST_NAME],
       [MIDDLE_NAME],
       [LAST_NAME],
       CONVERT(date, [GRADUATION_DATE])     
FROM mydb

Pass array to mvc Action via AJAX

If you're using ASP.NET Core MVC and need to handle the square brackets (rather than use the jQuery "traditional" option), the only option I've found is to manually build the IEnumerable in the contoller method.

string arrayKey = "p[]=";
var pArray = HttpContext.Request.QueryString.Value
    .Split('&')
    .Where(s => s.Contains(arrayKey))
    .Select(s => s.Substring(arrayKey.Length));

Checking if a number is an Integer in Java

Check if ceil function and floor function returns the same value

static boolean isInteger(int n) 
{ 
return (int)(Math.ceil(n)) == (int)(Math.floor(n)); 
} 

Find the most common element in a list

Sort a copy of the list and find the longest run. You can decorate the list before sorting it with the index of each element, and then choose the run that starts with the lowest index in the case of a tie.

How can I close a Twitter Bootstrap popover with a click from anywhere (else) on the page?

@RayOnAir, I have same issue with previous solutions. I come close to @RayOnAir solution too. One thing that improved is close already opened popover when click on other popover marker. So my code is:

var clicked_popover_marker = null;
var popover_marker = '#pricing i';

$(popover_marker).popover({
  html: true,
  trigger: 'manual'
}).click(function (e) {
  clicked_popover_marker = this;

  $(popover_marker).not(clicked_popover_marker).popover('hide');
  $(clicked_popover_marker).popover('toggle');
});

$(document).click(function (e) {
  if (e.target != clicked_popover_marker) {
    $(popover_marker).popover('hide');
    clicked_popover_marker = null;
  }
});

Angular 2 optional route parameter

You can define multiple routes with and without parameter:

@RouteConfig([
    { path: '/user/:id', component: User, name: 'User' },
    { path: '/user', component: User, name: 'Usernew' }
])

and handle the optional parameter in your component:

constructor(params: RouteParams) {
    var paramId = params.get("id");

    if (paramId) {
        ...
    }
}

See also the related github issue: https://github.com/angular/angular/issues/3525

What is PHPSESSID?

PHPSESSID reveals you are using PHP. If you don't want this you can easily change the name using the session.name in your php.ini file or using the session_name() function.

Passing event and argument to v-on in Vue.js

If you want to access event object as well as data passed, you have to pass event and ticket.id both as parameters, like following:

HTML

<input type="number" v-on:input="addToCart($event, ticket.id)" min="0" placeholder="0">

Javascript

methods: {
  addToCart: function (event, id) {
    // use event here as well as id
    console.log('In addToCart')
    console.log(id)
  }
}

See working fiddle: https://jsfiddle.net/nee5nszL/

Edited: case with vue-router

In case you are using vue-router, you may have to use $event in your v-on:input method like following:

<input type="number" v-on:input="addToCart($event, num)" min="0" placeholder="0">

Here is working fiddle.

Angular2 RC6: '<component> is not a known element'

The error coming in unit test, when component is out of <router-outlet> in main app page. so should define the component in test file like below.

<app-header></app-header>
<router-outlet></router-outlet>

and then needs to add in spec.ts file as below.

import { HeaderComponent } from './header/header.component';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        App`enter code here`Component,
        HeaderComponent <------------------------
      ],
    }).compileComponents();
  }));
});

Add ArrayList to another ArrayList in java

Wouldn't it just be a case of:

ArrayList<ArrayList<String>> outer = new ArrayList<ArrayList<String>>();
ArrayList<String> nodeList = new ArrayList<String>();

// Fill in nodeList here...

outer.add(nodeList);

Repeat as necesary.

This should return you a list in the format you specified.

How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)

on Kate

Ctrl + Shift + B also allows you to add more columns by simply clicking anywhere and paste it.

I used this when saving text files I copied from Google Translate as a side-by-side view.

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

go your project directory and create folders on app/src path that named your product flavors (like Alpha, Beta, Store or what ever your flavor's name is). then copy your google-services.json file to each folder. don't forget to change "package_name" field on your each product flavor's google-services.json file that you subfoldered.

How to run multiple Python versions on Windows

Here's a quick hack:

  1. Go to the directory of the version of python you want to run
  2. Right click on python.exe
  3. Select 'Create Shortcut'
  4. Give that shortcut a name to call by( I use p27, p33 etc.)
  5. Move that shortcut to your home directory(C:\Users\Your name)
  6. Open a command prompt and enter name_of_your_shortcut.lnk(I use p27.lnk)

How does Java handle integer underflows and overflows and how would you check for it?

Java doesn't do anything with integer overflow for either int or long primitive types and ignores overflow with positive and negative integers.

This answer first describes the of integer overflow, gives an example of how it can happen, even with intermediate values in expression evaluation, and then gives links to resources that give detailed techniques for preventing and detecting integer overflow.

Integer arithmetic and expressions reslulting in unexpected or undetected overflow are a common programming error. Unexpected or undetected integer overflow is also a well-known exploitable security issue, especially as it affects array, stack and list objects.

Overflow can occur in either a positive or negative direction where the positive or negative value would be beyond the maximum or minimum values for the primitive type in question. Overflow can occur in an intermediate value during expression or operation evaluation and affect the outcome of an expression or operation where the final value would be expected to be within range.

Sometimes negative overflow is mistakenly called underflow. Underflow is what happens when a value would be closer to zero than the representation allows. Underflow occurs in integer arithmetic and is expected. Integer underflow happens when an integer evaluation would be between -1 and 0 or 0 and 1. What would be a fractional result truncates to 0. This is normal and expected with integer arithmetic and not considered an error. However, it can lead to code throwing an exception. One example is an "ArithmeticException: / by zero" exception if the result of integer underflow is used as a divisor in an expression.

Consider the following code:

int bigValue = Integer.MAX_VALUE;
int x = bigValue * 2 / 5;
int y = bigValue / x;

which results in x being assigned 0 and the subsequent evaluation of bigValue / x throws an exception, "ArithmeticException: / by zero" (i.e. divide by zero), instead of y being assigned the value 2.

The expected result for x would be 858,993,458 which is less than the maximum int value of 2,147,483,647. However, the intermediate result from evaluating Integer.MAX_Value * 2, would be 4,294,967,294, which exceeds the maximum int value and is -2 in accordance with 2s complement integer representations. The subsequent evaluation of -2 / 5 evaluates to 0 which gets assigned to x.

Rearranging the expression for computing x to an expression that, when evaluated, divides before multiplying, the following code:

int bigValue = Integer.MAX_VALUE;
int x = bigValue / 5 * 2;
int y = bigValue / x;

results in x being assigned 858,993,458 and y being assigned 2, which is expected.

The intermediate result from bigValue / 5 is 429,496,729 which does not exceed the maximum value for an int. Subsequent evaluation of 429,496,729 * 2 doesn't exceed the maximum value for an int and the expected result gets assigned to x. The evaluation for y then does not divide by zero. The evaluations for x and y work as expected.

Java integer values are stored as and behave in accordance with 2s complement signed integer representations. When a resulting value would be larger or smaller than the maximum or minimum integer values, a 2's complement integer value results instead. In situations not expressly designed to use 2s complement behavior, which is most ordinary integer arithmetic situations, the resulting 2s complement value will cause a programming logic or computation error as was shown in the example above. An excellent Wikipedia article describes 2s compliment binary integers here: Two's complement - Wikipedia

There are techniques for avoiding unintentional integer overflow. Techinques may be categorized as using pre-condition testing, upcasting and BigInteger.

Pre-condition testing comprises examining the values going into an arithmetic operation or expression to ensure that an overflow won't occur with those values. Programming and design will need to create testing that ensures input values won't cause overflow and then determine what to do if input values occur that will cause overflow.

Upcasting comprises using a larger primitive type to perform the arithmetic operation or expression and then determining if the resulting value is beyond the maximum or minimum values for an integer. Even with upcasting, it is still possible that the value or some intermediate value in an operation or expression will be beyond the maximum or minimum values for the upcast type and cause overflow, which will also not be detected and will cause unexpected and undesired results. Through analysis or pre-conditions, it may be possible to prevent overflow with upcasting when prevention without upcasting is not possible or practical. If the integers in question are already long primitive types, then upcasting is not possible with primitive types in Java.

The BigInteger technique comprises using BigInteger for the arithmetic operation or expression using library methods that use BigInteger. BigInteger does not overflow. It will use all available memory, if necessary. Its arithmetic methods are normally only slightly less efficient than integer operations. It is still possible that a result using BigInteger may be beyond the maximum or minimum values for an integer, however, overflow will not occur in the arithmetic leading to the result. Programming and design will still need to determine what to do if a BigInteger result is beyond the maximum or minimum values for the desired primitive result type, e.g., int or long.

The Carnegie Mellon Software Engineering Institute's CERT program and Oracle have created a set of standards for secure Java programming. Included in the standards are techniques for preventing and detecting integer overflow. The standard is published as a freely accessible online resource here: The CERT Oracle Secure Coding Standard for Java

The standard's section that describes and contains practical examples of coding techniques for preventing or detecting integer overflow is here: NUM00-J. Detect or prevent integer overflow

Book form and PDF form of The CERT Oracle Secure Coding Standard for Java are also available.

How can I use Helvetica Neue Condensed Bold in CSS?

"Helvetica Neue Condensed Bold" get working with firefox:

.class {
  font-family: "Helvetica Neue";
  font-weight: bold;
  font-stretch: condensed;
}

But it's fail with Opera.

Not able to change TextField Border Color

The best and most effective solution is just adding theme in your main class and add input decoration like these.

theme: ThemeData(
    inputDecorationTheme: InputDecorationTheme(
        border: OutlineInputBorder(
           borderSide: BorderSide(color: Colors.pink)
        )
    ),
)

Splitting string into multiple rows in Oracle

REGEXP_COUNT wasn't added until Oracle 11i. Here's an Oracle 10g solution, adopted from Art's solution.

SELECT trim(regexp_substr('Err1, Err2, Err3', '[^,]+', 1, LEVEL)) str_2_tab
  FROM dual
CONNECT BY LEVEL <=
  LENGTH('Err1, Err2, Err3')
    - LENGTH(REPLACE('Err1, Err2, Err3', ',', ''))
    + 1;

Testing whether a value is odd or even

A few

x % 2 == 0; // Check if even

!(x & 1); // bitmask the value with 1 then invert.

((x >> 1) << 1) == x; // divide value by 2 then multiply again and check against original value

~x&1; // flip the bits and bitmask

Select multiple columns from a table, but group by one

I had a similar problem to the OP. Then I saw the answer from @Urs Marian which helped a lot. But additionally what I was looking for is, when there are multiple values in a column and they will be grouped, how I can get the last submitted value (e.g. ordered by a date/id column).

Example:

We have following table structure:

CREATE TABLE tablename(
    [msgid] [int] NOT NULL,
    [userid] [int] NOT NULL,
    [username] [varchar](70) NOT NULL,
    [message] [varchar](5000) NOT NULL
) 

Now there are at least two datasets in the table:

+-------+--------+----------+---------+
| msgid | userid | username | message |
+-------+--------+----------+---------+
|     1 |      1 | userA    | hello   |
|     2 |      1 | userB    | world   |
+-------+--------+----------+---------+

Therefore following SQL script does work (checked on MSSQL) to group it, also if the same userid has different username values. In the example below, the username with the highest msgid will be shown:

SELECT m.userid, 
(select top 1 username from table where userid = m.userid order by msgid desc) as username,
count(*) as messages
FROM tablename m
GROUP BY m.userid
ORDER BY count(*) DESC

Is there a way to list open transactions on SQL Server 2000 database?

Use this because whenever transaction open more than one transaction then below will work SELECT * FROM sys.sysprocesses WHERE open_tran <> 0

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

... or if you really want to use NOT IN you can use

SELECT * FROM match WHERE id NOT IN ( SELECT id FROM email WHERE id IS NOT NULL)

Calling a function from a string in C#

This code works in my console .Net application
class Program
{
    static void Main(string[] args)
    {
        string method = args[0]; // get name method
        CallMethod(method);
    }
    
    public static void CallMethod(string method)
    {
        try
        {
            Type type = typeof(Program);
            MethodInfo methodInfo = type.GetMethod(method);
            methodInfo.Invoke(method, null);
        }
        catch(Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
            Console.ReadKey();
        }
    }
    
    public static void Hello()
    {
        string a = "hello world!";
        Console.WriteLine(a);
        Console.ReadKey();
    }
}

What is the difference between a framework and a library?

Library - Any set of classes or components that can be used as the client deems fit to accomplish a certain task.
Framework - mandates certain guidelines for you to "plug-in" into something bigger than you. You merely provide the pieces specific to your application/requirements in a published-required manner, so that 'the framwework can make your life easy'

XPath test if node value is number

The one I found very useful is the following:

<xsl:choose>
  <xsl:when test="not(number(myNode))">
      <!-- myNode is a not a number or empty(NaN) or zero -->      
  </xsl:when>
  <xsl:otherwise>
      <!-- myNode is a number (!= zero) -->        
  </xsl:otherwise>
</xsl:choose>

Sorting multiple keys with Unix sort

I just want to add some tips, when you using sort , be careful about your locale that effects the order of the key comparison. I usually explicitly use LC_ALL=C to make locale what I want.

How to detect running app using ADB command

Alternatively, you could go with pgrep or Process Grep. (Busybox is needed)

You could do a adb shell pgrep com.example.app and it would display just the process Id.

As a suggestion, since Android is Linux, you can use most basic Linux commands with adb shell to navigate/control around. :D

@UniqueConstraint and @Column(unique = true) in hibernate annotation

In addition to Boaz's answer ....

@UniqueConstraint allows you to name the constraint, while @Column(unique = true) generates a random name (e.g. UK_3u5h7y36qqa13y3mauc5xxayq).

Sometimes it can be helpful to know what table a constraint is associated with. E.g.:

@Table(
   name = "product_serial_group_mask", 
   uniqueConstraints = {
      @UniqueConstraint(
          columnNames = {"mask", "group"},
          name="uk_product_serial_group_mask"
      )
   }
)

c# .net change label text

Old question, but I had this issue as well, so after assigning the Text property, calling Refresh() will update the text.

Label1.Text = "Du har nu lånat filmen:" + test;
Refresh();

Hashset vs Treeset

A lot of answers have been given, based on technical considerations, especially around performance. According to me, choice between TreeSet and HashSet matters.

But I would rather say the choice should be driven by conceptual considerations first.

If, for the objects your need to manipulate, a natural ordering does not make sense, then do not use TreeSet.
It is a sorted set, since it implements SortedSet. So it means you need to override function compareTo, which should be consistent with what returns function equals. For example if you have a set of objects of a class called Student, then I do not think a TreeSet would make sense, since there is no natural ordering between students. You can order them by their average grade, okay, but this is not a "natural ordering". Function compareTo would return 0 not only when two objects represent the same student, but also when two different students have the same grade. For the second case, equals would return false (unless you decide to make the latter return true when two different students have the same grade, which would make equals function have a misleading meaning, not to say a wrong meaning.)
Please note this consistency between equals and compareTo is optional, but strongly recommended. Otherwise the contract of interface Set is broken, making your code misleading to other people, thus also possibly leading to unexpected behavior.

This link might be a good source of information regarding this question.

Position buttons next to each other in the center of page

jsFiddle:http://jsfiddle.net/7Laf8/1302/

I hope this answers your question.

_x000D_
_x000D_
.wrapper {_x000D_
  text-align: center;_x000D_
  display: inline-block;_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <button class="button">Hello</button>_x000D_
  <button class="button">Another One</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to set the opacity/alpha of a UIImage?

Swift 5:

extension UIImage {
  func withAlphaComponent(_ alpha: CGFloat) -> UIImage? {
    UIGraphicsBeginImageContextWithOptions(size, false, scale)
    defer { UIGraphicsEndImageContext() }

    draw(at: .zero, blendMode: .normal, alpha: alpha)
    return UIGraphicsGetImageFromCurrentImageContext()
  }
}

How do I use the Tensorboard callback of Keras?

You should check out Losswise (https://losswise.com), it has a plugin for Keras that's easier to use than Tensorboard and has some nice extra features. With Losswise you'd just use from losswise.libs import LosswiseKerasCallback and then callback = LosswiseKerasCallback(tag='my fancy convnet 1') and you're good to go (see https://docs.losswise.com/#keras-plugin).

PowerShell Script to Find and Replace for all Files with a Specific Extension

This powershell example looks for all instances of the string "\foo\" in a folder and its subfolders, replaces "\foo\" with "\bar\" AND DOES NOT REWRITE files that don't contain the string "\foo\" This way you don't destroy the file last update datetime stamps where the string was not found:

Get-ChildItem  -Path C:\YOUR_ROOT_PATH\*.* -recurse 
 | ForEach {If (Get-Content $_.FullName | Select-String -Pattern '\\foo\\') 
           {(Get-Content $_ | ForEach {$_ -replace '\\foo\\', '\bar\'}) | Set-Content $_ }
           }

Default visibility for C# classes and members (fields, methods, etc.)?

From MSDN:

Top-level types, which are not nested in other types, can only have internal or public accessibility. The default accessibility for these types is internal.


Nested types, which are members of other types, can have declared accessibilities as indicated in the following table.

Default Nested Member Accessibility & Allowed Accessibility Modifiers

Source: Accessibility Levels (C# Reference) (December 6th, 2017)

Linux shell sort file according to the second column?

FWIW, here is a sort method for showing which processes are using the most virt memory.

memstat | sort -k 1 -t':' -g -r | less

Sort options are set to first column, using : as column seperator, numeric sort and sort in reverse.

Character Limit on Instagram Usernames

Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

Disabling contextual LOB creation as createClob() method threw error

I hit this error when my web app was started in Linux by user logged in with insufficient access rights. This error

org.hibernate.engine.jdbc.internal.LobCreatorBuilder - HHH000424: Disabling contextual LOB creation as createClob() method threw error : java.lang.reflect.InvocationTargetException

usually preceded by other errors / exceptions, especially from your application server i.e for Tomcat:

org.apache.catalina.LifecycleException: Failed to initialize component ...

or

java.lang.UnsatisfiedLinkError: ... cannot open shared object file: No such file or directory

Solution:

  1. Stop your web apps current instance.

  2. Login with super user or those with sufficient access rights i.e root

  3. Restart your web app or call previous function again.

How to build an android library with Android Studio and gradle?

Here is my solution for mac users I think it work for window also:

First go to your Android Studio toolbar

Build > Make Project (while you guys are online let it to download the files) and then

Build > Compile Module "your app name is shown here" (still online let the files are
download and finish) and then

Run your app that is done it will launch your emulator and configure it then run it!

That is it!!! Happy Coding guys!!!!!!!

Set today's date as default date in jQuery UI datepicker

Set default date in initialization:

$("#date").datepicker({
    defaultDate: '01/26/2014'
});

How to show full height background image?

You can do it with the code you have, you just need to ensure that html and body are set to 100% height.

Demo: http://jsfiddle.net/kevinPHPkevin/a7eGN/

html, body {
    height:100%;
} 

body {
    background-color: white;
    background-image: url('http://www.canvaz.com/portrait/charcoal-1.jpg');
    background-size: auto 100%;
    background-repeat: no-repeat;
    background-position: left top;
}

Get Value of a Edit Text field

I hope this one should work:

Integer.valueOf(mEdit.getText().toString());

I tried Integer.getInteger() method instead of valueOf() - it didn't work.

How can I change text color via keyboard shortcut in MS word 2010

For Word 2010 and 2013, go to File > Options > Customize Ribbon > Keyboard Shortcuts > All Commands (in left list) > Color: (in right list) -- at this point, you type in the short cut (such as Alt+r) and select the color (such as red). (This actually goes back to 2003 but I don't have that installed to provide the pathway.)

How (and why) to use display: table-cell (CSS)

How (and why) to use display: table-cell (CSS)

I just wanted to mention, since I don't think any of the other answers did directly, that the answer to "why" is: there is no good reason, and you should probably never do this.

In my over a decade of experience in web development, I can't think of a single time I would have been better served to have a bunch of <div>s with display styles than to just have table elements.

The only hypothetical I could come up with is if you have tabular data stored in some sort of non-HTML-table format (eg. a CSV file). In a very specific version of this case it might be easier to just add <div> tags around everything and then add descendent-based styles, instead of adding actual table tags.

But that's an extremely contrived example, and in all real cases I know of simply using table tags would be better.

Possible heap pollution via varargs parameter

The reason is because varargs give the option of being called with a non-parametrized object array. So if your type was List < A > ... , it can also be called with List[] non-varargs type.

Here is an example:

public static void testCode(){
    List[] b = new List[1];
    test(b);
}

@SafeVarargs
public static void test(List<A>... a){
}

As you can see List[] b can contain any type of consumer, and yet this code compiles. If you use varargs, then you are fine, but if you use the method definition after type-erasure - void test(List[]) - then the compiler will not check the template parameter types. @SafeVarargs will suppress this warning.

How to use the switch statement in R functions?

This is a more general answer to the missing "Select cond1, stmt1, ... else stmtelse" connstruction in R. It's a bit gassy, but it works an resembles the switch statement present in C

while (TRUE) {
  if (is.na(val)) {
    val <- "NULL"
    break
  }
  if (inherits(val, "POSIXct") || inherits(val, "POSIXt")) {
    val <- paste0("#",  format(val, "%Y-%m-%d %H:%M:%S"), "#")
    break
  }
  if (inherits(val, "Date")) {
    val <- paste0("#",  format(val, "%Y-%m-%d"), "#")
    break
  }
  if (is.numeric(val)) break
  val <- paste0("'", gsub("'", "''", val), "'")
  break
}

Can't use Swift classes inside Objective-C

For Swift 5:

  1. Add the @objc keyword to your class and methods
  2. Add public keyword to your class and methods
  3. Let your class inherit from NSObject
  4. Build Project
  5. Put #import "MyProject-Swift.h" in your Objective-C file

    @objc
    public class MyClass: NSObject {
    
        @objc
        public func myMethod() {
    
        }
    }
    

The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

I had the same problem when trying to run a PowerShell script that only looked at a remote server to read the size of a hard disk.

I turned off the Firewall (Domain networks, Private networks, and Guest or public network) on the remote server and the script worked.

I then turned the Firewall for Domain networks back on, and it worked.

I then turned the Firewall for Private network back on, and it also worked.

I then turned the Firewall for Guest or public networks, and it also worked.

Killing a process using Java

On Windows, you could use this command.

taskkill /F /IM <processname>.exe 

To kill it forcefully, you may use;

Runtime.getRuntime().exec("taskkill /F /IM <processname>.exe")

What is the $$hashKey added to my JSON.stringify result

Here is how you can easily remove the $$hashKey from the object:

$scope.myNewObject = JSON.parse(angular.toJson($scope.myObject))

$scope.myObject - Refers to the Object that you want to perform the operation upon i.e. remove the $$hashKey from

$scope.myNewObject - Assign the modified original object to the new object so it can be used as necessary

html5 audio player - jquery toggle click play/pause?

This thread was quite helpful. The jQuery selector need to be told which of the selected elements the following code applies to. The easiest way is to append a

    [0]

such as

    $(".test")[0].play();

Best design for a changelog / auditing database table?

There are a lot of interesting answers here and in similar questions. The only things that I can add from personal experience are:

  1. Put your audit table in another database. Ideally, you want separation from the original data. If you need to restore your database, you don't really want to restore the audit trail.

  2. Denormalize as much as reasonably possible. You want the table to have as few dependencies as possible to the original data. The audit table should be simple and lightning fast to retrieve data from. No fancy joins or lookups across other tables to get to the data.

Inserting multiple rows in a single SQL query?

In SQL Server 2008 you can insert multiple rows using a single SQL INSERT statement.

INSERT INTO MyTable ( Column1, Column2 ) VALUES
( Value1, Value2 ), ( Value1, Value2 )

For reference to this have a look at MOC Course 2778A - Writing SQL Queries in SQL Server 2008.

For example:

INSERT INTO MyTable
  ( Column1, Column2, Column3 )
VALUES
  ('John', 123, 'Lloyds Office'), 
  ('Jane', 124, 'Lloyds Office'), 
  ('Billy', 125, 'London Office'),
  ('Miranda', 126, 'Bristol Office');

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

Material UI and Grid system

Material UI have implemented their own Flexbox layout via the Grid component.

It appears they initially wanted to keep themselves as purely a 'components' library. But one of the core developers decided it was too important not to have their own. It has now been merged into the core code and was released with v1.0.0.

You can install it via:

npm install @material-ui/core

It is now in the official documentation with code examples.

How to add native library to "java.library.path" with Eclipse launch (instead of overriding it)

If you want to add a native library without interfering with java.library.path at development time in Eclipse (to avoid including absolute paths and having to add parameters to your launch configuration), you can supply the path to the native libraries location for each Jar in the Java Build Path dialog under Native library location. Note that the native library file name has to correspond to the Jar file name. See also this detailed description.

jQuery SVG vs. Raphael

Another svg javascript library you might want to look at is d3.js. http://d3js.org/

SonarQube not picking up Unit Test Coverage

Jenkins does not show coverage results as it is a problem of version compatibilities between jenkins jacoco plugin and maven jacoco plugin. On my side I have fixed it by using a more recent version of maven jacoco plugin

<build>
   <pluginManagement>
     <plugins>
       <plugin>
         <groupId>org.jacoco</groupId>
         <artifactId>jacoco-maven-plugin</artifactId>
         <version>0.7.9</version>
       </plugin>
     <plugins>
   <pluginManagement>
<build>

simple way to display data in a .txt file on a webpage?

In more recent browsers code like below may be enough.

_x000D_
_x000D_
<object data="https://www.w3.org/TR/PNG/iso_8859-1.txt" width="300" height="200">_x000D_
Not supported_x000D_
</object>
_x000D_
_x000D_
_x000D_

Create a copy of a table within the same database DB2

You have to surround the select part with parenthesis.

CREATE TABLE SCHEMA.NEW_TB AS (
    SELECT *
    FROM SCHEMA.OLD_TB
) WITH NO DATA

Should work. Pay attention to all the things @Gilbert said would not be copied.

I'm assuming DB2 on Linux/Unix/Windows here, since you say DB2 v9.5.

Setting TIME_WAIT TCP

Pax is correct about the reasons for TIME_WAIT, and why you should be careful about lowering the default setting.

A better solution is to vary the port numbers used for the originating end of your sockets. Once you do this, you won't really care about time wait for individual sockets.

For listening sockets, you can use SO_REUSEADDR to allow the listening socket to bind despite the TIME_WAIT sockets sitting around.

Add new column in Pandas DataFrame Python

You just do an opposite comparison. if Col2 <= 1. This will return a boolean Series with False values for those greater than 1 and True values for the other. If you convert it to an int64 dtype, True becomes 1 and False become 0,

df['Col3'] = (df['Col2'] <= 1).astype(int)

If you want a more general solution, where you can assign any number to Col3 depending on the value of Col2 you should do something like:

df['Col3'] = df['Col2'].map(lambda x: 42 if x > 1 else 55)

Or:

df['Col3'] = 0
condition = df['Col2'] > 1
df.loc[condition, 'Col3'] = 42
df.loc[~condition, 'Col3'] = 55

Java socket API: How to tell if a connection has been closed?

It is general practice in various messaging protocols to keep heartbeating each other (keep sending ping packets) the packet does not need to be very large. The probing mechanism will allow you to detect the disconnected client even before TCP figures it out in general (TCP timeout is far higher) Send a probe and wait for say 5 seconds for a reply, if you do not see reply for say 2-3 subsequent probes, your player is disconnected.

Also, related question

How to set up a PostgreSQL database in Django

This is one of the very good and step by step process to set up PostgreSQL in ubuntu server. I have tried it with Ubuntu 16.04 and its working.

https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-14-04

Using GZIP compression with Spring Boot/MVC/JavaConfig with RESTful

I had the same problem into my Spring Boot+Spring Data project when invoking to a @RepositoryRestResource.

The problem is the MIME type returned; which is application/hal+json. Adding it to the server.compression.mime-types property solved this problem for me.

Hope this helps to someone else!

Accessing nested JavaScript objects and arrays by string path

Just in case, anyone's visiting this question in 2017 or later and looking for an easy-to-remember way, here's an elaborate blog post on Accessing Nested Objects in JavaScript without being bamboozled by

Cannot read property 'foo' of undefined error

Access Nested Objects Using Array Reduce

Let's take this example structure

const user = {
    id: 101,
    email: '[email protected]',
    personalInfo: {
        name: 'Jack',
        address: [{
            line1: 'westwish st',
            line2: 'washmasher',
            city: 'wallas',
            state: 'WX'
        }]
    }
}

To be able to access nested arrays, you can write your own array reduce util.

const getNestedObject = (nestedObj, pathArr) => {
    return pathArr.reduce((obj, key) =>
        (obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObj);
}

// pass in your object structure as array elements
const name = getNestedObject(user, ['personalInfo', 'name']);

// to access nested array, just pass in array index as an element the path array.
const city = getNestedObject(user, ['personalInfo', 'address', 0, 'city']);
// this will return the city from the first address item.

There is also an excellent type handling minimal library typy that does all this for you.

With typy, your code will look like this

const city = t(user, 'personalInfo.address[0].city').safeObject;

Disclaimer: I am the author of this package.

How to replace a character by a newline in Vim

Here's the trick:

First, set your Vi(m) session to allow pattern matching with special characters (i.e.: newline). It's probably worth putting this line in your .vimrc or .exrc file:

:set magic

Next, do:

:s/,/,^M/g

To get the ^M character, type Ctrl + V and hit Enter. Under Windows, do Ctrl + Q, Enter. The only way I can remember these is by remembering how little sense they make:

A: What would be the worst control-character to use to represent a newline?

B: Either q (because it usually means "Quit") or v because it would be so easy to type Ctrl + C by mistake and kill the editor.

A: Make it so.

How to connect to mysql with laravel?

It's also much more better to not modify the app/config/database.php file itself... otherwise modify .env file and put your DB info there. (.env file is available in Laravel 5, not sure if it was there in previous versions...)

NOTE: Of course you should have already set mysql as your default database connection in the app/config/database.php file.

How to subtract 2 hours from user's local time?

Subtract from another date object

var d = new Date();

d.setHours(d.getHours() - 2);

IOException: read failed, socket might closed - Bluetooth on Android 4.3

i also faced with this problem,you could solve it in 2 ways , as mentioned earlier use reflection to create the socket Second one is, client is looking for a server with given UUID and if your server isn't running parallel to client then this happens. Create a server with given client UUID and then listen and accept the client from server side.It will work.

Filtering a pyspark dataframe using isin by exclusion

df.filter((df.bar != 'a') & (df.bar != 'b'))

Extracting text from HTML file using Python

Another example using BeautifulSoup4 in Python 2.7.9+

includes:

import urllib2
from bs4 import BeautifulSoup

Code:

def read_website_to_text(url):
    page = urllib2.urlopen(url)
    soup = BeautifulSoup(page, 'html.parser')
    for script in soup(["script", "style"]):
        script.extract() 
    text = soup.get_text()
    lines = (line.strip() for line in text.splitlines())
    chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
    text = '\n'.join(chunk for chunk in chunks if chunk)
    return str(text.encode('utf-8'))

Explained:

Read in the url data as html (using BeautifulSoup), remove all script and style elements, and also get just the text using .get_text(). Break into lines and remove leading and trailing space on each, then break multi-headlines into a line each chunks = (phrase.strip() for line in lines for phrase in line.split(" ")). Then using text = '\n'.join, drop blank lines, finally return as sanctioned utf-8.

Notes:

'python3' is not recognized as an internal or external command, operable program or batch file

If python2 is not installed on your computer, you can try with just python instead of python3

How to generate a random number in C++?

for random every RUN file

size_t randomGenerator(size_t min, size_t max) {
    std::mt19937 rng;
    rng.seed(std::random_device()());
    //rng.seed(std::chrono::high_resolution_clock::now().time_since_epoch().count());
    std::uniform_int_distribution<std::mt19937::result_type> dist(min, max);

    return dist(rng);
}

How to select a range of the second row to the last row

Sub SelectAllCellsInSheet(SheetName As String)
    lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
    Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
    Sheets(SheetName).Range("A2", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
End Sub

To use with ActiveSheet:

Call SelectAllCellsInSheet(ActiveSheet.Name)

When use ResponseEntity<T> and @RestController for Spring RESTful applications

ResponseEntity is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body.

@ResponseBody is a marker for the HTTP response body and @ResponseStatus declares the status code of the HTTP response.

@ResponseStatus isn't very flexible. It marks the entire method so you have to be sure that your handler method will always behave the same way. And you still can't set the headers. You'd need the HttpServletResponse or a HttpHeaders parameter.

Basically, ResponseEntity lets you do more.

Merging arrays with the same keys

Try this:

$array_one = ['ratio_type'];
$array_two = ['ratio_type', 'ratio_type'];
$array_three = ['ratio_type'];
$array_four = ['ratio_type'];
$array_five = ['ratio_type', 'ratio_type', 'ratio_type'];
$array_six = ['ratio_type'];
$array_seven = ['ratio_type'];
$array_eight = ['ratio_type'];

$all_array_elements = array_merge_recursive(
    $array_one,
    $array_two,
    $array_three,
    $array_four,
    $array_five,
    $array_six,
    $array_seven,
    $array_eight
);

foreach ($all_array_elements as $key => $value) {
    echo "[$key]" . ' - ' . $value . PHP_EOL;
}

// OR
var_dump($all_array_elements);

How can I make the computer beep in C#?

I just came across this question while searching for the solution for myself. You might consider calling the system beep function by running some kernel32 stuff.

using System.Runtime.InteropServices;
        [DllImport("kernel32.dll")]
        public static extern bool Beep(int freq, int duration);

        public static void TestBeeps()
        {
            Beep(1000, 1600); //low frequency, longer sound
            Beep(2000, 400); //high frequency, short sound
        }

This is the same as you would run powershell:

[console]::beep(1000, 1600)
[console]::beep(2000, 400)

What is a 'multi-part identifier' and why can't it be bound?

Adding table alias in front Set field causes this problem in my case.

Right Update Table1 Set SomeField = t2.SomeFieldValue From Table1 t1 Inner Join Table2 as t2 On t1.ID = t2.ID

Wrong Update Table1 Set t1.SomeField = t2.SomeFieldValue From Table1 t1 Inner Join Table2 as t2 On t1.ID = t2.ID

Dynamically access object property using variable

It gets interesting when you have to pass parameters to this function as well.

Code jsfiddle

var obj = {method:function(p1,p2,p3){console.log("method:",arguments)}}

var str = "method('p1', 'p2', 'p3');"

var match = str.match(/^\s*(\S+)\((.*)\);\s*$/);

var func = match[1]
var parameters = match[2].split(',');
for(var i = 0; i < parameters.length; ++i) {
  // clean up param begninning
    parameters[i] = parameters[i].replace(/^\s*['"]?/,'');
  // clean up param end
  parameters[i] = parameters[i].replace(/['"]?\s*$/,'');
}

obj[func](parameters); // sends parameters as array
obj[func].apply(this, parameters); // sends parameters as individual values

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

You can increase the timeout in node like so.

app.post('/slow/request', function(req, res){ req.connection.setTimeout(100000); //100 seconds ... }

How can I add new dimensions to a Numpy array?

I followed this approach:

import numpy as np
import cv2

ls = []

for image in image_paths:
    ls.append(cv2.imread('test.jpg'))

img_np = np.array(ls) # shape (100, 480, 640, 3)
img_np = np.rollaxis(img_np, 0, 4) # shape (480, 640, 3, 100).

Increase JVM max heap size for Eclipse

It is possible to increase heap size allocated by the Java Virtual Machine (JVM) by using command line options.

-Xms<size>        set initial Java heap size
-Xmx<size>        set maximum Java heap size
-Xss<size>        set java thread stack size

If you are using the tomcat server, you can change the heap size by going to Eclipse/Run/Run Configuration and select Apache Tomcat/your_server_name/Arguments and under VM arguments section use the following:

-XX:MaxPermSize=256m
-Xms256m -Xmx512M

If you are not using any server, you can type the following on the command line before you run your code:

java -Xms64m -Xmx256m HelloWorld

More information on increasing the heap size can be found here

How to catch SQLServer timeout exceptions

I am not sure but when we have execute time out or command time out The client sends an "ABORT" to SQL Server then simply abandons the query processing. No transaction is rolled back, no locks are released. to solve this problem I Remove transaction in Stored-procedure and use SQL Transaction in my .Net Code To manage sqlException

Easy way to convert a unicode list to a list containing python strings?

Just simply use this code

EmployeeList = eval(EmployeeList)
EmployeeList = [str(x) for x in EmployeeList]

Copy output of a JavaScript variable to the clipboard

When you need to copy a variable to the clipboard in the Chrome dev console, you can simply use the copy() command.

https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference#copyobject

Visualizing decision tree in scikit-learn

If you run into issues with grabbing the source .dot directly you can also use Source.from_file like this:

from graphviz import Source
from sklearn import tree
tree.export_graphviz(dtreg, out_file='tree.dot', feature_names=X.columns)
Source.from_file('tree.dot')

Date Format in Swift

swift 3

let date : Date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMM dd, yyyy"
let todaysDate = dateFormatter.string(from: date)

Pure CSS scroll animation

And for webkit enabled browsers I've had good results with:

.myElement {
    -webkit-overflow-scrolling: touch;
    scroll-behavior: smooth; // Added in from answer from Felix
    overflow-x: scroll;
}

This makes scrolling behave much more like the standard browser behavior - at least it works well on the iPhone we were testing on!

Hope that helps,

Ed

How to put a text beside the image?

Use floats to float the image, the text should wrap beside

http://www.w3schools.com/css/css_float.asp

How to create a HashMap with two keys (Key-Pair, Value)?

If they are two integers you can try a quick and dirty trick: Map<String, ?> using the key as i+"#"+j.

If the key i+"#"+j is the same as j+"#"+i try min(i,j)+"#"+max(i,j).

mvn command not found in OSX Mavrerick

Try following these if these might help:

Since your installation works on the terminal you installed, all the exports you did, work on the current bash and its child process. but is not spawned to new terminals.

env variables are lost if the session is closed; using .bash_profile, you can make it available in all sessions, since when a bash session starts, it 'runs' its .bashrc and .bash_profile

Now follow these steps and see if it helps:

  1. type env | grep M2_HOME on the terminal that is working. This should give something like

    M2_HOME=/usr/local/apache-maven/apache-maven-3.1.1

  2. typing env | grep JAVA_HOME should give like this:

    JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_40.jdk/Contents/Home

Now you have the PATH for M2_HOME and JAVA_HOME.

If you just do ls /usr/local/apache-maven/apache-maven-3.1.1/bin, you will see mvn binary there. All you have to do now is to point to this location everytime using PATH. since bash searches in all the directory path mentioned in PATH, it will find mvn.

  1. now open .bash_profile, if you dont have one just create one

    vi ~/.bash_profile

Add the following:

#set JAVA_HOME
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_40.jdk/Contents/Home
export JAVA_HOME


M2_HOME=/usr/local/apache-maven/apache-maven-3.1.1
export M2_HOME

PATH=$PATH:$JAVA_HOME/bin:$M2_HOME/bin
export PATH
  1. save the file and type source ~/.bash_profile. This steps executes the commands in the .bash_profile file and you are good to go now.

  2. open a new terminal and type mvn that should work.

Combination of async function + await + setTimeout

This is my version with nodejs now in 2020 in AWS labdas

const sleep = require('util').promisify(setTimeout)

async function f1 (some){
...
}

async function f2 (thing){
...
}

module.exports.someFunction = async event => {
    ...
    await f1(some)
    await sleep(5000)
    await f2(thing)
    ...
}

How to check command line parameter in ".bat" file?

Actually, all the other answers have flaws. The most reliable way is:

IF "%~1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)

Detailed Explanation:

Using "%1"=="-b" will flat out crash if passing argument with spaces and quotes. This is the least reliable method.

IF "%1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)

C:\> run.bat "a b"

b""=="-b" was unexpected at this time.

Using [%1]==[-b] is better because it will not crash with spaces and quotes, but it will not match if the argument is surrounded by quotes.

IF [%1]==[-b] (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)

C:\> run.bat "-b"

(does not match, and jumps to UNKNOWN instead of SPECIFIC)

Using "%~1"=="-b" is the most reliable. %~1 will strip off surrounding quotes if they exist. So it works with and without quotes, and also with no args.

IF "%~1"=="-b" (GOTO SPECIFIC) ELSE (GOTO UNKNOWN)

C:\> run.bat
C:\> run.bat -b
C:\> run.bat "-b"
C:\> run.bat "a b"

(all of the above tests work correctly)

Named parameters in JDBC

Plain vanilla JDBC does not support named parameters.

If you are using DB2 then using DB2 classes directly:

  1. Using named parameter markers with PreparedStatement objects
  2. Using named parameter markers with CallableStatement objects

How to use background thread in swift?

Swift 3.0+

A lot has been modernized in Swift 3.0. Running something on the background thread looks like this:

DispatchQueue.global(qos: .background).async {
    print("This is run on the background queue")

    DispatchQueue.main.async {
        print("This is run on the main queue, after the previous code in outer block")
    }
}

Swift 1.2 through 2.3

let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
    print("This is run on the background queue")

    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        print("This is run on the main queue, after the previous code in outer block")
    })
})

Pre Swift 1.2 – Known issue

As of Swift 1.1 Apple didn't support the above syntax without some modifications. Passing QOS_CLASS_BACKGROUND didn't actually work, instead use Int(QOS_CLASS_BACKGROUND.value).

For more information see Apples documentation

Starting the week on Monday with isoWeekday()

Here is a more generic solution for any given weekday. Working demo on jsfiddle

var myIsoWeekDay = 2; // say our weeks start on tuesday, for monday you would type 1, etc.

var startOfPeriod = moment("2013-06-23T00:00:00"),

// how many days do we have to substract?
var daysToSubtract = moment(startOfPeriod).isoWeekday() >= myIsoWeekDay ?
    moment(startOfPeriod).isoWeekday() - myIsoWeekDay :
    7 + moment(startOfPeriod).isoWeekday() - myIsoWeekDay;

// subtract days from start of period
var begin = moment(startOfPeriod).subtract('d', daysToSubtract);

How can I capture the result of var_dump to a string?

If you want to have a look at a variable's contents during runtime, consider using a real debugger like XDebug. That way you don't need to mess up your source code, and you can use a debugger even while normal users visit your application. They won't notice.

Comparing two integer arrays in Java

Even though there is something easy like .equals, I'd like to point out TWO mistakes you made in your code. The first: when you go through the arrays, you say b is true or false. Then you start again to check, because of the for-loop. But each time you are giving b a value. So, no matter what happens, the value b gets set to is always the value of the LAST for-loop. Next time, set boolean b = true, if equal = true, do nothing, if equal = false, b=false.

Secondly, you are now checking each value in array1 with each value in array2. If I understand correctly, you only need to check the values at the same location in the array, meaning you should have deleted the second for-loop and check like this: if (array2[i] == array1[i]). Then your code should function as well.

Your code would work like this:

public static void compareArrays(int[] array1, int[] array2) {
    boolean b = true;
    for (int i = 0; i < array2.length; i++) {
        if (array2[i] == array1[i]) {
            System.out.println("true");
        } else {
            b = false;
            System.out.println("False");
        }
    } 
    return b;

}

But as said by other, easier would be: Arrays.equals(ary1,ary2);

Changing Locale within the app itself

If you want to effect on the menu options for changing the locale immediately.You have to do like this.

//onCreate method calls only once when menu is called first time.
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    //1.Here you can add your  locale settings . 
    //2.Your menu declaration.
}
//This method is called when your menu is opend to again....
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
    menu.clear();
    onCreateOptionsMenu(menu);
    return super.onMenuOpened(featureId, menu);
}

C++ Passing Pointer to Function (Howto) + C++ Pointer Manipulation

If you want to pass a pointer-to-int into your function,

Declaration of function (if you need it):

void Fun(int *ptr);

Definition of function:

void Fun(int *ptr) {
    int *other_pointer = ptr;  // other_pointer points to the same thing as ptr
    *other_ptr = 3;            // manipulate the thing they both point to
}

Use of function:

int main() {
    int x = 2;
    printf("%d\n", x);
    Fun(&x);
    printf("%d\n", x);
}

Note as a general rule, that variables called Ptr or Pointer should never have type int, which is what you have then in your code. A pointer-to-int has type int *.

If I have a second pointer (int *oof), then:

bar = oof means: bar points to the oof pointer

It means "make bar point to the same thing oof points to".

bar = *oof means: bar points to the value that oof points to, but not to the oof pointer itself

That doesn't mean anything, it's invalid. bar is a pointer *oof is an int. You can't assign one to the other.

*bar = *oof means: change the value that bar points to to the value that oof points to

Yes.

&bar = &oof means: change the memory address that bar points to be the same as the memory address that oof points to

Nope, that's invalid again. &bar is a pointer to the bar variable, but it is what's called an "rvalue", or "temporary", and it cannot be assigned to. It's like the result of an arithmetic calculation. You can't write x + 1 = 5.

It might help you to think of pointers as addresses. bar = oof means "make bar, which is an address, equal to oof, which is also an address". bar = &foo means "make bar, which is an address, equal to the address of foo". If bar = *oof meant anything, it would mean "make bar, which is an address, equal to *oof, which is an int". You can't.

Then, & is the address-of operator. It means "the address of the operand", so &foo is the address of foo (i.e, a pointer to foo). * is the dereference operator. It means "the thing at the address given by the operand". So having done bar = &foo, *bar is foo.

Create an array of integers property in Objective-C

Like lucius said, it's not possible to have a C array property. Using an NSArray is the way to go. An array only stores objects, so you'd have to use NSNumbers to store your ints. With the new literal syntax, initialising it is very easy and straight-forward:

NSArray *doubleDigits = @[ @1, @2, @3, @4, @5, @6, @7, @8, @9, @10 ];

Or:

NSMutableArray *doubleDigits = [NSMutableArray array];

for (int n = 1; n <= 10; n++)
    [doubleDigits addObject:@(n)];

For more information: NSArray Class Reference, NSNumber Class Reference, Literal Syntax

Solving "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection" InvalidOperationException

The CosisEntities class is your DbContext. When you create a context in a using block, you're defining the boundaries for your data-oriented operation.

In your code, you're trying to emit the result of a query from a method and then end the context within the method. The operation you pass the result to then tries to access the entities in order to populate the grid view. Somewhere in the process of binding to the grid, a lazy-loaded property is being accessed and Entity Framework is trying to perform a lookup to obtain the values. It fails, because the associated context has already ended.

You have two problems:

  1. You're lazy-loading entities when you bind to the grid. This means that you're doing lots of separate query operations to SQL Server, which are going to slow everything down. You can fix this issue by either making the related properties eager-loaded by default, or asking Entity Framework to include them in the results of this query by using the Include extension method.

  2. You're ending your context prematurely: a DbContext should be available throughout the unit of work being performed, only disposing it when you're done with the work at hand. In the case of ASP.NET, a unit of work is typically the HTTP request being handled.

JSON response parsing in Javascript to get key/value pair

There are two ways to access properties of objects:

var obj = {a: 'foo', b: 'bar'};

obj.a //foo
obj['b'] //bar

Or, if you need to dynamically do it:

var key = 'b';
obj[key] //bar

If you don't already have it as an object, you'll need to convert it.

For a more complex example, let's assume you have an array of objects that represent users:

var users = [{name: 'Corbin', age: 20, favoriteFoods: ['ice cream', 'pizza']},
             {name: 'John', age: 25, favoriteFoods: ['ice cream', 'skittle']}];

To access the age property of the second user, you would use users[1].age. To access the second "favoriteFood" of the first user, you'd use users[0].favoriteFoods[2].

Another example: obj[2].key[3]["some key"]

That would access the 3rd element of an array named 2. Then, it would access 'key' in that array, go to the third element of that, and then access the property name some key.


As Amadan noted, it might be worth also discussing how to loop over different structures.

To loop over an array, you can use a simple for loop:

var arr = ['a', 'b', 'c'],
    i;
for (i = 0; i < arr.length; ++i) {
    console.log(arr[i]);
}

To loop over an object is a bit more complicated. In the case that you're absolutely positive that the object is a plain object, you can use a plain for (x in obj) { } loop, but it's a lot safer to add in a hasOwnProperty check. This is necessary in situations where you cannot verify that the object does not have inherited properties. (It also future proofs the code a bit.)

var user = {name: 'Corbin', age: 20, location: 'USA'},
    key;

for (key in user) {
    if (user.hasOwnProperty(key)) {
        console.log(key + " = " + user[key]);
    }
}    

(Note that I've assumed whatever JS implementation you're using has console.log. If not, you could use alert or some kind of DOM manipulation instead.)

jQuery remove special characters from string and more

str.toLowerCase().replace(/[\*\^\'\!]/g, '').split(' ').join('-')

XMLHttpRequest (Ajax) Error

The problem is likely to lie with the line:

window.onload = onPageLoad();

By including the brackets you are saying onload should equal the return value of onPageLoad(). For example:

/*Example function*/
function onPageLoad()
{
    return "science";
}
/*Set on load*/
window.onload = onPageLoad()

If you print out the value of window.onload to the console it will be:

science

The solution is remove the brackets:

window.onload = onPageLoad;

So, you're using onPageLoad as a reference to the so-named function.

Finally, in order to get the response value you'll need a readystatechange listener for your XMLHttpRequest object, since it's asynchronous:

xmlDoc = xmlhttp.responseXML;
parser = new DOMParser(); // This code is untested as it doesn't run this far.

Here you add the listener:

xmlHttp.onreadystatechange = function() {
    if(this.readyState == 4) {
        // Do something
    }
}

What is difference between monolithic and micro kernel?

Monolithic kernel has all kernel services along with kernel core part, thus are heavy and has negative impact on speed and performance. On the other hand micro kernel is lightweight causing increase in performance and speed.
I answered same question at wordpress site. For the difference between monolithic, microkernel and exokernel in tabular form, you can visit here

What does it mean by select 1 from table?

This is just used for convenience with IF EXISTS(). Otherwise you can go with

select * from [table_name]

Image In the case of 'IF EXISTS', we just need know that any row with specified condition exists or not doesn't matter what is content of row.

select 1 from Users

above example code, returns no. of rows equals to no. of users with 1 in single column

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

In your application context, change the bean with id from emf to entityManagerFactory:

<bean id="emf"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="packagesToScan" value="org.wahid.cse.entity" />
    <property name="dataSource" ref="dataSource" />

    <property name="jpaProperties">
        <props>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
        </props>
    </property>

    <property name="persistenceProvider">
        <bean class="org.hibernate.jpa.HibernatePersistenceProvider"></bean>
    </property>

</bean>

To

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="packagesToScan" value="org.wahid.cse.entity" />
    <property name="dataSource" ref="dataSource" />

    <property name="jpaProperties">
        <props>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
        </props>
    </property>

    <property name="persistenceProvider">
        <bean class="org.hibernate.jpa.HibernatePersistenceProvider"></bean>
    </property>

</bean>

How to redirect to another page in node.js

@Nazar Medeiros - Your solution uses passport with Express. I am not using passport, just express-jwt. I might be doing something wrong, but when a user logs in, the token needs to return to the client side. From what I have found so far, this means we have to return a json with the token and therefor cannot call redirect. Is there something I am missing there?

To get around this, I simply return the token, store it in my cookies and then make a ajax GET request (with the valid token). When that ajax call returns I replace the body's html with the returned HTML. This is probably not the right way to do it, but I can't find a better way. Here is my JQuery JavaScript code.

function loginUser(){
  $.post("/users/login", {
    username: $( '#login_input_username' ).val(),
   password: $( '#login_input_password' ).val()
 }).done(function(res){
    document.cookie = "token = " + res.token;
    redirectToHome();
  })
}

function redirectToHome(){
  var settings = {
    "async": true,
    "crossDomain": true,
    "url": "/home",
    "type": "GET",
    "headers": {
      "authorization": "Bearer " + getCookie('token'),
      "cache-control": "no-cache"
    }
  }

  $.ajax(settings).done(function (response) {
    $('body').replaceWith(response);
  });
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

Using the star sign in grep

The asterisk is just a repetition operator, but you need to tell it what you repeat. /*abc*/ matches a string containing ab and zero or more c's (because the second * is on the c; the first is meaningless because there's nothing for it to repeat). If you want to match anything, you need to say .* -- the dot means any character (within certain guidelines). If you want to just match abc, you could just say grep 'abc' myFile. For your more complex match, you need to use .* -- grep 'abc.*def' myFile will match a string that contains abc followed by def with something optionally in between.

Update based on a comment:

* in a regular expression is not exactly the same as * in the console. In the console, * is part of a glob construct, and just acts as a wildcard (for instance ls *.log will list all files that end in .log). However, in regular expressions, * is a modifier, meaning that it only applies to the character or group preceding it. If you want * in regular expressions to act as a wildcard, you need to use .* as previously mentioned -- the dot is a wildcard character, and the star, when modifying the dot, means find one or more dot; ie. find one or more of any character.

Which font is used in Visual Studio Code Editor and how to change fonts?

The default fonts are different across Windows, Mac, and Linux. As of VSCode 1.15.1, the default font settings can be found in the source code:

const DEFAULT_WINDOWS_FONT_FAMILY = 'Consolas, \'Courier New\', monospace';
const DEFAULT_MAC_FONT_FAMILY = 'Menlo, Monaco, \'Courier New\', monospace';
const DEFAULT_LINUX_FONT_FAMILY = '\'Droid Sans Mono\', \'Courier New\', monospace, \'Droid Sans Fallback\'';

Jquery, Clear / Empty all contents of tbody element?

jQuery:

$("#tbodyid").empty();

HTML:

<table>
    <tbody id="tbodyid">
        <tr>
            <td>something</td>
        </tr>
    </tbody>
</table>

Works for me
http://jsfiddle.net/mbsh3/

Variables within app.config/web.config

I would suggest you DslConfig. With DslConfig you can use hierarchical config files from Global Config, Config per server host to config per application on each server host (see the AppSpike).
If this is to complicated for you you can just use the global config Variables.var
Just configure in Varibales.var

baseDir = "C:\MyBase"
Var["MyBaseDir"] = baseDir
Var["Dir1"] = baseDir + "\Dir1"
Var["Dir2"] = baseDir + "\Dir2"

And get the config values with

Configuration config = new DslConfig.BooDslConfiguration()
config.GetVariable<string>("MyBaseDir")
config.GetVariable<string>("Dir1")
config.GetVariable<string>("Dir2")

How to load a resource from WEB-INF directory of a web archive

Use the getResourceAsStream() method on the ServletContext object, e.g.

servletContext.getResourceAsStream("/WEB-INF/myfile");

How you get a reference to the ServletContext depends on your application... do you want to do it from a Servlet or from a JSP?

EDITED: If you're inside a Servlet object, then call getServletContext(). If you're in JSP, use the predefined variable application.

How to hide collapsible Bootstrap 4 navbar on click

The easiest way to do it using only Angular 2/4 template with no coding:

<nav class="navbar navbar-default" aria-expanded="false">
  <div class="container-wrapper">

    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" (click)="isCollapsed = !isCollapsed">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>

    <div class="navbar-collapse collapse no-transition" [attr.aria-expanded]="!isCollapsed" [ngClass]="{collapse: isCollapsed}">
      <ul class="nav navbar-nav" (click)="isCollapsed = !isCollapsed">
        <li [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact: true}"><a routerLink="/">Home</a></li>
        <li [routerLinkActive]="['active']"><a routerLink="/about">About</a></li>
        <li [routerLinkActive]="['active']"><a routerLink="/portfolio">Portfolio</a></li>
        <li [routerLinkActive]="['active']"><a routerLink="/contacts">Contacts</a></li>
      </ul>
    </div>

  </div>
</nav>

What is a Question Mark "?" and Colon ":" Operator Used for?

Thats an if/else statement equilavent to

if(row % 2 == 1){
  System.out.print("<");
}else{
  System.out.print("\r>");
}

Set disable attribute based on a condition for Html.TextBoxFor

if you dont want to use Html Helpers take look it my solution

disabled="@(your Expression that returns true or false")"

that it

@{
    bool isManager = (Session["User"] as User).IsManager;
}
<textarea rows="4" name="LetterManagerNotes" disabled="@(!isManager)"></textarea>

and I think the better way to do it is to do that check in the controller and save it within a variable that is accessible inside the view(Razor engine) in order to make the view free from business logic

How to press back button in android programmatically?

Simply add finish(); in your first class' (login activity) onPause(); method. that's all

Locate Git installation folder on Mac OS X

On Mojave

The binary is in

/usr/bin/git

The related scripts are here

/Applications/Xcode.app/Contents/Developer/usr/libexec/git-core/git

How do you represent a JSON array of strings?

I'll elaborate a bit more on ChrisR awesome answer and bring images from his awesome reference.

A valid JSON always starts with either curly braces { or square brackets [, nothing else.

{ will start an object:

left brace followed by a key string (a name that can't be repeated, in quotes), colon and a value (valid types shown below), followed by an optional comma to add more pairs of string and value at will and finished with a right brace

{ "key": value, "another key": value }

Hint: although javascript accepts single quotes ', JSON only takes double ones ".

[ will start an array:

left bracket followed by value, optional comma to add more value at will and finished with a right bracket

[value, value]

Hint: spaces among elements are always ignored by any JSON parser.

And value is an object, array, string, number, bool or null:

Image showing the 6 types a JSON value can be: string, number, JSON object, Array/list, boolean, and null

So yeah, ["a", "b"] is a perfectly valid JSON, like you could try on the link Manish pointed.

Here are a few extra valid JSON examples, one per block:

{}

[0]

{"__comment": "json doesn't accept comments and you should not be commenting even in this way", "avoid!": "also, never add more than one key per line, like this"}

[{   "why":null} ]

{
  "not true": [0, false],
  "true": true,
  "not null": [0, 1, false, true, {
    "obj": null
  }, "a string"]
}

Checking if a folder exists using a .bat file

For a file:

if exist yourfilename (
  echo Yes 
) else (
  echo No
)

Replace yourfilename with the name of your file.

For a directory:

if exist yourfoldername\ (
  echo Yes 
) else (
  echo No
)

Replace yourfoldername with the name of your folder.

A trailing backslash (\) seems to be enough to distinguish between directories and ordinary files.

print arraylist element?

If you want to print an arraylist with integer numbers, as an example you can use below code.

class Test{
    public static void main(String[] args){
        ArrayList<Integer> arraylist = new ArrayList<Integer>();

        for(int i=0; i<=10; i++){
            arraylist .add(i);
        }
       for (Integer n : arraylist ){
            System.out.println(n);
       }
   }
}

The output is above code:

0
1
2
3
4
5
6
7
8
9
10

JSON to string variable dump

You can use console.log() in Firebug or Chrome to get a good object view here, like this:

$.getJSON('my.json', function(data) {
  console.log(data);
});

If you just want to view the string, look at the Resource view in Chrome or the Net view in Firebug to see the actual string response from the server (no need to convert it...you received it this way).

If you want to take that string and break it down for easy viewing, there's an excellent tool here: http://json.parser.online.fr/

How can I use different certificates on specific connections?

I've had to do something like this when using commons-httpclient to access an internal https server with a self-signed certificate. Yes, our solution was to create a custom TrustManager that simply passed everything (logging a debug message).

This comes down to having our own SSLSocketFactory that creates SSL sockets from our local SSLContext, which is set up to have only our local TrustManager associated with it. You don't need to go near a keystore/certstore at all.

So this is in our LocalSSLSocketFactory:

static {
    try {
        SSL_CONTEXT = SSLContext.getInstance("SSL");
        SSL_CONTEXT.init(null, new TrustManager[] { new LocalSSLTrustManager() }, null);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Unable to initialise SSL context", e);
    } catch (KeyManagementException e) {
        throw new RuntimeException("Unable to initialise SSL context", e);
    }
}

public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    LOG.trace("createSocket(host => {}, port => {})", new Object[] { host, new Integer(port) });

    return SSL_CONTEXT.getSocketFactory().createSocket(host, port);
}

Along with other methods implementing SecureProtocolSocketFactory. LocalSSLTrustManager is the aforementioned dummy trust manager implementation.

Reading a string with scanf

An array "decays" into a pointer to its first element, so scanf("%s", string) is equivalent to scanf("%s", &string[0]). On the other hand, scanf("%s", &string) passes a pointer-to-char[256], but it points to the same place.

Then scanf, when processing the tail of its argument list, will try to pull out a char *. That's the Right Thing when you've passed in string or &string[0], but when you've passed in &string you're depending on something that the language standard doesn't guarantee, namely that the pointers &string and &string[0] -- pointers to objects of different types and sizes that start at the same place -- are represented the same way.

I don't believe I've ever encountered a system on which that doesn't work, and in practice you're probably safe. None the less, it's wrong, and it could fail on some platforms. (Hypothetical example: a "debugging" implementation that includes type information with every pointer. I think the C implementation on the Symbolics "Lisp Machines" did something like this.)

Create a dropdown component

If you want something with a dropdown (some list of values) and a user specified value that can be filled into the selected input as well. This custom dropdown in angular also has a filter dropdown list on key value entered. Please check this stackblitzlink -> https://stackblitz.com/edit/angular-l9guzo?embed=1&file=src/app/custom-textarea.component.ts

In CSS what is the difference between "." and "#" when declaring a set of styles?

.class targets the following element:

<div class="class"></div>

#class targets the following element:

<div id="class"></div>

Note that the id MUST be unique throughout the document, whilst any number of elements may share a class.

iOS 7 - Status bar overlaps the view

This is all that is needed to remove the status bar. enter image description here

Convert from ASCII string encoded in Hex to plain ASCII?

b''.fromhex('7061756c')

use it without delimiter

Fork() function in C

First a link to some documentation of fork()

http://pubs.opengroup.org/onlinepubs/009695399/functions/fork.html

The pid is provided by the kernel. Every time the kernel create a new process it will increase the internal pid counter and assign the new process this new unique pid and also make sure there are no duplicates. Once the pid reaches some high number it will wrap and start over again.

So you never know what pid you will get from fork(), only that the parent will keep it's unique pid and that fork will make sure that the child process will have a new unique pid. This is stated in the documentation provided above.

If you continue reading the documentation you will see that fork() return 0 for the child process and the new unique pid of the child will be returned to the parent. If the child want to know it's own new pid you will have to query for it using getpid().

pid_t pid = fork()
if(pid == 0) {
    printf("this is a child: my new unique pid is %d\n", getpid());
} else {
    printf("this is the parent: my pid is %d and I have a child with pid %d \n", getpid(), pid);
}

and below is some inline comments on your code

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

int main() {
    pid_t pid1, pid2, pid3;
    pid1=0, pid2=0, pid3=0;
    pid1= fork(); /* A */
    if(pid1 == 0){
        /* This is child A */
        pid2=fork(); /* B */
        pid3=fork(); /* C */
    } else {
        /* This is parent A */
        /* Child B and C will never reach this code */
        pid3=fork(); /* D */
        if(pid3==0) {
            /* This is child D fork'ed from parent A */
            pid2=fork(); /* E */
        }
        if((pid1 == 0)&&(pid2 == 0)) {
            /* pid1 will never be 0 here so this is dead code */
            printf("Level 1\n");
        }
        if(pid1 !=0) {
            /* This is always true for both parent and child E */
            printf("Level 2\n");
        }
        if(pid2 !=0) {
           /* This is parent E (same as parent A) */
           printf("Level 3\n");
        }
        if(pid3 !=0) {
           /* This is parent D (same as parent A) */
           printf("Level 4\n");
        }
    }
    return 0;
}

Passing the argument to CMAKE via command prompt

In the CMakeLists.txt file, create a cache variable, as documented here:

SET(FAB "po" CACHE STRING "Some user-specified option")

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#command:set

Then, either use the GUI (ccmake or cmake-gui) to set the cache variable, or specify the value of the variable on the cmake command line:

cmake -DFAB:STRING=po

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#opt:-Dvar:typevalue

Modify your cache variable to a boolean if, in fact, your option is boolean.

Android - How To Override the "Back" button so it doesn't Finish() my Activity?

I think what you want is not to override the back button (that just doesn't seem like a good idea - Android OS defines that behavior, why change it?), but to use the Activity Lifecycle and persist your settings/data in the onSaveInstanceState(Bundle) event.

@Override
onSaveInstanceState(Bundle frozenState) {
    frozenState.putSerializable("object_key",
        someSerializableClassYouWantToPersist);
    // etc. until you have everything important stored in the bundle
}

Then you use onCreate(Bundle) to get everything out of that persisted bundle and recreate your state.

@Override
onCreate(Bundle savedInstanceState) {
    if(savedInstanceState!=null){ //It could be null if starting the app.
        mCustomObject = savedInstanceState.getSerializable("object_key");
    }
    // etc. until you have reloaded everything you stored
}

Consider the above psuedo-code to point you in the right direction. Reading up on the Activity Lifecycle should help you determine the best way to accomplish what you're looking for.

Creating an object: with or without `new`

Both do different things.

The first creates an object with automatic storage duration. It is created, used, and then goes out of scope when the current block ({ ... }) ends. It's the simplest way to create an object, and is just the same as when you write int x = 0;

The second creates an object with dynamic storage duration and allows two things:

  • Fine control over the lifetime of the object, since it does not go out of scope automatically; you must destroy it explicitly using the keyword delete;

  • Creating arrays with a size known only at runtime, since the object creation occurs at runtime. (I won't go into the specifics of allocating dynamic arrays here.)

Neither is preferred; it depends on what you're doing as to which is most appropriate.

Use the former unless you need to use the latter.

Your C++ book should cover this pretty well. If you don't have one, go no further until you have bought and read, several times, one of these.

Good luck.


Your original code is broken, as it deletes a char array that it did not new. In fact, nothing newd the C-style string; it came from a string literal. deleteing that is an error (albeit one that will not generate a compilation error, but instead unpredictable behaviour at runtime).

Usually an object should not have the responsibility of deleteing anything that it didn't itself new. This behaviour should be well-documented. In this case, the rule is being completely broken.

Include another JSP file

1.<a href="index.jsp?p=products">Products</a> when user clicks on Products link,you can directly call products.jsp.

I mean u can maintain name of the JSP file same as parameter Value.

<%
 if(request.getParameter("p")!=null)
 { 
   String contextPath="includes/";
   String p = request.getParameter("p");
   p=p+".jsp";
   p=contextPath+p;

%>    

<%@include file="<%=p%>" %>

<% 
 }
%>

or

2.you can maintain external resource file with key,value pairs. like below

products : products.jsp

customer : customers.jsp

you can programatically retrieve the name of JSP file from properies file.

this way you can easily change the name of JSP file

How can I add a hint text to WPF textbox?

Do it in the code-behind by setting the text color initially to gray and adding event handlers for gaining and losing keyboard focus.

TextBox tb = new TextBox();
tb.Foreground = Brushes.Gray;
tb.Text = "Text";
tb.GotKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_GotKeyboardFocus);
tb.LostKeyboardFocus += new KeyboardFocusChangedEventHandler(tb_LostKeyboardFocus);

Then the event handlers:

private void tb_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    if(sender is TextBox)
    {
        //If nothing has been entered yet.
        if(((TextBox)sender).Foreground == Brushes.Gray)
        {
            ((TextBox)sender).Text = "";
            ((TextBox)sender).Foreground = Brushes.Black;
        }
    }
}


private void tb_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    //Make sure sender is the correct Control.
    if(sender is TextBox)
    {
        //If nothing was entered, reset default text.
        if(((TextBox)sender).Text.Trim().Equals(""))
        {
            ((TextBox)sender).Foreground = Brushes.Gray;
            ((TextBox)sender).Text = "Text";
        }
    }
}

getElementById in React

You need to have your function in the componentDidMount lifecycle since this is the function that is called when the DOM has loaded.

Make use of refs to access the DOM element

<input type="submit" className="nameInput" id="name" value="cp-dev1" onClick={this.writeData} ref = "cpDev1"/>

  componentDidMount: function(){
    var name = React.findDOMNode(this.refs.cpDev1).value;
    this.someOtherFunction(name);
  }

See this answer for more info on How to access the dom element in React

How to replace multiple patterns at once with sed?

I always use multiple statements with "-e"

$ sed -e 's:AND:\n&:g' -e 's:GROUP BY:\n&:g' -e 's:UNION:\n&:g' -e 's:FROM:\n&:g' file > readable.sql

This will append a '\n' before all AND's, GROUP BY's, UNION's and FROM's, whereas '&' means the matched string and '\n&' means you want to replace the matched string with an '\n' before the 'matched'

Default SecurityProtocol in .NET 4.5

If you can use .NET 4.7.1 or newer, it will use TLS 1.2 as the minimum protocol based on the operating system capabilities. Per Microsoft recommendation :

To ensure .NET Framework applications remain secure, the TLS version should not be hardcoded. .NET Framework applications should use the TLS version the operating system (OS) supports.

How can I style an Android Switch?

You can define the drawables that are used for the background, and the switcher part like this:

<Switch
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:thumb="@drawable/switch_thumb"
    android:track="@drawable/switch_bg" />

Now you need to create a selector that defines the different states for the switcher drawable. Here the copies from the Android sources:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/switch_thumb_disabled_holo_light" />
    <item android:state_pressed="true"  android:drawable="@drawable/switch_thumb_pressed_holo_light" />
    <item android:state_checked="true"  android:drawable="@drawable/switch_thumb_activated_holo_light" />
    <item                               android:drawable="@drawable/switch_thumb_holo_light" />
</selector>

This defines the thumb drawable, the image that is moved over the background. There are four ninepatch images used for the slider:

The deactivated version (xhdpi version that Android is using)The deactivated version
The pressed slider: The pressed slider
The activated slider (on state):The activated slider
The default version (off state): enter image description here

There are also three different states for the background that are defined in the following selector:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/switch_bg_disabled_holo_dark" />
    <item android:state_focused="true"  android:drawable="@drawable/switch_bg_focused_holo_dark" />
    <item                               android:drawable="@drawable/switch_bg_holo_dark" />
</selector>

The deactivated version: The deactivated version
The focused version: The focused version
And the default version:the default version

To have a styled switch just create this two selectors, set them to your Switch View and then change the seven images to your desired style.

How can I get a specific parameter from location.search?

My favorite way for getting URL params is this approach:

var parseQueryString = function() {

    var str = window.location.search;
    var objURL = {};

    str.replace(
        new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
        function( $0, $1, $2, $3 ){
            objURL[ $1 ] = $3;
        }
    );
    return objURL;
};

//Example how to use it: 
var params = parseQueryString();
alert(params["foo"]); 

Make a phone call programmatically

Probably the mymobileNO.titleLabel.text value doesn't include the scheme tel://

Your code should look like this:

NSString *phoneNumber = [@"tel://" stringByAppendingString:mymobileNO.titleLabel.text];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];

Wait till a Function with animations is finished until running another Function

This answer uses promises, a JavaScript feature of the ECMAScript 6 standard. If your target platform does not support promises, polyfill it with PromiseJs.

You can get the Deferred object jQuery creates for the animation using .promise() on the animation call. Wrapping these Deferreds into ES6 Promises results in much cleaner code than using timers.

You can also use Deferreds directly, but this is generally discouraged because they do not follow the Promises/A+ specification.

The resulting code would look like this:

var p1 = Promise.resolve($('#Content').animate({ opacity: 0.5 }, { duration: 500, queue: false }).promise());
var p2 = Promise.resolve($('#Content').animate({ marginLeft: "-100px" }, { duration: 2000, queue: false }).promise());
Promise.all([p1, p2]).then(function () {
    return $('#Content').animate({ width: 0 }, { duration: 500, queue: false }).promise();
});

Note that the function in Promise.all() returns the promise. This is where magic happens. If in a then call a promise is returned, the next then call will wait for that promise to be resolved before executing.

jQuery uses an animation queue for each element. So animations on the same element are executed synchronously. In this case you wouldn't have to use promises at all!

I have disabled the jQuery animation queue to demonstrate how it would work with promises.

Promise.all() takes an array of promises and creates a new Promise that finishes after all promises in the array finished.

Promise.race() also takes an array of promises, but finishes as soon as the first Promise finished.

Error when creating a new text file with python?

You can use open(name, 'a')

However, when you enter filename, use inverted commas on both sides, otherwise ".txt"cannot be added to filename

How is "mvn clean install" different from "mvn install"?

You can call more than one target goal with maven. mvn clean install calls clean first, then install. You have to clean manually, because clean is not a standard target goal and not executed automatically on every install.

clean removes the target folder - it deletes all class files, the java docs, the jars, reports and so on. If you don't clean, then maven will only "do what has to be done", like it won't compile classes when the corresponding source files haven't changed (in brief).

we call it target in ant and goal in maven