Programs & Examples On #Dto

DTO is an acronym for Data Transfer Object, a design pattern used in data transfer.

What is a Data Transfer Object (DTO)?

In general Value Objects should be Immutable. Like Integer or String objects in Java. We can use them for transferring data between software layers. If the software layers or services running in different remote nodes like in a microservices environment or in a legacy Java Enterprise App. We must make almost exact copies of two classes. This is the where we met DTOs.

|-----------|                                                   |--------------|
| SERVICE 1 |--> Credentials DTO >--------> Credentials DTO >-- | AUTH SERVICE |
|-----------|                                                   |--------------|

In legacy Java Enterprise Systems DTOs can have various EJB stuff in it.

I do not know this is a best practice or not but I personally use Value Objects in my Spring MVC/Boot Projects like this:

        |------------|         |------------------|                             |------------|
-> Form |            | -> Form |                  | -> Entity                   |            |
        | Controller |         | Service / Facade |                             | Repository |
<- View |            | <- View |                  | <- Entity / Projection View |            |
        |------------|         |------------------|                             |------------|

Controller layer doesn't know what are the entities are. It communicates with Form and View Value Objects. Form Objects has JSR 303 Validation annotations (for instance @NotNull) and View Value Objects have Jackson Annotations for custom serialization. (for instance @JsonIgnore)

Service layer communicates with repository layer via using Entity Objects. Entity objects have JPA/Hibernate/Spring Data annotations on it. Every layer communicates with only the lower layer. The inter-layer communication is prohibited because of circular/cyclic dependency.

User Service ----> XX CANNOT CALL XX ----> Order Service

Some ORM Frameworks have the ability of projection via using additional interfaces or classes. So repositories can return View objects directly. There for you do not need an additional transformation.

For instance this is our User entity:

@Entity
public final class User {
    private String id;
    private String firstname;
    private String lastname;
    private String phone;
    private String fax;
    private String address;
    // Accessors ...
}

But you should return a Paginated list of users that just include id, firstname, lastname. Then you can create a View Value Object for ORM projection.

public final class UserListItemView {
    private String id;
    private String firstname;
    private String lastname;
    // Accessors ...
}

You can easily get the paginated result from repository layer. Thanks to spring you can also use just interfaces for projections.

List<UserListItemView> find(Pageable pageable);

Don't worry for other conversion operations BeanUtils.copy method works just fine.

any tool for java object to object mapping?

You can also try mapping framework based on Dozer, but with Excel mapping declaration. They've got some tools and additional cool features. Check at http://openl-tablets.sf.net/mapper

Difference between DTO, VO, POJO, JavaBeans?

Basically,

DTO: "Data transfer objects " can travel between seperate layers in software architecture.

VO: "Value objects " hold a object such as Integer,Money etc.

POJO: Plain Old Java Object which is not a special object.

Java Beans: requires a Java Class to be serializable, have a no-arg constructor and a getter and setter for each field

Plain Old CLR Object vs Data Transfer Object

I wrote an article for that topic: DTO vs Value Object vs POCO.

In short:

  • DTO != Value Object
  • DTO ? POCO
  • Value Object ? POCO

Why can't I check if a 'DateTime' is 'Nothing'?

A way around this would be to use Object datatype instead:

Private _myDate As Object
Private Property MyDate As Date
    Get
        If IsNothing(_myDate) Then Return Nothing
        Return CDate(_myDate)
    End Get
    Set(value As Date)
        If date = Nothing Then
            _myDate = Nothing
            Return
        End If
        _myDate = value
     End Set
End Property

Then you can set the date to nothing like so:

MyDate = Nothing
Dim theDate As Date = MyDate
If theDate = Nothing Then
    'date is nothing
End If

Vendor code 17002 to connect to SQLDeveloper

I had the same Problem. I had start my Oracle TNS Listener, then it works normally again.

See LISTENER: TNS-12545 ... No such file or directory.

How do I get the collection of Model State Errors in ASP.NET MVC?

Putting together several answers from above, this is what I ended up using:

var validationErrors = ModelState.Values.Where(E => E.Errors.Count > 0)
    .SelectMany(E => E.Errors)
    .Select(E => E.ErrorMessage)
    .ToList();

validationErrors ends up being a List<string> that contains each error message. From there, it's easy to do what you want with that list.

enter image description here

Python strptime() and timezones?

Your time string is similar to the time format in rfc 2822 (date format in email, http headers). You could parse it using only stdlib:

>>> from email.utils import parsedate_tz
>>> parsedate_tz('Tue Jun 22 07:46:22 EST 2010')
(2010, 6, 22, 7, 46, 22, 0, 1, -1, -18000)

See solutions that yield timezone-aware datetime objects for various Python versions: parsing date with timezone from an email.

In this format, EST is semantically equivalent to -0500. Though, in general, a timezone abbreviation is not enough, to identify a timezone uniquely.

Disable scrolling in all mobile devices

In page header, add

<meta name="viewport" content="width=device-width, initial-scale=1, minimum-sacle=1, maximum-scale=1, user-scalable=no">

In page stylesheet, add

html, body {
  overflow-x: hidden;
  overflow-y: hidden;
}

It is both html and body!

Creating a textarea with auto-resize

You're using the higher value of the current clientHeight and the content scrollHeight. When you make the scrollHeight smaller by removing content, the calculated area can't get smaller because the clientHeight, previously set by style.height, is holding it open. You could instead take a max() of scrollHeight and a minimum height value you have predefined or calculated from textarea.rows.

In general you probably shouldn't really rely on scrollHeight on form controls. Apart from scrollHeight being traditionally less widely-supported than some of the other IE extensions, HTML/CSS says nothing about how form controls are implemented internally and you aren't guaranteed scrollHeight will be anything meaningful. (Traditionally some browsers have used OS widgets for the task, making CSS and DOM interaction on their internals impossible.) At least sniff for scrollHeight/clientHeight's existance before trying to enable the effect.

Another possible alternative approach to avoid the issue if it's important that it work more widely might be to use a hidden div sized to the same width as the textarea, and set in the same font. On keyup, you copy the text from the textarea to a text node in hidden div (remembering to replace '\n' with a line break, and escape '<'/'&' properly if you're using innerHTML). Then simply measuring the div's offsetHeight will give you the height you need.

How do I use CMake?

CMake takes a CMakeList file, and outputs it to a platform-specific build format, e.g. a Makefile, Visual Studio, etc.

You run CMake on the CMakeList first. If you're on Visual Studio, you can then load the output project/solution.

How can I find script's directory?

import os
script_dir = os.path.dirname(os.path.realpath(__file__)) + os.sep

How do I resize a Google Map with JavaScript after it has loaded?

The popular answer google.maps.event.trigger(map, "resize"); didn't work for me alone.

Here was a trick that assured that the page had loaded and that the map had loaded as well. By setting a listener and listening for the idle state of the map you can then call the event trigger to resize.

$(document).ready(function() {
    google.maps.event.addListener(map, "idle", function(){
        google.maps.event.trigger(map, 'resize'); 
    });
}); 

This was my answer that worked for me.

Can you use a trailing comma in a JSON object?

Simple, cheap, easy to read, and always works regardless of the specs.

$delimiter = '';
for ....  {
    print $delimiter.$whatever
    $delimiter = ',';
}

The redundant assignment to $delim is a very small price to pay. Also works just as well if there is no explicit loop but separate code fragments.

What's the best practice to round a float to 2 decimals?

//by importing Decimal format we can do...

import java.util.Scanner;
import java.text.DecimalFormat;
public class Average
{
public static void main(String[] args)
{
int sub1,sub2,sub3,total;
Scanner in = new Scanner(System.in);
System.out.print("Enter Subject 1 Marks : ");
sub1 = in.nextInt();
System.out.print("Enter Subject 2 Marks : ");
sub2 = in.nextInt();
System.out.print("Enter Subject 3 Marks : ");
sub3 = in.nextInt();
total = sub1 + sub2 + sub3;
System.out.println("Total Marks of Subjects = " + total);
res = (float)total;
average = res/3;
System.out.println("Before Rounding Decimal.. Average = " +average +"%");
DecimalFormat df = new DecimalFormat("###.##");
System.out.println("After Rounding Decimal.. Average = " +df.format(average)+"%");
}
}
/* Output
Enter Subject 1 Marks : 72
Enter Subject 2 Marks : 42
Enter Subject 3 Marks : 52
Total Marks of Subjects = 166
Before Rounding Decimal.. Average = 55.333332%
After Rounding Decimal.. Average = 55.33%
*/

/* Output
Enter Subject 1 Marks : 98
Enter Subject 2 Marks : 88
Enter Subject 3 Marks : 78
Total Marks of Subjects = 264
Before Rounding Decimal.. Average = 88.0%
After Rounding Decimal.. Average = 88%
*/

/* You can Find Avrerage values in two ouputs before rounding average
And After rounding Average..*/

How much overhead does SSL impose?

Assuming you don't count connection set-up (as you indicated in your update), it strongly depends on the cipher chosen. Network overhead (in terms of bandwidth) will be negligible. CPU overhead will be dominated by cryptography. On my mobile Core i5, I can encrypt around 250 MB per second with RC4 on a single core. (RC4 is what you should choose for maximum performance.) AES is slower, providing "only" around 50 MB/s. So, if you choose correct ciphers, you won't manage to keep a single current core busy with the crypto overhead even if you have a fully utilized 1 Gbit line. [Edit: RC4 should not be used because it is no longer secure. However, AES hardware support is now present in many CPUs, which makes AES encryption really fast on such platforms.]

Connection establishment, however, is different. Depending on the implementation (e.g. support for TLS false start), it will add round-trips, which can cause noticable delays. Additionally, expensive crypto takes place on the first connection establishment (above-mentioned CPU could only accept 14 connections per core per second if you foolishly used 4096-bit keys and 100 if you use 2048-bit keys). On subsequent connections, previous sessions are often reused, avoiding the expensive crypto.

So, to summarize:

Transfer on established connection:

  • Delay: nearly none
  • CPU: negligible
  • Bandwidth: negligible

First connection establishment:

  • Delay: additional round-trips
  • Bandwidth: several kilobytes (certificates)
  • CPU on client: medium
  • CPU on server: high

Subsequent connection establishments:

  • Delay: additional round-trip (not sure if one or multiple, may be implementation-dependant)
  • Bandwidth: negligible
  • CPU: nearly none

How can I view the contents of an ElasticSearch index?

I can recommend Elasticvue, which is modern, free and open source. It allows accessing your ES instance via browser add-ons quite easily (supports Firefox, Chrome, Edge). But there are also further ways.

Just make sure you set cors values in elasticsearch.yml appropiate.

Android: View.setID(int id) programmatically - how to avoid ID conflicts?

inspired by @dilettante answer, here's my solution as an extension function in kotlin:

/* sets a valid id that isn't in use */
fun View.findAndSetFirstValidId() {
    var i: Int
    do {
        i = Random.nextInt()
    } while (findViewById<View>(i) != null)
    id = i
}

No input file specified

Citing http://support.statamic.com/kb/hosting-servers/running-on-godaddy :

If you want to use GoDaddy as a host and you find yourself getting "No input file specified" errors in the control panel, you'll need to create a php5.ini file in your weboot with the following rule:

cgi.fix_pathinfo = 1

best easy answer just one line change and you are all set.

recommended for godaddy hosting.

How can I install MacVim on OS X?

  • Step 1. Install homebrew from here: http://brew.sh
  • Step 1.1. Run export PATH=/usr/local/bin:$PATH
  • Step 2. Run brew update
  • Step 3. Run brew install vim && brew install macvim
  • Step 4. Run brew link macvim

You now have the latest versions of vim and macvim managed by brew. Run brew update && brew upgrade every once in a while to upgrade them.

This includes the installation of the CLI mvim and the mac application (which both point to the same thing).

I use this setup and it works like a charm. Brew even takes care of installing vim with the preferable options.

How to return a value from pthread threads in C?

You are returning the address of a local variable, which no longer exists when the thread function exits. In any case, why call pthread_exit? why not simply return a value from the thread function?

void *myThread()
{
   return (void *) 42;
}

and then in main:

printf("%d\n",(int)status);   

If you need to return a complicated value such a structure, it's probably easiest to allocate it dynamically via malloc() and return a pointer. Of course, the code that initiated the thread will then be responsible for freeing the memory.

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

I suspect that the problem lies in the fact that you are calling your state setter immediately inside the function component body, which forces React to re-invoke your function again, with the same props, which ends up calling the state setter again, which triggers React to call your function again.... and so on.

const SingInContainer = ({ message, variant}) => {
    const [open, setSnackBarState] = useState(false);
    const handleClose = (reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setSnackBarState(false)

      };

    if (variant) {
        setSnackBarState(true); // HERE BE DRAGONS
    }
    return (
        <div>
        <SnackBar
            open={open}
            handleClose={handleClose}
            variant={variant}
            message={message}
            />
        <SignInForm/>
        </div>
    )
}

Instead, I recommend you just conditionally set the default value for the state property using a ternary, so you end up with:

const SingInContainer = ({ message, variant}) => {
    const [open, setSnackBarState] = useState(variant ? true : false); 
                                  // or useState(!!variant); 
                                  // or useState(Boolean(variant));
    const handleClose = (reason) => {
        if (reason === 'clickaway') {
          return;
        }
        setSnackBarState(false)

      };

    return (
        <div>
        <SnackBar
            open={open}
            handleClose={handleClose}
            variant={variant}
            message={message}
            />
        <SignInForm/>
        </div>
    )
}

Comprehensive Demo

See this CodeSandbox.io demo for a comprehensive demo of it working, plus the broken component you had, and you can toggle between the two.

Get user profile picture by Id

This will be helpful link:

http://graph.facebook.com/893914824028397/picture?type=large&redirect=true&width=500&height=500

You can set height and width as you needed

893914824028397 is facebookid

What is the difference between HTML tags and elements?

HTML Elements

An HTML element usually consists of a start tag and end tag, with the content inserted in between:

<tagname>Content goes here...</tagname>

The HTML element is everything from the start tag to the end tag. Source

HTML Attributes

An attribute is used to define the characteristics of an HTML element and is placed inside the element's opening tag. All attributes are made up of two parts: a name and a value.

  • All HTML elements can have attributes
  • Attributes provide additional information about an element
  • Attributes are always specified in the start tag
  • Attributes usually come in name/value pairs like: name="value" Source

HTML Tag vs Element

"Elements" and "tags" are terms that are widely confused. HTML documents contain tags, but do not contain the elements. The elements are only generated after the parsing step, from these tags. Source: wikipedia > HTML_element

An HTML element is defined by a starting tag. If the element contains other content, it ends with a closing tag.

For example <p> is starting tag of a paragraph and </p> is closing tag of the same paragraph but <p>This is paragraph</p> is a paragraph element.

Source:tutorialspoint > html_elements

Can Twitter Bootstrap alerts fade in as well as out?

None of the current answers worked for me. I'm using Bootstrap 3.

I liked what Rob Vermeer was doing and started from his response.

For a fade in and then fade out effect, I just used wrote the following function and used jQuery:

Html on my page to add the alert(s) to:

        <div class="alert-messages text-center">
        </div>

Javascript function to show and dismiss the alert.

function showAndDismissAlert(type, message) {
    var htmlAlert = '<div class="alert alert-' + type + '">' + message + '</div>';

    // Prepend so that alert is on top, could also append if we want new alerts to show below instead of on top.
    $(".alert-messages").prepend(htmlAlert);

    // Since we are prepending, take the first alert and tell it to fade in and then fade out.
    // Note: if we were appending, then should use last() instead of first()
    $(".alert-messages .alert").first().hide().fadeIn(200).delay(2000).fadeOut(1000, function () { $(this).remove(); });
}

Then, to show and dismiss the alert, just call the function like this:

    showAndDismissAlert('success', 'Saved Successfully!');
    showAndDismissAlert('danger', 'Error Encountered');
    showAndDismissAlert('info', 'Message Received');

As a side note, I styled the div.alert-messages fixed on top:

    <style>
    div.alert-messages {
        position: fixed;
        top: 50px;
        left: 25%;
        right: 25%;
        z-index: 7000;
    }
    </style>

Setting SMTP details for php mail () function

Try from your dedicated server to telnet to smtp.gmail.com on port 465. It might be blocked by your internet provider

Bootstrap dropdown not working

Try this code:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Bootstrap Tutorial</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
</head>
<body>
    <h1>Welcome to Bootstrap</h1>
    <div class="dropdown">
        <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            Dropdown button
        </button>
        <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
            <a class="dropdown-item" href="#">Action</a>
            <a class="dropdown-item" href="#">Another action</a>
            <a class="dropdown-item" href="#">Something else here</a>
        </div>
    </div>


    <script src="https://code.jquery.com/jquery.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</body>
</html>

javascript variable reference/alias

edit to my previous answer: if you want to count a function's invocations, you might want to try:

var countMe = ( function() {
  var c = 0;

  return function() {
    c++;
    return c;
  }
})();

alert(countMe()); // Alerts "1"
alert(countMe()); // Alerts "2"

Here, c serves as the counter, and you do not have to use arguments.callee.

DECODE( ) function in SQL Server

In my Case I used it in a lot of places first example if you have 2 values for select statement like gender (Male or Female) then use the following statement:

SELECT CASE Gender WHEN 'Male' THEN 1 ELSE 2 END AS Gender

If there is more than one condition like nationalities you can use it as the following statement:

SELECT CASE Nationality 
WHEN 'AMERICAN'   THEN 1 
WHEN 'BRITISH'   THEN 2
WHEN 'GERMAN'    THEN 3 
WHEN 'EGYPT'     THEN 4 
WHEN 'PALESTINE' THEN 5 
ELSE 6 END AS Nationality 

How to parse a text file with C#

One way that I've found really useful in situations like this is to go old-school and use the Jet OLEDB provider, together with a schema.ini file to read large tab-delimited files in using ADO.Net. Obviously, this method is really only useful if you know the format of the file to be imported.

public void ImportCsvFile(string filename)
{
    FileInfo file = new FileInfo(filename);

    using (OleDbConnection con = 
            new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
            file.DirectoryName + "\";
            Extended Properties='text;HDR=Yes;FMT=TabDelimited';"))
    {
        using (OleDbCommand cmd = new OleDbCommand(string.Format
                                  ("SELECT * FROM [{0}]", file.Name), con))
        {
            con.Open();

            // Using a DataReader to process the data
            using (OleDbDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    // Process the current reader entry...
                }
            }

            // Using a DataTable to process the data
            using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
            {
                DataTable tbl = new DataTable("MyTable");
                adp.Fill(tbl);

                foreach (DataRow row in tbl.Rows)
                {
                    // Process the current row...
                }
            }
        }
    }
} 

Once you have the data in a nice format like a datatable, filtering out the data you need becomes pretty trivial.

Check file extension in upload form in PHP

Not sure if this would have a faster computational time, but another option...

$acceptedFormats = array('gif', 'png', 'jpg');

if(!in_array(pathinfo($filename, PATHINFO_EXTENSION), $acceptedFormats))) {
    echo 'error';
}

How to install a specific version of a package with pip?

Use ==:

pip install django_modeltranslation==0.4.0-beta2

How to filter JSON Data in JavaScript or jQuery?

You can use jQuery each function as it is explained below:

Define your data:

var jsonStr = '[{"name":"Lenovo Thinkpad 41A4298,"website":"google"},{"name":"Lenovo Thinkpad 41A2222,"website":"google"},{"name":"Lenovo Thinkpad 41Awww33,"website":"yahoo"},{"name":"Lenovo Thinkpad 41A424448,"website":"google"},{"name":"Lenovo Thinkpad 41A429rr8,"website":"ebay"},{"name":"Lenovo Thinkpad 41A429ff8,"website":"ebay"},{"name":"Lenovo Thinkpad 41A429ss8,"website":"rediff"},{"name":"Lenovo Thinkpad 41A429sg8,"website":"yahoo"}]';

Parse JSON string to JSON object:

var json = JSON.parse(jsonStr);

Iterate and filter:

$.each(JSON.parse(json), function (idx, obj) {
    if (obj.website == 'yahoo') {
        // do whatever you want
    }
});

window.onload vs <body onload=""/>

window.onload = myOnloadFunc and <body onload="myOnloadFunc();"> are different ways of using the same event. Using window.onload is less obtrusive though - it takes your JavaScript out of the HTML.

All of the common JavaScript libraries, Prototype, ExtJS, Dojo, JQuery, YUI, etc. provide nice wrappers around events that occur as the document is loaded. You can listen for the window onLoad event, and react to that, but onLoad is not fired until all resources have been downloaded, so your event handler won't be executed until that last huge image has been fetched. In some cases that's exactly what you want, in others you might find that listening for when the DOM is ready is more appropriate - this event is similar to onLoad but fires without waiting for images, etc. to download.

Resource interpreted as stylesheet but transferred with MIME type text/html (seems not related with web server)

I want to expand on Todd R's point in the OP. In asp.net pages, the web.config file defines permissions needed to access each file or folder in the application. In our case, the folder of CSS files did not allow access for unauthorized users, causing it to fail on the login page before the user was authorized. Changing the required permissions in web.config allowed unauthorized users to access the CSS files and solved this problem.

How can I set multiple CSS styles in JavaScript?

I think is this a very simple way with regards to all solutions above:

const elm = document.getElementById("myElement")

const allMyStyle = [
  { prop: "position", value: "fixed" },
  { prop: "boxSizing", value: "border-box" },
  { prop: "opacity", value: 0.9 },
  { prop: "zIndex", value: 1000 },
];

allMyStyle.forEach(({ prop, value }) => {
  elm.style[prop] = value;
});

Is there a way to detect if a browser window is not currently active?

This is an adaptation of the answer from Andy E.

This will do a task e.g. refresh the page every 30 seconds, but only if the page is visible and focused.

If visibility can't be detected, then only focus will be used.

If the user focuses the page, then it will update immediately

The page won't update again until 30 seconds after any ajax call

var windowFocused = true;
var timeOut2 = null;

$(function(){
  $.ajaxSetup ({
    cache: false
  });
  $("#content").ajaxComplete(function(event,request, settings){
       set_refresh_page(); // ajax call has just been made, so page doesn't need updating again for 30 seconds
   });
  // check visibility and focus of window, so as not to keep updating unnecessarily
  (function() {
      var hidden, change, vis = {
              hidden: "visibilitychange",
              mozHidden: "mozvisibilitychange",
              webkitHidden: "webkitvisibilitychange",
              msHidden: "msvisibilitychange",
              oHidden: "ovisibilitychange" /* not currently supported */
          };
      for (hidden in vis) {
          if (vis.hasOwnProperty(hidden) && hidden in document) {
              change = vis[hidden];
              break;
          }
      }
      document.body.className="visible";
      if (change){     // this will check the tab visibility instead of window focus
          document.addEventListener(change, onchange,false);
      }

      if(navigator.appName == "Microsoft Internet Explorer")
         window.onfocus = document.onfocusin = document.onfocusout = onchangeFocus
      else
         window.onfocus = window.onblur = onchangeFocus;

      function onchangeFocus(evt){
        evt = evt || window.event;
        if (evt.type == "focus" || evt.type == "focusin"){
          windowFocused=true; 
        }
        else if (evt.type == "blur" || evt.type == "focusout"){
          windowFocused=false;
        }
        if (evt.type == "focus"){
          update_page();  // only update using window.onfocus, because document.onfocusin can trigger on every click
        }

      }

      function onchange () {
        document.body.className = this[hidden] ? "hidden" : "visible";
        update_page();
      }

      function update_page(){
        if(windowFocused&&(document.body.className=="visible")){
          set_refresh_page(1000);
        }
      }


  })();
  set_refresh_page();
})

function get_date_time_string(){
  var d = new Date();
  var dT = [];
  dT.push(d.getDate());
  dT.push(d.getMonth())
  dT.push(d.getFullYear());
  dT.push(d.getHours());
  dT.push(d.getMinutes());
  dT.push(d.getSeconds());
  dT.push(d.getMilliseconds());
  return dT.join('_');
}

function do_refresh_page(){

// do tasks here

// e.g. some ajax call to update part of the page.

// (date time parameter will probably force the server not to cache)

//      $.ajax({
//        type: "POST",
//        url: "someUrl.php",
//        data: "t=" + get_date_time_string()+"&task=update",
//        success: function(html){
//          $('#content').html(html);
//        }
//      });

}

function set_refresh_page(interval){
  interval = typeof interval !== 'undefined' ? interval : 30000; // default time = 30 seconds
  if(timeOut2 != null) clearTimeout(timeOut2);
  timeOut2 = setTimeout(function(){
    if((document.body.className=="visible")&&windowFocused){
      do_refresh_page();
    }
    set_refresh_page();
  }, interval);
}

How is returning the output of a function different from printing it?

Unfortunately, there is a character limit so this will be in many parts. First thing to note is that return and print are statements, not functions, but that is just semantics.

I’ll start with a basic explanation. print just shows the human user a string representing what is going on inside the computer. The computer cannot make use of that printing. return is how a function gives back a value. This value is often unseen by the human user, but it can be used by the computer in further functions.

On a more expansive note, print will not in any way affect a function. It is simply there for the human user’s benefit. It is very useful for understanding how a program works and can be used in debugging to check various values in a program without interrupting the program.

return is the main way that a function returns a value. All functions will return a value, and if there is no return statement (or yield but don’t worry about that yet), it will return None. The value that is returned by a function can then be further used as an argument passed to another function, stored as a variable, or just printed for the benefit of the human user. Consider these two programs:

def function_that_prints():
    print "I printed"

def function_that_returns():
    return "I returned"

f1 = function_that_prints()
f2 = function_that_returns()

print "Now let us see what the values of f1 and f2 are"

print f1 --->None

print f2---->"I returned"

When function_that_prints ran, it automatically printed to the console "I printed". However, the value stored in f1 is None because that function had no return statement.

When function_that_returns ran, it did not print anything to the console. However, it did return a value, and that value was stored in f2. When we printed f2 at the end of the code, we saw "I returned"

Reading specific XML elements from XML file

This is how I would do it (the code below has been tested, full source provided below), begin by creating a class with common properties

    class Word
    {
        public string Base { get; set; }
        public string Category { get; set; }
        public string Id { get; set; }
    }

load using XDocument with INPUT_DATA for demonstration purposes and find element name with lexicon . . .

    XDocument doc = XDocument.Parse(INPUT_DATA);
    XElement lex = doc.Element("lexicon");

make sure there is a value and use linq to extract the word elements from it . . .

    Word[] catWords = null;
    if (lex != null)
    {
        IEnumerable<XElement> words = lex.Elements("word");
        catWords = (from itm in words
                    where itm.Element("category") != null
                        && itm.Element("category").Value == "verb"
                        && itm.Element("id") != null
                        && itm.Element("base") != null
                    select new Word() 
                    {
                        Base = itm.Element("base").Value,
                        Category = itm.Element("category").Value,
                        Id = itm.Element("id").Value,
                    }).ToArray<Word>();
    }

The where statement checks if the category element exists and that the category value is not null and then check it again that it is a verb. Then check that the other nodes also exists . . .

The linq query will return an IEnumerable< Typename > object, so we can call ToArray< Typename >() to cast the entire collection into the type we want.

Then print it to get . . .

[Found]
 Id: E0006429
 Base: abandon
 Category: verb

[Found]
 Id: E0006524
 Base: abolish
 Category: verb

Full Source:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace test
{
    class Program
    {

        class Word
        {
            public string Base { get; set; }
            public string Category { get; set; }
            public string Id { get; set; }
        }

        static void Main(string[] args)
        {
            XDocument doc = XDocument.Parse(INPUT_DATA);
            XElement lex = doc.Element("lexicon");
            Word[] catWords = null;
            if (lex != null)
            {
                IEnumerable<XElement> words = lex.Elements("word");
                catWords = (from itm in words
                            where itm.Element("category") != null
                                && itm.Element("category").Value == "verb"
                                && itm.Element("id") != null
                                && itm.Element("base") != null
                            select new Word() 
                            {
                                Base = itm.Element("base").Value,
                                Category = itm.Element("category").Value,
                                Id = itm.Element("id").Value,
                            }).ToArray<Word>();
            }

            //print it
            if (catWords != null)
            {
                Console.WriteLine("Words with <category> and value verb:\n");
                foreach (Word itm in catWords)
                    Console.WriteLine("[Found]\n Id: {0}\n Base: {1}\n Category: {2}\n", 
                        itm.Id, itm.Base, itm.Category);
            }
        }

        const string INPUT_DATA =
        @"<?xml version=""1.0""?>
        <lexicon>
        <word>
          <base>a</base>
          <category>determiner</category>
          <id>E0006419</id>
        </word>
        <word>
          <base>abandon</base>
          <category>verb</category>
          <id>E0006429</id>
          <ditransitive/>
          <transitive/>
        </word>
        <word>
          <base>abbey</base>
          <category>noun</category>
          <id>E0203496</id>
        </word>
        <word>
          <base>ability</base>
          <category>noun</category>
          <id>E0006490</id>
        </word>
        <word>
          <base>able</base>
          <category>adjective</category>
          <id>E0006510</id>
          <predicative/>
          <qualitative/>
        </word>
        <word>
          <base>abnormal</base>
          <category>adjective</category>
          <id>E0006517</id>
          <predicative/>
          <qualitative/>
        </word>
        <word>
          <base>abolish</base>
          <category>verb</category>
          <id>E0006524</id>
          <transitive/>
        </word>
        </lexicon>";

    }
}

Does SVG support embedding of bitmap images?

Yes, you can reference any image from the image element. And you can use data URIs to make the SVG self-contained. An example:

<svg xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink">

    ...
    <image
        width="100" height="100"
        xlink:href="data:image/png;base64,IMAGE_DATA"
        />
    ...
</svg>

The svg element attribute xmlns:xlink declares xlink as a namespace prefix and says where the definition is. That then allows the SVG reader to know what xlink:href means.

The IMAGE_DATA is where you'd add the image data as base64-encoded text. Vector graphics editors that support SVG usually have an option for saving with images embedded. Otherwise there are plenty of tools around for encoding a byte stream to and from base64.

Here's a full example from the SVG testsuite.

HTML Code for text checkbox '?'

Use the Unicode Character

&#10004;   =   ✔


OpenJDK8 for windows

Go to this link

Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download

Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.

JDK vs OpenJDK

Simple and clean way to convert JSON string to Object in Swift

I like RDC's response, but why limit the JSON returned to have only arrays at the top level? I needed to allow a dictionary at the top level, so I modified it thus:

extension String
{
    var parseJSONString: AnyObject?
    {
        let data = self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)

        if let jsonData = data
        {
            // Will return an object or nil if JSON decoding fails
            do
            {
                let message = try NSJSONSerialization.JSONObjectWithData(jsonData, options:.MutableContainers)
                if let jsonResult = message as? NSMutableArray {
                    return jsonResult //Will return the json array output
                } else if let jsonResult = message as? NSMutableDictionary {
                    return jsonResult //Will return the json dictionary output
                } else {
                    return nil
                }
            }
            catch let error as NSError
            {
                print("An error occurred: \(error)")
                return nil
            }
        }
        else
        {
            // Lossless conversion of the string was not possible
            return nil
        }
    }

Insert at first position of a list in Python

From the documentation:

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a),x) is equivalent to a.append(x)

http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

Get the first item from an iterable that matches a condition

I would write this

next(x for x in xrange(10) if x > 3)

Concatenating Column Values into a Comma-Separated List

Please try this with the following code:

DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+',' , '') + CarName
FROM Cars
SELECT @listStr

Get Row Index on Asp.net Rowcommand event

this is answer for your question.

GridViewRow gvr = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;

int RowIndex = gvr.RowIndex; 

Replace all non-alphanumeric characters in a string

The pythonic way.

print "".join([ c if c.isalnum() else "*" for c in s ])

This doesn't deal with grouping multiple consecutive non-matching characters though, i.e.

"h^&i => "h**i not "h*i" as in the regex solutions.

Detecting when Iframe content has loaded (Cross browser)

For those using React, detecting a same-origin iframe load event is as simple as setting onLoad event listener on iframe element.

<iframe src={'path-to-iframe-source'} onLoad={this.loadListener} frameBorder={0} />

MySQL INSERT INTO table VALUES.. vs INSERT INTO table SET

I think the extension is intended to allow a similar syntax for inserts and updates. In Oracle, a similar syntactical trick is:

UPDATE table SET (col1, col2) = (SELECT val1, val2 FROM dual)

How to delete a file via PHP?

Check your permissions first of all on the file, to make sure you can a) see it from your script, and b) are able to delete it.

You can also use a path calculated from the directory you're currently running the script in, eg:

unlink(dirname(__FILE__) . "/../../public_files/" . $filename);

(in PHP 5.3 I believe you can use the __DIR__ constant instead of dirname() but I've not used it myself yet)

Can I scroll a ScrollView programmatically in Android?

I was using the Runnable with sv.fullScroll(View.FOCUS_DOWN); It works perfectly for the immediate problem, but that method makes ScrollView take the Focus from the entire screen, if you make that AutoScroll to happen every time, no EditText will be able to receive information from the user, my solution was use a different code under the runnable:

sv.scrollTo(0, sv.getBottom() + sv.getScrollY());

making the same without losing focus on important views

greetings.

How to toggle a boolean?

bool = !bool;

This holds true in most languages.

How to make Java work with SQL Server?

Have you tried the jtds driver for SQLServer?

What's the fastest way to loop through an array in JavaScript?

This looks to be the fastest way by far...

var el;
while (el = arr.shift()) {
  el *= 2;
}

Take into account that this will consume the array, eating it, and leaving nothing left...

How to install a Python module via its setup.py in Windows?

setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").

From the command line, you can type

python setup.py --help

...to get a list of commands. What you are looking to do is...

python setup.py install

Connection string with relative path to the database file

Relative to what, your application ? If so then you can simply get the applications current Path with :

System.Environment.CurrentDirectory 

And append it to the connection string

Why is this error, 'Sequence contains no elements', happening?

In the following line.

temp.Response = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();

You are calling First but the collection returned from db.Responses.Where is empty.

jQuery datepicker years shown

what no one else has put is that you can also set hard-coded date ranges:

for example:

yearRange: "1901:2012"

whilst it may be advisable to not do this, it is however, an option that is perfectly valid (and useful if you are legitimately looking for say a specific year in a catalogue - such as "1963:1984" ).

How to determine if string contains specific substring within the first X characters

Or if you need to set the value of found:

found = Value1.StartsWith("abc")

Edit: Given your edit, I would do something like:

found = Value1.Substring(0, 5).Contains("abc")

Set value of textbox using JQuery

You're targeting the wrong item with that jQuery selector. The name of your search bar is searchBar, not the id. What you want to use is $('#main_search').val('hi').

How can I pad an integer with zeros on the left?

If you for any reason use pre 1.5 Java then may try with Apache Commons Lang method

org.apache.commons.lang.StringUtils.leftPad(String str, int size, '0')

batch file to copy files to another location?

Open Notepad.

Type the following lines into it (obviously replace the folders with your ones)

@echo off
rem you could also remove the line above, because it might help you to see what happens

rem /i option is needed to avoid the batch file asking you whether destination folder is a file or a folder
rem /e option is needed to copy also all folders and subfolders
xcopy "c:\New Folder" "c:\Copy of New Folder" /i /e

Save the file as backup.bat (not .txt)

Double click on the file to run it. It will backup the folder and all its contents files/subfolders.

Now if you want the batch file to be run everytime you login in Windows, you should place it in Windows Startup menu. You find it under: Start > All Program > Startup To place the batch file in there either drag it into the Startup menu or RIGH click on the Windows START button and select Explore, go in Programs > Startup, and copy the batch file into there.

To run the batch file everytime the folder is updated you need an application, it can not be done with just a batch file.

Explicit vs implicit SQL joins

Personally I prefer the join syntax as its makes it clearer that the tables are joined and how they are joined. Try compare larger SQL queries where you selecting from 8 different tables and you have lots of filtering in the where. By using join syntax you separate out the parts where the tables are joined, to the part where you are filtering the rows.

Append data to a POST NSURLRequest

All the changes to the NSMutableURLRequest must be made before calling NSURLConnection.

I see this problem as I copy and paste the code above and run TCPMon and see the request is GET instead of the expected POST.

NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                     cachePolicy:NSURLRequestUseProtocolCachePolicy
                                 timeoutInterval:60.0];


[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request 
                                                         delegate:self];

Finding square root without using sqrt function?

if you need to find square root without using sqrt(),use root=pow(x,0.5).

Where x is value whose square root you need to find.

How do I run pip on python for windows?

I have a Mac, but luckily this should work the same way:

pip is a command-line thing. You don't run it in python.

For example, on my Mac, I just say:

$pip install somelib

pretty easy!

What is the difference between Serialization and Marshaling?

Marshalling is the rule to tell compiler how the data will be represented on another environment/system; For example;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string cFileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string cAlternateFileName;

as you can see two different string values represented as different value types.

Serialization will only convert object content, not representation (will stay same) and obey rules of serialization, (what to export or no). For example, private values will not be serialized, public values yes and object structure will stay same.

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

For nodejs use the below code

res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');

Open file in a relative location in Python

With this type of thing you need to be careful what your actual working directory is. For example, you may not run the script from the directory the file is in. In this case, you can't just use a relative path by itself.

If you are sure the file you want is in a subdirectory beneath where the script is actually located, you can use __file__ to help you out here. __file__ is the full path to where the script you are running is located.

So you can fiddle with something like this:

import os
script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)

What does {0} mean when found in a string in C#?

For future reference, in Visual Studio you can try placing the cursor in the method name (for example, WriteLine) and press F1 to pull up help on that context. Digging around should then find you String.Format() in this case, with lots of helpful information.

Note that highlighting a selection (for example, double-clicking or doing a drag-select) and hitting F1 only does a non-context string search (which tends to suck at finding anything helpful), so make sure you just position the cursor anywhere inside the word without highlighting it.

This is also helpful for documentation on classes and other types.

How do I create an executable in Visual Studio 2013 w/ C++?

Do ctrl+F5 to compile and run your project without debugging. Look at the output pane (defaults to "Show output from Build"). If it compiled successfully, the path to the .exe file should be there after {projectname}.vcxproj ->

Trying to get Laravel 5 email to work

You are getting an authentication error because the username and password in your config file is setup wrong.

Change this:

'username' => env('[email protected]'),
'password' => env('MyPassword'),

To this:

'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),

The env method checks your .env file. In your .env file you call these MAIL_USERNAME, so that's what you need to pass to the env method.

One troubleshooting tip: add dd(Config::get('mail')); so that you can see the actual generated config. This will help you spot issues like this, and know exactly what information Laravel is going to try and use. So you may want to stop that in your test route temporarily to examine what you have:

Route::get('test', function()
{
    dd(Config::get('mail'));
});

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

The only problemo with @mikemaccana's great solution is that it uses the binary >> operator which is costly, performance-wise. I suggest this modification to his great work as a slight improvement that your colleagues can perhaps read more easily.

const getColumnName = (i) => {
     const previousLetters = (i >= 26 ? getColumnName(Math.floor(i / 26) -1 ) : '');
     const lastLetter = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i % 26]; 
     return previousLetters + lastLetter;
}

Or as a one-liner

const getColumnName = i => (i >= 26 ? getColumnName(Math.floor(i / 26) -1 ) : '') + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i % 26];

Example:

getColumnName(0); // "A"
getColumnName(1); // "B"
getColumnName(25); // "Z"
getColumnName(26); // "AA"
getColumnName(27); // "AB"
getColumnName(80085) // "DNLF"

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

For MAC users

After some research, this worked for me:

  • Quit VirtualBox
  • Right click "Applications" folder
  • Click on "Get Info"
  • Change "Everyone" Permission to "Read Only"
  • Open VirtualBox, and now it should work.

Print array to a file

Quick and simple do this:

file_put_contents($filename, var_export($myArray, true));

Array to Collection: Optimized code

What about :

List myList = new ArrayList(); 
String[] myStringArray = new String[] {"Java", "is", "Cool"}; 

Collections.addAll(myList, myStringArray); 

Regular expression to get a string between two strings in Javascript

Regular expression to get a string between two strings in JavaScript

The most complete solution that will work in the vast majority of cases is using a capturing group with a lazy dot matching pattern. However, a dot . in JavaScript regex does not match line break characters, so, what will work in 100% cases is a [^] or [\s\S]/[\d\D]/[\w\W] constructs.

ECMAScript 2018 and newer compatible solution

In JavaScript environments supporting ECMAScript 2018, s modifier allows . to match any char including line break chars, and the regex engine supports lookbehinds of variable length. So, you may use a regex like

var result = s.match(/(?<=cow\s+).*?(?=\s+milk)/gs); // Returns multiple matches if any
// Or
var result = s.match(/(?<=cow\s*).*?(?=\s*milk)/gs); // Same but whitespaces are optional

In both cases, the current position is checked for cow with any 1/0 or more whitespaces after cow, then any 0+ chars as few as possible are matched and consumed (=added to the match value), and then milk is checked for (with any 1/0 or more whitespaces before this substring).

Scenario 1: Single-line input

This and all other scenarios below are supported by all JavaScript environments. See usage examples at the bottom of the answer.

cow (.*?) milk

cow is found first, then a space, then any 0+ chars other than line break chars, as few as possible as *? is a lazy quantifier, are captured into Group 1 and then a space with milk must follow (and those are matched and consumed, too).

Scenario 2: Multiline input

cow ([\s\S]*?) milk

Here, cow and a space are matched first, then any 0+ chars as few as possible are matched and captured into Group 1, and then a space with milk are matched.

Scenario 3: Overlapping matches

If you have a string like >>>15 text>>>67 text2>>> and you need to get 2 matches in-between >>>+number+whitespace and >>>, you can't use />>>\d+\s(.*?)>>>/g as this will only find 1 match due to the fact the >>> before 67 is already consumed upon finding the first match. You may use a positive lookahead to check for the text presence without actually "gobbling" it (i.e. appending to the match):

/>>>\d+\s(.*?)(?=>>>)/g

See the online regex demo yielding text1 and text2 as Group 1 contents found.

Also see How to get all possible overlapping matches for a string.

Performance considerations

Lazy dot matching pattern (.*?) inside regex patterns may slow down script execution if very long input is given. In many cases, unroll-the-loop technique helps to a greater extent. Trying to grab all between cow and milk from "Their\ncow\ngives\nmore\nmilk", we see that we just need to match all lines that do not start with milk, thus, instead of cow\n([\s\S]*?)\nmilk we can use:

/cow\n(.*(?:\n(?!milk$).*)*)\nmilk/gm

See the regex demo (if there can be \r\n, use /cow\r?\n(.*(?:\r?\n(?!milk$).*)*)\r?\nmilk/gm). With this small test string, the performance gain is negligible, but with very large text, you will feel the difference (especially if the lines are long and line breaks are not very numerous).

Sample regex usage in JavaScript:

_x000D_
_x000D_
//Single/First match expected: use no global modifier and access match[1]
console.log("My cow always gives milk".match(/cow (.*?) milk/)[1]);
// Multiple matches: get multiple matches with a global modifier and
// trim the results if length of leading/trailing delimiters is known
var s = "My cow always gives milk, thier cow also gives milk";
console.log(s.match(/cow (.*?) milk/g).map(function(x) {return x.substr(4,x.length-9);}));
//or use RegExp#exec inside a loop to collect all the Group 1 contents
var result = [], m, rx = /cow (.*?) milk/g;
while ((m=rx.exec(s)) !== null) {
  result.push(m[1]);
}
console.log(result);
_x000D_
_x000D_
_x000D_

Using the modern String#matchAll method

_x000D_
_x000D_
const s = "My cow always gives milk, thier cow also gives milk";
const matches = s.matchAll(/cow (.*?) milk/g);
console.log(Array.from(matches, x => x[1]));
_x000D_
_x000D_
_x000D_

Effect of NOLOCK hint in SELECT statements

In addition to what is said above, you should be very aware that nolock actually imposes the risk of you not getting rows that has been committed before your select.

See http://blogs.msdn.com/sqlcat/archive/2007/02/01/previously-committed-rows-might-be-missed-if-nolock-hint-is-used.aspx

Interfaces with static fields in java for sharing 'constants'

According to JVM specification, fields and methods in a Interface can have only Public, Static, Final and Abstract. Ref from Inside Java VM

By default, all the methods in interface is abstract even tough you didn't mention it explicitly.

Interfaces are meant to give only specification. It can not contain any implementations. So To avoid implementing classes to change the specification, it is made final. Since Interface cannot be instantiated, they are made static to access the field using interface name.

Specifying java version in maven - differences between properties and compiler plugin

None of the solutions above worked for me straight away. So I followed these steps:

  1. Add in pom.xml:
<properties>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
</properties>
  1. Go to Project Properties > Java Build Path, then remove the JRE System Library pointing to JRE1.5.

  2. Force updated the project.

How do you get the current project directory from C# code when creating a custom MSBuild task?

If a project is running on an IIS express, the Environment.CurrentDirectory could point to where IIS Express is located ( the default path would be C:\Program Files (x86)\IIS Express ), not to where your project resides.


This is probably the most suitable directory path for various kinds of projects.

AppDomain.CurrentDomain.BaseDirectory

This is the MSDN definition.

Gets the base directory that the assembly resolver uses to probe for assemblies.

How to pause in C?

For Linux; getchar() is all you need.

If you are on Windows, check out the following, it is exactly what you need!

kbit() function

  • kbhit() function is used to determine if a key has been pressed or not.
  • To use kbhit() in C or C++ prorams you have to include the header file "conio.h".

For example, see how it works in the following program;

//any_key.c

#include <stdio.h> 
#include <conio.h>

int main(){

    //code here
    printf ("Press any key to continue . . .\n");
    while (1) if (kbhit()) break; 
    //code here 
    return 0;

}

When I compile and run the program, this is what I see.

Only when user presses just one key from the keyboard, kbhit() returns 1.

What does FETCH_HEAD in Git mean?

I have just discovered and used FETCH_HEAD. I wanted a local copy of some software from a server and I did

git fetch gitserver release_1

gitserver is the name of my machine that stores git repositories. release_1 is a tag for a version of the software. To my surprise, release_1 was then nowhere to be found on my local machine. I had to type

 git tag release_1 FETCH_HEAD 

to complete the copy of the tagged chain of commits (release_1) from the remote repository to the local one. Fetch had found the remote tag, copied the commit to my local machine, had not created a local tag, but had set FETCH_HEAD to the value of the commit, so that I could find and use it. I then used FETCH_HEAD to create a local tag which matched the tag on the remote. That is a practical illustration of what FETCH_HEAD is and how it can be used, and might be useful to someone else wondering why git fetch doesn't do what you would naively expect.

In my opinion it is best avoided for that purpose and a better way to achieve what I was trying to do is

git fetch gitserver release_1:release_1

i.e. to fetch release_1 and call it release_1 locally. (It is source:dest, see https://git-scm.com/book/en/v2/Git-Internals-The-Refspec; just in case you'd like to give it a different name!)

You might want to use FETCH_HEAD at times though:-

git fetch gitserver bugfix1234
git cherry-pick FETCH_HEAD

might be a nice way of using bug fix number 1234 from your Git server, and leaving Git's garbage collection to dispose of the copy from the server once the fix has been cherry-picked onto your current branch. (I am assuming that there is a nice clean tagged commit containing the whole of the bug fix on the server!)

Which variable size to use (db, dw, dd) with x86 assembly?

The full list is:

DB, DW, DD, DQ, DT, DDQ, and DO (used to declare initialized data in the output file.)

See: http://www.tortall.net/projects/yasm/manual/html/nasm-pseudop.html

They can be invoked in a wide range of ways: (Note: for Visual-Studio - use "h" instead of "0x" syntax - eg: not 0x55 but 55h instead):

    db      0x55                ; just the byte 0x55
    db      0x55,0x56,0x57      ; three bytes in succession
    db      'a',0x55            ; character constants are OK
    db      'hello',13,10,'$'   ; so are string constants
    dw      0x1234              ; 0x34 0x12
    dw      'A'                 ; 0x41 0x00 (it's just a number)
    dw      'AB'                ; 0x41 0x42 (character constant)
    dw      'ABC'               ; 0x41 0x42 0x43 0x00 (string)
    dd      0x12345678          ; 0x78 0x56 0x34 0x12
    dq      0x1122334455667788  ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    ddq     0x112233445566778899aabbccddeeff00
    ; 0x00 0xff 0xee 0xdd 0xcc 0xbb 0xaa 0x99
    ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    do      0x112233445566778899aabbccddeeff00 ; same as previous
    dd      1.234567e20         ; floating-point constant
    dq      1.234567e20         ; double-precision float
    dt      1.234567e20         ; extended-precision float

DT does not accept numeric constants as operands, and DDQ does not accept float constants as operands. Any size larger than DD does not accept strings as operands.

Create ArrayList from array

Since this question is pretty old, it surprises me that nobody suggested the simplest form yet:

List<Element> arraylist = Arrays.asList(new Element(1), new Element(2), new Element(3));

As of Java 5, Arrays.asList() takes a varargs parameter and you don't have to construct the array explicitly.

Sharing link on WhatsApp from mobile website (not application) for Android

The above answers are bit outdated. Although those method work, but by using below method, you can share any text to a predefined number. The below method works for android, WhatsApp web, IOS etc.

You just need to use this format:

<a href="https://api.whatsapp.com/send?phone=whatsappphonenumber&text=urlencodedtext"></a>

UPDATE-- Use this from now(Nov-2018)

<a href="https://wa.me/whatsappphonenumber/?text=urlencodedtext"></a>

Use: https://wa.me/15551234567

Don't use: https://wa.me/+001-(555)1234567

To create your own link with a pre-filled message that will automatically appear in the text field of a chat, use https://wa.me/whatsappphonenumber/?text=urlencodedtext where whatsappphonenumber is a full phone number in international format and URL-encodedtext is the URL-encoded pre-filled message.

Example:https://wa.me/15551234567?text=I'm%20interested%20in%20your%20car%20for%20sale

To create a link with just a pre-filled message, use https://wa.me/?text=urlencodedtext

Example:https://wa.me/?text=I'm%20inquiring%20about%20the%20apartment%20listing

After clicking on the link, you will be shown a list of contacts you can send your message to.

For more information, see https://www.whatsapp.com/faq/en/general/26000030

How to develop Android app completely using python?

There are two primary contenders for python apps on Android

Chaquopy

https://chaquo.com/chaquopy/

This integrates with the Android build system, it provides a Python API for all android features. To quote the site "The complete Android API and user interface toolkit are directly at your disposal."

Beeware (Toga widget toolkit)

https://pybee.org/

This provides a multi target transpiler, supports many targets such as Android and iOS. It uses a generic widget toolkit (toga) that maps to the host interface calls.

Which One?

Both are active projects and their github accounts shows a fair amount of recent activity.

Beeware Toga like all widget libraries is good for getting the basics out to multiple platforms. If you have basic designs, and a desire to expand to other platforms this should work out well for you.

On the other hand, Chaquopy is a much more precise in its mapping of the python API to Android. It also allows you to mix in Java, useful if you want to use existing code from other resources. If you have strict design targets, and predominantly want to target Android this is a much better resource.

How to specify multiple conditions in an if statement in javascript

if((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == '')) {

        PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}

This could be one of possible solutions, so 'or' is || not !!

CGContextDrawImage draws image upside down when passed UIImage.CGImage

We can solve this problem using the same function:

UIGraphicsBeginImageContext(image.size);

UIGraphicsPushContext(context);

[image drawInRect:CGRectMake(gestureEndPoint.x,gestureEndPoint.y,350,92)];

UIGraphicsPopContext();

UIGraphicsEndImageContext();

Bootstrap push div content to new line

Do a row div.

Like this:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">_x000D_
<div class="grid">_x000D_
    <div class="row">_x000D_
        <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 bg-success">Under me should be a DIV</div>_x000D_
        <div class="col-lg-6 col-md-6 col-sm-5 col-xs-12 bg-danger">Under me should be a DIV</div>_x000D_
    </div>_x000D_
    <div class="row">_x000D_
        <div class="col-lg-3 col-md-3 col-sm-4 col-xs-12 bg-warning">I am the last DIV</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

ASP.NET Setting width of DataBound column in GridView

<asp:GridView ID="GridView1" AutoGenerateEditButton="True" 
ondatabound="gv_DataBound" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="False" width="600px">

<Columns>
                <asp:BoundField HeaderText="UserId" 
                DataField="UserId" 
                SortExpression="UserId" ItemStyle-Width="400px"></asp:BoundField>
   </Columns>
</asp:GridView>

Capturing image from webcam in java?

Some time ago I've created generic Java library which can be used to take pictures with a PC webcam. The API is very simple, not overfeatured, can work standalone, but also supports additional webcam drivers like OpenIMAJ, JMF, FMJ, LTI-CIVIL, etc, and some IP cameras.

Link to the project is https://github.com/sarxos/webcam-capture

Example code (take picture and save in test.jpg):

Webcam webcam = Webcam.getDefault();
webcam.open();
BufferedImage image = webcam.getImage();
ImageIO.write(image, "JPG", new File("test.jpg"));

It is also available in Maven Central Repository or as a separate ZIP which includes all required dependencies and 3rd party JARs.

Can I automatically increment the file build version when using Visual Studio?

Set the version number to "1.0.*" and it will automatically fill in the last two number with the date (in days from some point) and the time (half the seconds from midnight)

How to automatically redirect HTTP to HTTPS on Apache servers?

This worked for me:

RewriteCond %{HTTPS} =off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [QSA,L,R=301]

How to select a single field for all documents in a MongoDB collection?

For better understanding I have written similar MySQL query.

Selecting specific fields 

MongoDB : db.collection_name.find({},{name:true,email:true,phone:true});

MySQL : SELECT name,email,phone FROM table_name;

Selecting specific fields with where clause

MongoDB : db.collection_name.find({email:'[email protected]'},{name:true,email:true,phone:true});

MySQL : SELECT name,email,phone FROM table_name WHERE email = '[email protected]';

How to JSON decode array elements in JavaScript?

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

See the jQuery API.

php foreach with multidimensional array

Wouldn't a normal foreach basically yield the same result as a mysql_fetch_assoc in your case?

when using foreach on that array, you would get an array containing those three keys: 'id','firstname' and 'lastname'.

That should be the same as mysql_fetch_assoc would give (in a loop) for each row.

Extracting the top 5 maximum values in excel

Put the data into a Pivot Table and do a top n filter on it

Excel Demo

"Char cannot be dereferenced" error

I guess ch is a declared as char. Since char is a primitive data type and not and object, you can't call any methof from it. You should use Character.isLetter(ch).

jQuery: Wait/Delay 1 second without executing code

JavaScript setTimeout is a very good solution:

function funcx()
   {
   // your code here
   // break out here if needed
   setTimeout(funcx, 3000);
   }

funcx();

The delay function in jQuery is mostly used for delaying animations in a jQuery animation queue.

Firebase onMessageReceived not called when app in background

This is working as intended, notification messages are delivered to your onMessageReceived callback only when your app is in the foreground. If your app is in the background or closed then a notification message is shown in the notification center, and any data from that message is passed to the intent that is launched as a result of the user tapping on the notification.

You can specify a click_action to indicate the intent that should be launched when the notification is tapped by the user. The main activity is used if no click_action is specified.

When the intent is launched you can use the

getIntent().getExtras();

to retrieve a Set that would include any data sent along with the notification message.

For more on notification message see docs.

Bash: Strip trailing linebreak from output

If you want to print output of anything in Bash without end of line, you echo it with the -n switch.

If you have it in a variable already, then echo it with the trailing newline cropped:

$ testvar=$(wc -l < log.txt)
$ echo -n $testvar

Or you can do it in one line, instead:

$ echo -n $(wc -l < log.txt)

Eclipse Generate Javadoc Wizard: what is "Javadoc Command"?

Yes, it is asking for the application/executable that is capable of creating Javadoc. There is a javadoc executable inside the jdk's bin folder.

How do I create variable variables?

It should be extremely risky... but you can use exec():

a = 'b=5'
exec(a)
c = b*2
print (c)

Result: 10

datetime to string with series in python pandas

There is a pandas function that can be applied to DateTime index in pandas data frame.

date = dataframe.index #date is the datetime index
date = dates.strftime('%Y-%m-%d') #this will return you a numpy array, element is string.
dstr = date.tolist() #this will make you numpy array into a list

the element inside the list:

u'1910-11-02'

You might need to replace the 'u'.

There might be some additional arguments that I should put into the previous functions.

How to add line breaks to an HTML textarea?

You need to use \n for linebreaks inside textarea

Regex: Use start of line/end of line signs (^ or $) in different context

Just use look-arounds to solve this:

(?<=^|,)garp(?=$|,)

The difference with look-arounds and just regular groups are that with regular groups the comma would be part of the match, and with look-arounds it wouldn't. In this case it doesn't make a difference though.

Escape text for HTML

If you're using .NET 4 or above and you don't want to reference System.Web, you can use WebUtility.HtmlEncode from System

var encoded = WebUtility.HtmlEncode(unencoded);

This has the same effect as HttpUtility.HtmlEncode and should be preferred over System.Security.SecurityElement.Escape.

Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6

Per this github comment, one can disable urllib3 request warnings via requests in a 1-liner:

requests.packages.urllib3.disable_warnings()

This will suppress all warnings though, not just InsecureRequest (ie it will also suppress InsecurePlatform etc). In cases where we just want stuff to work, I find the conciseness handy.

How can I scan barcodes on iOS?

you can check ZBarSDK to reads QR Code and ECN/ISBN codes it's simple to integrate try the following code.

- (void)scanBarcodeWithZBarScanner
  {
// ADD: present a barcode reader that scans from the camera feed
ZBarReaderViewController *reader = [ZBarReaderViewController new];
reader.readerDelegate = self;
reader.supportedOrientationsMask = ZBarOrientationMaskAll;

ZBarImageScanner *scanner = reader.scanner;
// TODO: (optional) additional reader configuration here

// EXAMPLE: disable rarely used I2/5 to improve performance
 [scanner setSymbology: ZBAR_I25
               config: ZBAR_CFG_ENABLE
                   to: 0];

//Get the return value from controller
[reader setReturnBlock:^(BOOL value) {

}

and in didFinishPickingMediaWithInfo we get bar code value.

    - (void) imagePickerController: (UIImagePickerController*) reader
   didFinishPickingMediaWithInfo: (NSDictionary*) info
   {
    // ADD: get the decode results
    id<NSFastEnumeration> results =
    [info objectForKey: ZBarReaderControllerResults];
    ZBarSymbol *symbol = nil;
    for(symbol in results)
    // EXAMPLE: just grab the first barcode
    break;

    // EXAMPLE: do something useful with the barcode data
    barcodeValue = symbol.data;

    // EXAMPLE: do something useful with the barcode image
    barcodeImage =   [info objectForKey:UIImagePickerControllerOriginalImage];
    [_barcodeIV setImage:barcodeImage];

    //set the values for to TextFields
    [self setBarcodeValue:YES];

    // ADD: dismiss the controller (NB dismiss from the *reader*!)
    [reader dismissViewControllerAnimated:YES completion:nil];
   }

Skipping error in for-loop

Here's a simple way

for (i in 1:10) {
  
  skip_to_next <- FALSE
  
  # Note that print(b) fails since b doesn't exist
  
  tryCatch(print(b), error = function(e) { skip_to_next <<- TRUE})
  
  if(skip_to_next) { next }     
}

Note that the loop completes all 10 iterations, despite errors. You can obviously replace print(b) with any code you want. You can also wrap many lines of code in { and } if you have more than one line of code inside the tryCatch

Update records in table from CTE

You don't need a CTE for this

UPDATE PEDI_InvoiceDetail
SET
    DocTotal = v.DocTotal
FROM
     PEDI_InvoiceDetail
inner join 
(
   SELECT InvoiceNumber, SUM(Sale + VAT) AS DocTotal
   FROM PEDI_InvoiceDetail
   GROUP BY InvoiceNumber
) v
   ON PEDI_InvoiceDetail.InvoiceNumber = v.InvoiceNumber

How to check if "Radiobutton" is checked?

radiobuttonObj.isChecked() will give you boolean

if(radiobuttonObj1.isChecked()){
//do what you want 
}else if(radiobuttonObj2.isChecked()){
//do what you want 
}

Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

This means that you must declare strict mode by writing "use strict" at the beginning of the file or the function to use block-scope declarations.

EX:

function test(){
    "use strict";
    let a = 1;
} 

Npm Please try using this command again as root/administrator

npm cache verify

Try for newer versions of npm.

I'm using v 5.5.1 and it's working fine.

Installing J2EE into existing eclipse IDE

Step 1 Go to Help ---> Install New Software...

Step 2 Try to find "http://download.eclipse.org/webtools/updates" under work with drop down. If you find then select and install all the available updates.

If you can not find then click on Add -> Add Repository. Name: Eclipse Webtools Location: http://download.eclipse.org/webtools/updates Select all available updates and Install them.

Visit http://download.eclipse.org/webtools/updates/ for more details.

How to read all of Inputstream in Server Socket JAVA

int c;
    String raw = "";
    do {
        c = inputstream.read();
        raw+=(char)c;
    } while(inputstream.available()>0);

InputStream.available() shows the available bytes only after one byte is read, hence do .. while

How to display UTF-8 characters in phpMyAdmin?

the solution for this can be as easy as :

  1. find the phpmysqladmin connection function/method
  2. add this after database is conncted $db_conect->set_charset('utf8');

Return Bit Value as 1/0 and NOT True/False in SQL Server

Modify your query to generate the output that you want.

Try casting them to int:

select cast(bitFlag as int)

Or, if you like, use case:

select (case when bitFlag = 0 then 0 else 1 end)

How to import a single table in to mysql database using command line

All of these options are fine, if you have the option to re-export the data.

But if you need to use an existing SQL file, and use a specific table from it, then this perl script in the TimeSheet blog, with enable you to extract the table to a separate SQL file, and then import it.

The original link is dead, so it is a good thing that someone has put it instead of the author, Jared Cheney, on GitHub, in this link.

Debugging WebSocket in Google Chrome

Short answer for Chrome Version 29 and up:

  1. Open debugger, go to the tab "Network"
  2. Load page with websocket
  3. Click on the websocket request with upgrade response from server
  4. Select the tab "Frames" to see websocket frames
  5. Click on the websocket request again to refresh frames

How to insert data into elasticsearch

If you are using KIBANA with elasticsearch then you can use below RESt request to create and put in the index.

CREATING INDEX:

http://localhost:9200/company
PUT company
{
  "settings": {
    "index": {
      "number_of_shards": 1,
      "number_of_replicas": 1
    },
    "analysis": {
      "analyzer": {
        "analyzer-name": {
          "type": "custom",
          "tokenizer": "keyword",
          "filter": "lowercase"
        }
      }
    }
  },
  "mappings": {
    "employee": {
      "properties": {
        "age": {
          "type": "long"
        },
        "experience": {
          "type": "long"
        },
        "name": {
          "type": "text",
          "analyzer": "analyzer-name"
        }
      }
    }
  }
}

CREATING DOCUMENT:

POST http://localhost:9200/company/employee/2/_create
{
"name": "Hemani",
"age" : 23,
"experienceInYears" : 2
}

Cross-platform way of getting temp directory in Python

I use:

from pathlib import Path
import platform
import tempfile

tempdir = Path("/tmp" if platform.system() == "Darwin" else tempfile.gettempdir())

This is because on MacOS, i.e. Darwin, tempfile.gettempdir() and os.getenv('TMPDIR') return a value such as '/var/folders/nj/269977hs0_96bttwj2gs_jhhp48z54/T'; it is one that I do not always want.

MySQL: Insert record if not exists in table

You are inserting not Updating the result. You can define the name column in primary column or set it is unique.

Public class is inaccessible due to its protection level

This error is a result of the protection level of ClassB's constructor, not ClassB itself. Since the name of the constructor is the same as the name of the class* , the error may be interpreted incorrectly. Since you did not specify the protection level of your constructor, it is assumed to be internal by default. Declaring the constructor public will fix this problem:

public ClassB() { } 

* One could also say that constructors have no name, only a type; this does not change the essence of the problem.

Recursively find files with a specific extension

Using bash globbing (if find is not a must)

ls Robert.{pdf,jpg} 

How to trigger an event after using event.preventDefault()

The approach I use is this:

$('a').on('click', function(event){
    if (yourCondition === true) { //Put here the condition you want
        event.preventDefault(); // Here triggering stops
        // Here you can put code relevant when event stops;
        return;
    }
    // Here your event works as expected and continue triggering
    // Here you can put code you want before triggering
});

MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB

I recently created a table with 82 columns and had the same error with InnoDB. To bypass the problem we switched the table format to MyISAM as it was just used for a basic form.

Java Read Large Text File With 70million line of text

This article is a great way to start.

Also, you need to create test cases in which you read first 10k(or something else, but shouldn't be too small) lines and calculate the reading times accordingly.

Threading might be a good way to go, but it's important that we know what you will be doing with the data.

Another thing to be considered is, how you will store that size of data.

Simple way to query connected USB devices info in Python?

If you are working on windows, you can use pywin32 (old link: see update below).

I found an example here:

import win32com.client

wmi = win32com.client.GetObject ("winmgmts:")
for usb in wmi.InstancesOf ("Win32_USBHub"):
    print usb.DeviceID

Update Apr 2020:

'pywin32' release versions from 218 and up can be found here at github. Current version 227.

React with ES7: Uncaught TypeError: Cannot read property 'state' of undefined

You have to bind your event handlers to correct context (this):

onChange={this.setAuthorState.bind(this)}

How to use QueryPerformanceCounter?

I would extend this question with a NDIS driver example on getting time. As one knows, KeQuerySystemTime (mimicked under NdisGetCurrentSystemTime) has a low resolution above milliseconds, and there are some processes like network packets or other IRPs which may need a better timestamp;

The example is just as simple:

LONG_INTEGER data, frequency;
LONGLONG diff;
data = KeQueryPerformanceCounter((LARGE_INTEGER *)&frequency)
diff = data.QuadPart / (Frequency.QuadPart/$divisor)

where divisor is 10^3, or 10^6 depending on required resolution.

Apache VirtualHost and localhost

This worked for me!

To run projects like http://localhost/projectName

<VirtualHost localhost:80>
   ServerAdmin localhost
    DocumentRoot path/to/htdocs/
    ServerName localhost
</VirtualHost>

To run projects like http://somewebsite.com locally

<VirtualHost somewebsite.com:80>
     ServerAdmin [email protected]
     DocumentRoot /path/to/htdocs/somewebsiteFolder
     ServerName www.somewebsite.com
     ServerAlias somewebsite.com
</VirtualHost>

Same for other websites

<VirtualHost anothersite.local:80>
     ServerAdmin [email protected]
     DocumentRoot /path/to/htdocs/anotherSiteFolder
     ServerName www.anothersite.local
     ServerAlias anothersite.com
</VirtualHost>

Tests not running in Test Explorer

For me (not quite a solution) it was deselecting the .testsettings file in the Menu [Test]->[Test Settings]->[{current File}] to uncheck the currently used file.

In my case it starts so.

<TestSettings name="Local (with code coverage)" id="e81d13d9-42d0-41b9-8f31-f719648d8d2d" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010">
  <Deployment>
    <DeploymentItem filename="ConfigurationImportExportTest\Configurations\" />
    <DeploymentItem filename="output\Debug\" />
  </Deployment>
  <Execution>

Apparently the DeploymentItem interferes.

because this was in the Output tab:

Warning: Test Run deployment issue: The assembly or module 'Microsoft.SqlServer.Management.SqlParser' directly or indirectly referenced by deployment item 'output\Debug\' specified by the test settings was not found.
.... more of the same

It does not tell me lots.
Seems like it has to do with the way that all projects put their compilation products in a common \output\Debug folder

however that seems not to hinder it. It puts out another warning mentioning things like

A testsettings or runsettings file with `ForcedLegacyMode = TRUE or VSMDI files are not supported by MSTest-V2.

That seems to stop it.

postgresql COUNT(DISTINCT ...) very slow

I was also searching same answer, because at some point of time I needed total_count with distinct values along with limit/offset.

Because it's little tricky to do- To get total count with distinct values along with limit/offset. Usually it's hard to get total count with limit/offset. Finally I got the way to do -

SELECT DISTINCT COUNT(*) OVER() as total_count, * FROM table_name limit 2 offset 0;

Query performance is also high.

python for increment inner loop

You might just be better of using while loops rather than for loops for this. I translated your code directly from the java code.

str1 = "ababa"
str2 = "aba"
i = 0

while i < len(str1):
  j = 0
  while j < len(str2):
    if not str1[i+j] == str1[j]:
      break
    if j == (len(str2) -1):
      i += len(str2)
    j+=1  
  i+=1

How to apply a low-pass or high-pass filter to an array in Matlab?

You can design a lowpass Butterworth filter in runtime, using butter() function, and then apply that to the signal.

fc = 300; % Cut off frequency
fs = 1000; % Sampling rate

[b,a] = butter(6,fc/(fs/2)); % Butterworth filter of order 6
x = filter(b,a,signal); % Will be the filtered signal

Highpass and bandpass filters are also possible with this method. See https://www.mathworks.com/help/signal/ref/butter.html

Java Generics With a Class & an Interface - Together

Here's how you would do it in Kotlin

fun <T> myMethod(item: T) where T : ClassA, T : InterfaceB {
    //your code here
}

Delete all data rows from an Excel table (apart from the first)

This is how I clear the data:

Sub Macro3()
    With Sheet1.ListObjects("Table1")
        If Not .DataBodyRange Is Nothing Then
            .DataBodyRange.Delete
        End If
    End With
End Sub

How to use an existing database with an Android application

You can do this by using a content provider. Each data item used in the application remains private to the application. If an application want to share data accross applications, there is only technique to achieve this, using a content provider, which provides interface to access that private data.

What does LayoutInflater in Android do?

my customize list hope it illustrate concept

public class second extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.second);
//  TextView textview=(TextView)findViewById(R.id.textView1);
//  textview.setText(getIntent().getExtras().getString("value"));

    setListAdapter(new MyAdapter(this,R.layout.list_item,R.id.textView1, getResources().getStringArray(R.array.counteries)));
}

private class MyAdapter extends ArrayAdapter<String>{

    public MyAdapter(Context context, int resource, int textViewResourceId,
            String[] objects) {
        super(context, resource, textViewResourceId, objects);
        // TODO Auto-generated constructor stub
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row=inflater.inflate(R.layout.list_item,parent,false);
        String[]items=getResources().getStringArray(R.array.counteries);

        ImageView iv=(ImageView) row.findViewById(R.id.imageView1);
        TextView tv=(TextView) row.findViewById(R.id.textView1);
        tv.setText(items[position]);

        if(items[position].equals("unitedstates")){
            iv.setImageResource(R.drawable.usa);
        }else   if(items[position].equals("Russia")){
            iv.setImageResource(R.drawable.russia);
        }else   if(items[position].equals("Japan")){
            iv.setImageResource(R.drawable.japan);
        }
        // TODO Auto-generated method stub
        return row;
    }

}

}

fe_sendauth: no password supplied

I just put --password flag into my command and after hitting Enter it asked me for password, which I supplied.

How can I calculate the difference between two dates?

You can find the difference by converting the date in seconds and take time interval since 1970 for this and then you can find the difference between two dates.

How to get current language code with Swift?

It's important to make the difference between the App language and the device locale language (The code below is in Swift 3)

Will return the Device language:

let locale = NSLocale.current.languageCode

Will return the App language:

let pre = Locale.preferredLanguages[0]

Tomcat 7 "SEVERE: A child container failed during start"

I have seen this exception while tomcat started and it almost took many hours to figure out the reason. Finally I found out that there were some Spring JARs of a lower version in the lib folder in addition to the Spring jars in the Maven dependencies. The JARs in the lib were automatically added by Eclipse when I added a new Spring Rest controller. I removed those from the lib folder and then let Maven handle the JARs/dependancies and it was fine. Bottom line is if the JARS managed by maven and jars in the WEB-INF/lib causes a classpath issues, you may encounter this error.

Convert list to tuple in Python

I find many answers up to date and properly answered but will add something new to stack of answers.

In python there are infinite ways to do this, here are some instances
Normal way

>>> l= [1,2,"stackoverflow","python"]
>>> l
[1, 2, 'stackoverflow', 'python']
>>> tup = tuple(l)
>>> type(tup)
<type 'tuple'>
>>> tup
(1, 2, 'stackoverflow', 'python')

smart way

>>>tuple(item for item in l)
(1, 2, 'stackoverflow', 'python')

Remember tuple is immutable ,used for storing something valuable. For example password,key or hashes are stored in tuples or dictionaries. If knife is needed why to use sword to cut apples. Use it wisely, it will also make your program efficient.

Deleting a SQL row ignoring all foreign keys and constraints

This is the way to disable foreign key checks in MySQL. Not relevant to OP's question since they use MS SQL Server, but google search results do turn this up so here's for reference:

SET FOREIGN_KEY_CHECKS = 0;

/ Run your script /

SET FOREIGN_KEY_CHECKS = 1;

See if this helps, This is for ignoring the foreign key checks. But deleting disabling this is very bad practice.

Bootstrap 3 modal responsive

I had the same issue I have resolved by adding a media query for @screen-xs-min in less version under Modals.less

@media (max-width: @screen-xs-min) {
  .modal-xs { width: @modal-sm; }
}

enumerate() for dictionary in python

Python3:

One solution:

enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}
for i, k in enumerate(enumm):
    print("{}) d.key={}, d.value={}".format(i, k, enumm[k]))

Output:
0) enumm.key=0, enumm.value=1
1) enumm.key=1, enumm.value=2
2) enumm.key=2, enumm.value=3
3) enumm.key=4, enumm.value=4
4) enumm.key=5, enumm.value=5
5) enumm.key=6, enumm.value=6
6) enumm.key=7, enumm.value=7

An another example:

d = {1 : {'a': 1, 'b' : 2, 'c' : 3},
     2 : {'a': 10, 'b' : 20, 'c' : 30}
    }    
for i, k in enumerate(d):
        print("{}) key={}, value={}".format(i, k, d[k])

Output:    
    0) key=1, value={'a': 1, 'b': 2, 'c': 3}
    1) key=2, value={'a': 10, 'b': 20, 'c': 30}

Function names in C++: Capitalize or not?

I think its a matter of preference, although i prefer myFunction(...)

Tri-state Check box in HTML?

You could use HTML's indeterminate IDL attribute on input elements.

How do I replace part of a string in PHP?

Simply use str_replace:

$text = str_replace(' ', '_', $text);

You would do this after your previous substr and strtolower calls, like so:

$text = substr($text,0,10);
$text = strtolower($text);
$text = str_replace(' ', '_', $text);

If you want to get fancy, though, you can do it in one line:

$text = strtolower(str_replace(' ', '_', substr($text, 0, 10)));

How to save an image to localStorage and display it on the next page?

To whoever also needs this problem solved:

Firstly, I grab my image with getElementByID, and save the image as a Base64. Then I save the Base64 string as my localStorage value.

bannerImage = document.getElementById('bannerImg');
imgData = getBase64Image(bannerImage);
localStorage.setItem("imgData", imgData);

Here is the function that converts the image to a Base64 string:

function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    var dataURL = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

Then, on my next page I created an image with a blank src like so:

<img src="" id="tableBanner" />

And straight when the page loads, I use these next three lines to get the Base64 string from localStorage, and apply it to the image with the blank src I created:

var dataImage = localStorage.getItem('imgData');
bannerImg = document.getElementById('tableBanner');
bannerImg.src = "data:image/png;base64," + dataImage;

Tested it in quite a few different browsers and versions, and it seems to work quite well.

Multiple arguments to function called by pthread_create()?

Use:

struct arg_struct *args = malloc(sizeof(struct arg_struct));

And pass this arguments like this:

pthread_create(&tr, NULL, print_the_arguments, (void *)args);

Don't forget free args! ;)

Import Python Script Into Another?

It's worth mentioning that (at least in python 3), in order for this to work, you must have a file named __init__.py in the same directory.

How can I shuffle the lines of a text file on the Unix command line or in a shell script?

This is a python script that I saved as rand.py in my home folder:

#!/bin/python

import sys
import random

if __name__ == '__main__':
  with open(sys.argv[1], 'r') as f:
    flist = f.readlines()
    random.shuffle(flist)

    for line in flist:
      print line.strip()

On Mac OSX sort -R and shuf are not available so you can alias this in your bash_profile as:

alias shuf='python rand.py'

how to increase the limit for max.print in R

Use the options command, e.g. options(max.print=1000000).

See ?options:

 ‘max.print’: integer, defaulting to ‘99999’.  ‘print’ or ‘show’
      methods can make use of this option, to limit the amount of
      information that is printed, to something in the order of
      (and typically slightly less than) ‘max.print’ _entries_.

PHP String to Float

You want the non-locale-aware floatval function:

float floatval ( mixed $var ) - Gets the float value of a string.

Example:

$string = '122.34343The';
$float  = floatval($string);
echo $float; // 122.34343

Sleep function Visual Basic

Since you are asking about .NET, you should change the parameter from Long to Integer. .NET's Integer is 32-bit. (Classic VB's integer was only 16-bit.)

Declare Sub Sleep Lib "kernel32.dll" (ByVal Milliseconds As Integer)

Really though, the managed method isn't difficult...

System.Threading.Thread.CurrentThread.Sleep(5000)

Be careful when you do this. In a forms application, you block the message pump and what not, making your program to appear to have hanged. Rarely is sleep a good idea.

Difference Between Cohesion and Coupling

Simply put, cohesion means that a class should represent a single concept.

The public interface of a class is cohesive if all the class features are related to the concept that the class represents. For example, instead of having CashRegister class, having CashRegister and Coin features cohesion makes it into 2 classes - CashRegister and Coin class.

In coupling, one class depends on another as it uses the objects of the class.

The problem with high coupling is that it can create side effects. One change in one class could cause an unexpected error in the other class and could break the whole code.

Generally, high cohesion and low coupling is considered high quality OOP.

How to handle configuration in Go

I agree with nemo and I wrote a little tool to make it all real easy.

bitbucket.org/gotamer/cfg is a json configuration package

  • You define your config items in your application as a struct.
  • A json config file template from your struct is saved on the first run
  • You can save runtime modifications to the config

See doc.go for an example

Entry point for Java applications: main(), init(), or run()?

Java has a special static method:

public static void main(String[] args) { ... }

which is executed in a class when the class is started with a java command line:

$ java Class

would execute said method in the class "Class" if it existed.

public void run() { ... }

is required by the Runnable interface, or inherited from the Thread class when creating new threads.

Get column index from label in a data frame

I wanted to see all the indices for the colnames because I needed to do a complicated column rearrangement, so I printed the colnames as a dataframe. The rownames are the indices.

as.data.frame(colnames(df))

1 A
2 B
3 C

Count the number of commits on a Git branch

How about git log --pretty=oneline | wc -l

That should count all the commits from the perspective of your current branch.

How to check if that data already exist in the database during update (Mongoose And Express)

If you're searching by an unique index, then using UserModel.count may actually be better for you than UserModel.findOne due to it returning the whole document (ie doing a read) instead of returning just an int.

Convert String to double in Java

Try this, BigDecimal bdVal = new BigDecimal(str);

If you want Double only then try Double d = Double.valueOf(str); System.out.println(String.format("%.3f", new BigDecimal(d)));

Add string in a certain position in Python

This seems very easy:

>>> hash = "355879ACB6"
>>> hash = hash[:4] + '-' + hash[4:]
>>> print hash
3558-79ACB6

However if you like something like a function do as this:

def insert_dash(string, index):
    return string[:index] + '-' + string[index:]

print insert_dash("355879ACB6", 5)

How to use npm with node.exe?

Search all .npmrc file in your system.

Please verify that the path you have given is correct. If not please remove the incorrect path.

C++ Singleton design pattern

In addition to the other discussion here, it may be worth noting that you can have global-ness, without limiting usage to one instance. For example, consider the case of reference counting something...

struct Store{
   std::array<Something, 1024> data;
   size_t get(size_t idx){ /* ... */ }
   void incr_ref(size_t idx){ /* ... */}
   void decr_ref(size_t idx){ /* ... */}
};

template<Store* store_p>
struct ItemRef{
   size_t idx;
   auto get(){ return store_p->get(idx); };
   ItemRef() { store_p->incr_ref(idx); };
   ~ItemRef() { store_p->decr_ref(idx); };
};

Store store1_g;
Store store2_g; // we don't restrict the number of global Store instances

Now somewhere inside a function (such as main) you can do:

auto ref1_a = ItemRef<&store1_g>(101);
auto ref2_a = ItemRef<&store2_g>(201); 

The refs don't need to store a pointer back to their respective Store because that information is supplied at compile-time. You also don't have to worry about the Store's lifetime because the compiler requires that it is global. If there is indeed only one instance of Store then there's no overhead in this approach; with more than one instance it's up to the compiler to be clever about code generation. If necessary, the ItemRef class can even be made a friend of Store (you can have templated friends!).

If Store itself is a templated class then things get messier, but it is still possible to use this method, perhaps by implementing a helper class with the following signature:

template <typename Store_t, Store_t* store_p>
struct StoreWrapper{ /* stuff to access store_p, e.g. methods returning 
                       instances of ItemRef<Store_t, store_p>. */ };

The user can now create a StoreWrapper type (and global instance) for each global Store instance, and always access the stores via their wrapper instance (thus forgetting about the gory details of the template parameters needed for using Store).

How to align absolutely positioned element to center?

Have you tried using?:

left:50%;
top:50%;
margin-left:-[half the width] /* As pointed out on the comments by Chetan Sastry */

Not sure if it'll work, but it's worth a try...

Minor edit: Added the margin-left part, as pointed out on the comments by Chetan...

How do I create a message box with "Yes", "No" choices and a DialogResult?

DialogResult dr = MessageBox.Show("Are you happy now?", 
                      "Mood Test", MessageBoxButtons.YesNo);
switch(dr)
{
   case DialogResult.Yes:
      break;
   case DialogResult.No:
      break;
}

MessageBox class is what you are looking for.

Inserting an item in a Tuple

You can cast it to a list, insert the item, then cast it back to a tuple.

a = ('Product', '500.00', '1200.00')
a = list(a)
a.insert(3, 'foobar')
a = tuple(a)
print a

>> ('Product', '500.00', '1200.00', 'foobar')

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

Swift 3 - custom class, easy to reuse. It uses backgroundColor set in UI builder

import UIKit

@IBDesignable
class CircleBackgroundView: UIView {

    override func layoutSubviews() {
        super.layoutSubviews()
        layer.cornerRadius = bounds.size.width / 2
        layer.masksToBounds = true
    }

}

How to determine the last Row used in VBA including blank spaces in between

here is my code to find the next empty row for example in first row 'A'. To use it for any other row just change cells(i,2 or 3 or 4 so on)

Sheets("Sheeet1").Select
   for i=1 to 5000
        if cells(i,1)="" then nextEmpty=i goto 20
   next i
20 'continue your code here 

enter code here

Display JSON Data in HTML Table

As an alternative to the answers you already have, and for others that come accross this post. I recently had a similar task and created a small jquery plug in to do it for me. Its pretty small under 3KB minified, and has sorting, paging and the ability to show and hide columns.

It should be pretty easy to customize using css. More information can be found here http://mrjsontable.azurewebsites.net/ and the project is available for you to do as you wish with on github https://github.com/MatchingRadar/Mr.JsonTable

To get it to work download the files and pop them in your site. Follow the instructions and you should end up with something like the following:

<div id="citytable"></div>

Then in the ajax success method you will want something like this

success: function(data){ 
    $("#citytable").mrjsontable({
        tableClass: "my-table",
        pageSize: 10, //you can change the page size here
        columns: [
            new $.fn.mrjsontablecolumn({
                heading: "City",
                data: "city"
            }),
            new $.fn.mrjsontablecolumn({
                heading: "City Status",
                data: "cStatus"
            })
        ],
        data: data
    });
}

Hope it helps somebody else!

jquery find element by specific class when element has multiple classes

An element can have any number of classNames, however, it can only have one class attribute; only the first one will be read by jQuery.

Using the code you posted, $(".alert-box.warn") will work but $(".alert-box.dead") will not.

JS map return object

map rockets and add 10 to its launches:

_x000D_
_x000D_
var rockets = [_x000D_
    { country:'Russia', launches:32 },_x000D_
    { country:'US', launches:23 },_x000D_
    { country:'China', launches:16 },_x000D_
    { country:'Europe(ESA)', launches:7 },_x000D_
    { country:'India', launches:4 },_x000D_
    { country:'Japan', launches:3 }_x000D_
];_x000D_
rockets.map((itm) => {_x000D_
    itm.launches += 10_x000D_
    return itm_x000D_
})_x000D_
console.log(rockets)
_x000D_
_x000D_
_x000D_

If you don't want to modify rockets you can do:

var plusTen = []
rockets.forEach((itm) => {
    plusTen.push({'country': itm.country, 'launches': itm.launches + 10})
})

Python: Converting from ISO-8859-1/latin1 to UTF-8

Decode to Unicode, encode the results to UTF8.

apple.decode('latin1').encode('utf8')

How to convert an array into an object using stdClass()

If you want to recursively convert the entire array into an Object type (stdClass) then , below is the best method and it's not time-consuming or memory deficient especially when you want to do a recursive (multi-level) conversion compared to writing your own function.

$array_object = json_decode(json_encode($array));

How to pass variables from one php page to another without form?

check to make sure the variable is set. Then clean it before using it:

isset($_GET['var'])?$var=mysql_escape_string($_GET['var']):$var='SomeDefaualtValue';

Otherwise, assign it a default value ($var='' is fine) to avoid the error you mentioned.

Codeigniter: does $this->db->last_query(); execute a query?

The query execution happens on all get methods like

$this->db->get('table_name');
$this->db->get_where('table_name',$array);

While last_query contains the last query which was run

$this->db->last_query();

If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions

public function _compile_select($select_override = FALSE)
public function _reset_select()

Now you can write query and get it in a variable

$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();

Now reset query so if you want to write another query the object will be cleared.

$this->db->_reset_select();

And the thing is done. Cheers!!! Note : While using this way you must use

$this->db->from('myTable')

instead of

$this->db->get('myTable')

which runs the query.

Take a look at this example

How to convert 2D float numpy array to 2D int numpy array?

you can use np.int_:

>>> x = np.array([[1.0, 2.3], [1.3, 2.9]])
>>> x
array([[ 1. ,  2.3],
       [ 1.3,  2.9]])
>>> np.int_(x)
array([[1, 2],
       [1, 2]])

jQuery UI Dialog individual CSS styling

Run the following immediately after the dialog is called in the Ajax:

    $(".ui-dialog-titlebar").hide();
    $(".ui-dialog").addClass("customclass");

This applies just to the dialog that is opened, so it can be changed for each one used.

(This quick answer is based on another response on Stack Overflow.)

How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway

You can used Lambda as "Lambda Proxy Integration" ,ref this [https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html#api-gateway-proxy-integration-lambda-function-python] , options avalible to this lambda are

For Nodejs Lambda 'event.headers', 'event.pathParameters', 'event.body', 'event.stageVariables', and 'event.requestContext'

For Python Lambda event['headers']['parametername'] and so on

How can I reuse a navigation bar on multiple pages?

A very old but simple enough technique is to use "Server-Side Includes", to include HTML pages into a top-level page that has the .shtml extension. For instance this would be your index.shtml file:

<html>
<head>...</head>
<body>
<!-- repeated header: note that the #include is in a HTML comment -->
<!--#include file="header.html" -->
<!-- unique content here... -->
</body>
</html>

Yes, it is lame, but it works. Remember to enable SSI support in your HTTP server configuration (this is how to do it for Apache).

How to restore the menu bar in Visual Studio Code

Press Ctrl + Shift + P to open the Command Palette, then write command : Toggle Menu Bar

Which command do I use to generate the build of a Vue app?

If you've created your project using:

vue init webpack myproject

You'd need to set your NODE_ENV to production and run, because the project has web pack configured for both development and production:

NODE_ENV=production npm run build

Copy dist/ directory into your website root directory.

If you're deploying with Docker, you'd need an express server, serving the dist/ directory.

Dockerfile

FROM node:carbon

RUN mkdir -p /usr/src/app

WORKDIR /usr/src/app
ADD . /usr/src/app
RUN npm install

ENV NODE_ENV=production

RUN npm run build

# Remove unused directories
RUN rm -rf ./src
RUN rm -rf ./build

# Port to expose
EXPOSE 8080
CMD [ "npm", "start" ]

.setAttribute("disabled", false); changes editable attribute to false

Try doing this instead:

function enable(id)
{
    var eleman = document.getElementById(id);
    eleman.removeAttribute("disabled");        
}

To enable an element you have to remove the disabled attribute. Setting it to false still means it is disabled.

http://jsfiddle.net/SRK2c/

Triggering change detection manually in Angular

I used accepted answer reference and would like to put an example, since Angular 2 documentation is very very hard to read, I hope this is easier:

  1. Import NgZone:

    import { Component, NgZone } from '@angular/core';
    
  2. Add it to your class constructor

    constructor(public zone: NgZone, ...args){}
    
  3. Run code with zone.run:

    this.zone.run(() => this.donations = donations)
    

Invalid length for a Base-64 char array

The length of a base64 encoded string is always a multiple of 4. If it is not a multiple of 4, then = characters are appended until it is. A query string of the form ?name=value has problems when the value contains = charaters (some of them will be dropped, I don't recall the exact behavior). You may be able to get away with appending the right number of = characters before doing the base64 decode.

Edit 1

You may find that the value of UserNameToVerify has had "+"'s changed to " "'s so you may need to do something like so:

a = a.Replace(" ", "+");

This should get the length right;

int mod4 = a.Length % 4;
if (mod4 > 0 )
{
    a += new string('=', 4 - mod4);
}

Of course calling UrlEncode (as in LukeH's answer) should make this all moot.

Can you style html form buttons with css?

You can achieve your desired through easily by CSS :-

HTML

<input type="submit" name="submit" value="Submit Application" id="submit" />

CSS

#submit {
    background-color: #ccc;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius:6px;
    color: #fff;
    font-family: 'Oswald';
    font-size: 20px;
    text-decoration: none;
    cursor: pointer;
    border:none;
}



#submit:hover {
    border: none;
    background:red;
    box-shadow: 0px 0px 1px #777;
}

DEMO

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

Removing all script tags from html with JS Regular Expression

Whenever you have to resort to Regex based script tag cleanup. At least add a white-space to the closing tag in the form of

</script\s*>

Otherwise things like

<script>alert(666)</script   >

would remain since trailing spaces after tagnames are valid.

Rounding float in Ruby

what about (2.3465*100).round()/100.0?

How do I schedule a task to run at periodic intervals?

Use timer.scheduleAtFixedRate

public void scheduleAtFixedRate(TimerTask task,
                                long delay,
                                long period)

Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period.
In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. It is also appropriate for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another.

Parameters:

  • task - task to be scheduled.
  • delay - delay in milliseconds before task is to be executed.
  • period - time in milliseconds between successive task executions.

Throws:

  • IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is negative.
  • IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.

Pure CSS scroll animation

You can use my script from CodePen by just wrapping all the content within a .levit-container DIV.

~function  () {
    function Smooth () {
        this.$container = document.querySelector('.levit-container');
        this.$placeholder = document.createElement('div');
    }

    Smooth.prototype.init = function () {
        var instance = this;

        setContainer.call(instance);
        setPlaceholder.call(instance);
        bindEvents.call(instance);
    }

    function bindEvents () {
        window.addEventListener('scroll', handleScroll.bind(this), false);
    }

    function setContainer () {
        var style = this.$container.style;

        style.position = 'fixed';
        style.width = '100%';
        style.top = '0';
        style.left = '0';
        style.transition = '0.5s ease-out';
    }

    function setPlaceholder () {
        var instance = this,
                $container = instance.$container,
                $placeholder = instance.$placeholder;

        $placeholder.setAttribute('class', 'levit-placeholder');
        $placeholder.style.height = $container.offsetHeight + 'px';
        document.body.insertBefore($placeholder, $container);
    }

    function handleScroll () {
        this.$container.style.transform = 'translateZ(0) translateY(' + (window.scrollY * (- 1)) + 'px)';
    }

    var smooth = new Smooth();
    smooth.init();
}();

https://codepen.io/acauamontiel/pen/zxxebb?editors=0010

How to print colored text to the terminal?

There is also the Python termcolor module. Usage is pretty simple:

from termcolor import colored

print colored('hello', 'red'), colored('world', 'green')

Or in Python 3:

print(colored('hello', 'red'), colored('world', 'green'))

It may not be sophisticated enough, however, for game programming and the "colored blocks" that you want to do...

catch forEach last iteration

const arr= [1, 2, 3]
arr.forEach(function(element){
 if(arr[arr.length-1] === element){
  console.log("Last Element")
 }
})

How to fix Ora-01427 single-row subquery returns more than one row in select?

Use the following query:

SELECT E.I_EmpID AS EMPID,
       E.I_EMPCODE AS EMPCODE,
       E.I_EmpName AS EMPNAME,
       REPLACE(TO_CHAR(A.I_REQDATE, 'DD-Mon-YYYY'), ' ', '') AS FROMDATE,
       REPLACE(TO_CHAR(A.I_ENDDATE, 'DD-Mon-YYYY'), ' ', '') AS TODATE,
       TO_CHAR(NOD) AS NOD,
       DECODE(A.I_DURATION,
              'FD',
              'FullDay',
              'FN',
              'ForeNoon',
              'AN',
              'AfterNoon') AS DURATION,
       L.I_LeaveType AS LEAVETYPE,
       REPLACE(TO_CHAR((SELECT max(C.I_WORKDATE)
                         FROM T_COMPENSATION C
                        WHERE C.I_COMPENSATEDDATE = A.I_REQDATE
                          AND C.I_EMPID = A.I_EMPID),
                       'DD-Mon-YYYY'),
               ' ',
               '') AS WORKDATE,
       A.I_REASON AS REASON,
       AP.I_REJECTREASON AS REJECTREASON
  FROM T_LEAVEAPPLY A
 INNER JOIN T_EMPLOYEE_MS E
    ON A.I_EMPID = E.I_EmpID
   AND UPPER(E.I_IsActive) = 'YES'
   AND A.I_STATUS = '1'
 INNER JOIN T_LeaveType_MS L
    ON A.I_LEAVETYPEID = L.I_LEAVETYPEID
  LEFT OUTER JOIN T_APPROVAL AP
    ON A.I_REQDATE = AP.I_REQDATE
   AND A.I_EMPID = AP.I_EMPID
   AND AP.I_APPROVALSTATUS = '1'
 WHERE E.I_EMPID <> '22'
 ORDER BY A.I_REQDATE DESC

The trick is to force the inner query return only one record by adding an aggregate function (I have used max() here). This will work perfectly as far as the query is concerned, but, honestly, OP should investigate why the inner query is returning multiple records by examining the data. Are these multiple records really relevant business wise?